diff --git a/design/architecture/microservices/account-service/api-contracts.md b/design/architecture/microservices/account-service/api-contracts.md index 89c31dc784..d25cd74309 100644 --- a/design/architecture/microservices/account-service/api-contracts.md +++ b/design/architecture/microservices/account-service/api-contracts.md @@ -24,8 +24,16 @@ Supported reads and downloads, including any controlled export the product suppo Decline or missing reacceptance does not itself cancel a subscription, delete content, decide a refund, or change billing or entitlement state. Subscription and billing consequences remain independent under [ADR 0143](../../decisions/adr-0143-stripe-v1-hosting-billing-and-deferred-creator-monetization.md) and the Account subscription lifecycle; payment or continued hosting never implies hosted-terms acceptance or marketplace enrollment. Future creator commerce remains separately gated by [ADR 0179](../../decisions/adr-0179-firemud-managed-creator-commerce-boundary.md). +### Original Creator Callback Authorization + +For fresh current-actor callbacks, Account observes its existing clock after the final blocking owner operations and immediately before invoking the callback. The original ControlUI issuance must have whole-second `issuedAt = iat = nbf`, with zero skew, and one clock observation must satisfy `issuedAt <= now < expiresAt`. Account does not rewrite the token, registry cleanup deadline, source evidence, or retained order. Exact historical recovery of an already-held original order remains separate and may proceed after creator expiry. Global token profile, signature, and key contracts remain defined by [JWT and Token Contracts](../../system-architecture-jwt-and-token-contracts.md). + +For each fresh current-actor path, Account loads the existing trusted public JWKS source outside SQL transactions and synchronization. The protected snapshot must contain the immutable original signer receipt’s exact key ID and RFC 7638 fingerprint. An accepted original key may coexist with other current public keys and need not be the newest active signer. The snapshot belongs to one invocation and does not guarantee acceptance through later locks, callback, or commit. Signature/profile, active registry, historical signer provenance, and current Account source checks remain independent; the source remains unregistered. + The original Draft claim transport delegates to Account’s existing creator and retained-fence owners; a claim uses the exact same-namespace Game Design workload and protected creator credential, while the separate held-order read is restricted to the exact World workload. The [original-order proto](../../../../protos/account/v1/original_draft_order_service.proto) carries only the original operation and transport correlation; it supplies neither environment authority nor a creator credential in its body. The credential is carried in the protected binary metadata header and retains Account’s 16 KiB maximum compact creator-token bound. The shared transport codec permits 22,872 bytes of inbound metadata and a 4 MiB + 1 KiB inbound request message. Before registering `AccountOriginalDraftOrderGrpcService`, the Account receiving server must allow inbound metadata of at least `AccountOriginalDraftOrderGrpcCodec.MAX_METADATA_BYTES` and inbound request messages of at least `AccountOriginalDraftOrderGrpcCodec.MAX_WIRE_BYTES`; binding the service configures neither server limit. Held replay preserves the original binding and pending settlement rather than issuing fresh creator authority. These adapters remain unregistered, and both application profiles continue to omit permission for the RPCs. Controlled issuer, environment and PKI inputs are component proof only; caller qualification and remaining genuine authority are tracked in [Game Authoring](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#original-account-ordered-world-source-caller). +The selected-publication order adapter accepts only the exact same-namespace Game Design workload without authenticated end-user caller context, and carries the original creator credential only in protected binary metadata with an unchanged 16 KiB maximum. Its `AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES` allowance is 22,872 bytes, including base64 wire encoding and bounded metadata overhead. Any future Account receiving composition must allow that metadata size before registering `AccountSelectedDraftPublicationOrderGrpcService`; binding the service does not configure the server limit. The service remains unregistered, so this prerequisite does not configure or claim a deployed receiver. + The unregistered Draft terminal reconciler consumes the exact required Game Design and World owner readbacks outside Account transactions, then retains missing evidence through the existing Account fence repository after rechecking the original binding and ordering. Additional required v2 owners without a supported reader remain pending. It creates no new authorization or runtime access; its qualification and source-provenance limits belong to [the authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#account-terminal-settlement-continuation). Both terminal-read transports retain the complete original binding and complete owner readback. Their shared bounds are 4 MiB for the binding, 16 MiB for the complete framed owner readback (including its repeated binding and result), and 1 KiB for protobuf/request metadata. The response allowance is therefore 20 MiB plus 1 KiB; both Account clients set that inbound limit, and both owner codecs enforce the same field and wire bounds on production and consumption. Receiving-server composition must allow the request bound of 4 MiB plus 1 KiB before these currently unregistered adapters are enabled. These limits change no original bytes, outcome, owner authorization or settlement rule. diff --git a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md index 0048d2555f..24b45510ab 100644 --- a/design/architecture/microservices/automation-scripting-service/runtime-and-data.md +++ b/design/architecture/microservices/automation-scripting-service/runtime-and-data.md @@ -39,6 +39,37 @@ The current dry-run and readiness capacity reservations also are not idempotent The current queue consumer has an additional bounded-drain limitation that must remain explicit: `drainWorkItems` and `drainIndexedWorkItemPointers` consume pointers with atomic Redis `LPOP`, so a producer's concurrent `RPUSH` is not discarded by a range/read followed by deletion. The indexed path still uses database-wide `KEYS("automation:queue:*")`, and the current lists have no pointer TTL or maximum-length bound, so the path is not a cluster-safe discovery or retention proof. Durable claim fallback can process pending PostgreSQL rows independently, but it does not establish a reset/rebuild recovery gate. Target enqueue/rebuild must atomically apply `SCRIPT_OUTBOX_QUEUE_POINTER_TTL_SECONDS` and `SCRIPT_OUTBOX_QUEUE_MAX_POINTERS_PER_KEY`, preserve or durably account for unreturned tails and concurrent appends, use an owner-maintained/cursor-based cluster-safe queue index rather than database-wide `KEYS`, and trigger bounded durable re-drive with exact identity/readback before reset-gate release. The two settings remain environment/service configuration (currently `TBD`); no target support claim is valid until each environment supplies validated positive bounds and focused concurrent-drain, truncation/expiry, cluster, and re-drive proof. +The selected-source terminal reader and Account settlement composition are standalone and unregistered construction components; they do not establish complete authenticated owner intake or physical proof. The [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status) owns their code and validation status. Without the exact committed Account settlement, finalized source participation remains pending. + +## Authored Template Source Inventory + +Automation owns the source inventory declaration schema carried as authored content by a new versioned Game Design `TEMPLATE_CONFIG` source ([closed schema and reference rules](../game-design-service/game-templates.md#closed-versioned-configuration-and-references-target-state)). The Automation value schema is `automation-authored-source-inventory/v1` with exactly three required family arrays: `SCRIPT_DEFINITIONS`, `EVENT_BINDINGS`, and `SCRIPT_PATCH_SOURCES`. The current shared value accepts only explicitly authored empty arrays; omitted, null, unknown, malformed, duplicate, trailing, oversized, or nonempty input is rejected. Its canonical RFC 8785 bytes preserve the authored declaration deterministically. This declaration is content only: it is not an owner receipt, source readback, authorization, provenance, or proof of owner completeness, and cannot qualify a publication on its own. Existing `TEMPLATE_CONFIG` schema-version content is not reinterpreted as this declaration. + +The authored shape is: + +```json +{ + "schema": "automation-authored-source-inventory/v1", + "families": { + "SCRIPT_DEFINITIONS": [], + "EVENT_BINDINGS": [], + "SCRIPT_PATCH_SOURCES": [] + } +} +``` + +Script schedule definitions remain derived from script source and are not another authored family. The optional template `automation.scriptPatch` is a separate default selection of one exact patch for the same base version; its absence means no template default and does not establish an empty patch-source inventory. The declaration producer, full owner census/retention and Account terminal-settlement composition remain incomplete; the standalone terminal reader does not register or enable intake. Publication must continue to deny where complete authenticated owner evidence or physical proof is unavailable. + +An Automation selected-source intake is a distinct Account-authorized operation, not participation inferred from a Game Design-only commit. Account must first authorize the exact immutable source read; after the read, Automation must retain the original content and outcome while holding revalidated current Account authority through its local commit. The declaration must originate in a genuine authored revision of the exact selected Game Design commit. Its inventory covers script roots, every event binding and patch source, and all dependent or inbound behavior/hook references from the complete selected World and other authored inputs. An explicit empty declaration is supported only when authenticated owner evidence closes that whole selected input set and rejects conflicting or unqualified existing content. Missing producers, omitted families, unavailable rows and a tenant-wide script query are not absence proof; an unsupported nonempty input denies instead of being discarded. + +The immutable intake result retains the canonical tenant/version and selected commit, original source revision and operation, complete inventory bytes, exact Account authorization binding, original owner terminal and their digests. The result and authenticated readback are derived after the authored source commit, outside its preimage. An identical retry reads the original result; changed scope, selection, content or authorization binding conflicts rather than manufacturing a new receipt. A workload identity, creator declaration or matching digest alone is insufficient. Until the required selected-input producers and continuously held-authority proof exist, the Automation receipt cannot qualify publication, which must not substitute an empty or synthetic version marker. + +The separate [`AutomationSelectedSourceIntakeCommandService.RetainSelectedSource`](../../../../protos/automation-scripting/v1/automation_selected_source_intake_command.proto) supplies a closed schema-version-1 retention command without changing those owner checks. The receiver authenticates the exact Game Design workload against its configured namespace before decoding and rejects authenticated caller context and ambient original-Draft-order, Game Logic intake or selected-owner authorization-producer credentials. It separately denies a mismatched request namespace or ambient SQL/synchronization. Its request binds an independent nonzero transport correlation, complete original Account Automation-retention authorization bytes/digest, and the original World freeze request and acknowledgement through their existing codecs. The complete selected Draft, canonical tenant/version and namespace must agree across those bindings; original operation, fence, intake and applicable freeze identities cannot be reused as transport correlation. Success echoes the entire request and returns only the complete canonical `COMMITTED_EMPTY` receipt and digest. Changing only the transport correlation replays the same owner receipt, not another intake. The request wire bound is the 16 MiB authorization bound plus both existing 1 MiB World Account-binding bounds and 64 KiB; the response bound adds the unchanged Automation receipt bound and another 64 KiB. These wire budgets do not expand any embedded grammar or byte limit. The workload-only file-backed mTLS client pins Automation, applies a five-second deadline and rejects ambient SQL/synchronization before transport. This standalone command remains unregistered and grants no publication, source release, admission or runtime activation. + +Automation's terminal read is a separate schema-version-1 `AUTOMATION_INTAKE_TERMINAL_READ` request, authenticated only for the exact same-namespace Account mTLS peer. It carries a fresh read correlation distinct from the original operation, fence and intake request, plus the complete original authorization binding bytes and digest. The only positive terminal is the typed `COMMITTED_EMPTY` outcome, with the complete canonical immutable Automation receipt bytes and recomputed digest; an exact retry returns that same receipt even when the read correlation changes. Missing, pending, changed, corrupt or ambiguous evidence denies and is never interpreted as absence, abort or release authority. Account's settlement consequence is defined by its [selected-owner intake contract](../account-service/api-contracts.md#grpc-apis) and must preserve the same original operation under its existing source locks. + +Publication consumes this empty-only receipt only within the [canonical selected-full profile](../game-design-service/version-control.md#selected-full-publication-profile), with the original publication request/freeze binding and independent exact recipient readback. The immutable receipt and closed transport definitions do not enable arbitrary nonempty Automation source, produce genuine Account authorization, establish continuous currentness or register a runtime command. The [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) retains the implementation and controlled-proof limits. + ## Architecture and Design Notes - Executes scripts in response to world or player events received via gRPC callbacks from Game Session and other domain services. Standard lifecycle events (`onSpawn`, `onEnterRegion`, `onCommand`, and similar) are delivered as unary gRPC calls via `TriggerScriptEvent`, while tick-derived scheduling signals are driven by a gRPC streaming tick heartbeat originating from Game Session. diff --git a/design/architecture/microservices/game-design-service/ability-action-tools.md b/design/architecture/microservices/game-design-service/ability-action-tools.md index d938afe9f5..9d0bf11857 100644 --- a/design/architecture/microservices/game-design-service/ability-action-tools.md +++ b/design/architecture/microservices/game-design-service/ability-action-tools.md @@ -1,15 +1,14 @@ # Ability & Action Design Tools -This document outlines the editors for defining abilities, actions, and combat mechanics. The tooling is part of the Game Design Service and pushes finalized data to the [Game Logic Service](../game-logic-service/README.md) during version publishing. +This document outlines the Game Design editors for authored ability and action inputs. Game Design owns these authored inputs, their revision history, and the frozen source-bound rule inventory. Game Logic owns validation and immutable retention of the selected inventory through authenticated intake, then consumes the rules from the published, pinned release at runtime. The owner handoff and publication boundary are defined by [Game Design Version Control](version-control.md#selected-full-publication-profile) and [Game Logic Runtime and Data](../game-logic-service/runtime-and-data.md#selected-release-rule-inputs-and-intake). The publish workflow is part of the durable control-plane workflow described in [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). ## Implementation Status -The current proven behavior is stable-reference validation against the exact published base version for the plugin publication path. `abilitySchemaDigest` is persisted in plugin metadata and exposed by the publication read, but dedicated Game Logic-owned release-attested ability-schema validation remains target-state and unproved. Current plugin publication and activation compare the plugin's `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; that aggregate comparison is not a dedicated ability-schema attestation. Script-patch publication does not currently enforce same-tenant published-base identity, and launch resolution does not currently prove same-base published patch identity or Automation `READY`; those are implementation gaps. Exact `scriptPinEpoch` propagation and same-version old-epoch rejection at runtime handoff are target-state and remain unproved; this design-time editor does not establish that runtime proof. See the [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#script-transition-reconciliation) and [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). +The selected gameplay-rule intake and receipt path remain standalone and unregistered, and public fresh/PENDING full-version publication denies before mutation; see the [gameplay-rule retention tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [Game Authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation). The current proven behavior is stable-reference validation against the exact published base version for the plugin publication path. `abilitySchemaDigest` is persisted in plugin metadata and exposed by the publication read, but dedicated Game Logic-owned release-attested ability-schema validation remains target-state and unproved. Current plugin publication and activation compare the plugin's `abilitySchemaDigest` with the published `AUTOMATION_SCRIPTING` aggregate participant digest; that aggregate comparison is not a dedicated ability-schema attestation. Script-patch publication does not currently enforce same-tenant published-base identity, and launch resolution does not currently prove same-base published patch identity or Automation `READY`; those are implementation gaps. Exact `scriptPinEpoch` propagation and same-version old-epoch rejection at runtime handoff are target-state and remain unproved; this design-time editor does not establish that runtime proof. See the [Automation and Scheduler Runtime tracker](../../../project-management/implementation-tracking/automation-and-scheduler-runtime.md#script-transition-reconciliation) and [Versioning & Runtime Configuration](../../system-architecture-versioning-runtime.md). -Data entered in these editors is stored as revisions using the `SaveRevision` gRPC call defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). -Finalized versions are published with `PublishVersion` so the Game Logic Service can load the rules as part of the cross-service publish workflow described in the [Game Design Service Architecture](README.md). +Data entered in these editors is stored as Game Design revisions using the `SaveRevision` gRPC call defined in [`game_design_service.proto`](../../../../protos/game-design/v1/game_design_service.proto). `PublishVersion` coordinates validation and finalization of existing owner data; it does not copy or repair authored rules in Game Logic. The exact selected inventory is handed to Game Logic through its authenticated source-intake operation before the publication digest gate, as defined by the owner contracts linked above. Ability definitions use a structured schema delivered through the API. @@ -121,7 +120,7 @@ Example: if an `onInterval` combat-support handler can branch into at most eight At runtime, a published game version ties together: -- Ability/action definitions owned by the Game Logic Service. +- Ability/action definitions authored by Game Design and consumed by Game Logic from the published, pinned release. - Script and plugin patch versions owned by the Automation & Scripting Service. Within a given published game version: @@ -165,7 +164,7 @@ From an observability perspective, live script and plugin invocations (`isDryRun 1. Abilities and actions are created in the web UI and saved via `SaveRevision`. 2. Designers can group related abilities into categories for organization. 3. Each revision becomes part of a published version through `PublishVersion`. -4. When a version is published, abilities are copied to the Game Logic Service using the `version_id`. +4. Game Logic validates and immutably retains the exact source-bound ability/action selection through authenticated intake before the publication digest gate; `PublishVersion` does not copy or repair these definitions. ## Related Documentation diff --git a/design/architecture/microservices/game-logic-service/runtime-and-data.md b/design/architecture/microservices/game-logic-service/runtime-and-data.md index f9812c20b9..ab5fe9f0f1 100644 --- a/design/architecture/microservices/game-logic-service/runtime-and-data.md +++ b/design/architecture/microservices/game-logic-service/runtime-and-data.md @@ -8,14 +8,14 @@ The prepared selected gameplay-rule intake repository, terminal owner and public The sections below define the target-state runtime contract. Current implementation and proof status is: -- The current implementation attests an empty owned-rule manifest and returns synthetic `appliedCommitId = "version:"` because Game Logic does not yet own version-scoped draft rule tables. The empty-manifest digest is intentional and does not represent hidden service state. +- The default Spring digest composition denies full-version reads because its retained publication source reader is not configured. An explicitly composed reader can validate exact retained intake evidence; missing source or receipt never produces an empty-manifest fallback or synthetic `version:` commit. This does not register or enable publication. The [selected intake tracker](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#selected-gameplay-rule-retention-and-receipt-composition) and [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-full-owner-publication-preparation) retain detailed execution attribution and remaining proof limits. - Same-type Game Logic takeover behind an existing edge connection is target behavior, but suppression of a client-visible reconnect after an ordinary qualifying Game Logic restart remains implementation or proof debt under ADR 0013. - Target: `SendCommunication` and every other player-delegated gameplay RPC propagate one complete, validated typed `PlayerExecutionContext` from Game Session through Game Logic and onward. Game Logic validates the context against request and owner evidence, never treats caller-supplied identifiers as authority, remains stateless, and owns semantic gameplay outcomes; Game Session owns session, reconnect, and presentation state. This is the ADR 0024 target contract. - Current implementation gap: the live `SendCommunicationRequest` is still a flat schema with tenant/session/character/account, communication/text and target metadata, room, game-instance, speaker, and effect fields plus legacy `session_attestation`; its current proto does not carry typed `playableStateNamespaceId`, `playableStateScope`, region/epoch, pointer, or admitted-bundle fields. Complete typed-context propagation is therefore not current behavior or proof. ## Runtime Notes -- Stateless service accessed over gRPC by other microservices. +- Stateless gameplay execution accessed over gRPC by other microservices; immutable authored-source intake evidence is durable owner storage, not process-local player or session state. - No authoritative gameplay state may exist only in Game Logic process memory. Any state that must survive instance loss belongs in authoritative domain services, durable ledgers, or Game Session-owned coordination, so another Game Logic instance can take over immediately. - Same-type Game Logic instances must be freely replaceable behind the current caller connection. Meaningful gameplay state needed after a non-edge restart must be reconstructed from authoritative service APIs and Game Session-provided tick/session context rather than preserved only in local memory. - Uses a modular command parser for extensibility. The text protocol's system commands such as `LOGIN`, `LOGON`, and `PING` are interpreted and completed by Game Session; this service focuses on gameplay commands only, as described in the [Game Session Service](../game-session-service/protocols.md#minimal-text-command-protocol). @@ -34,21 +34,70 @@ The sections below define the target-state runtime contract. Current implementat The Game Logic Service does not orchestrate or own synchronous saga or Temporal workflows. All gameplay commands execute inside ticks using Redis-based rollback and the transaction model described in [Transaction Strategies](../../system-architecture-transactions.md). -When a game version is published, its rule data is prepared and finalized by the Game Design and Game Session services; this service reads the already-published, versioned rule data for the active `runtime_version` and does not participate directly in the durable `publish` workflow. +Before the publication digest gate, Game Design supplies authored inputs through the separate authenticated intake below, and Game Logic validates and immutably retains that exact selection. Publication reads the retained evidence without creating or repairing it. Game Session owns runtime orchestration; it does not replace Game Logic's rule-input retention authority. Runtime consumption is limited to the published, pinned release for the active `runtime_version`. Role classification: Game Logic is a digest-gate participant for full publishes, not a workflow-step participant, unless future publish workflows add explicit finalize or compensation steps owned by this service. ## Draft Digest Contract -For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. It must expose `GetDraftDesignDigest(tenantId, versionId)` and publish a service-local digest input manifest with: +For full-version publish gating, this service is still a required digest participant even though it does not orchestrate publish-workflow steps. Its authenticated `GetDraftDesignDigest` read binds the publication request and exact retained selection below, rather than selecting content by tenant and version alone, and publishes a service-local digest input manifest with: -- included objects such as version-scoped rule and configuration tables this service owns that affect runtime command behavior; +- included objects and source ownership for the complete effective, version-scoped set of supported command inputs that affect runtime command behavior; - excluded objects such as runtime queues, caches, telemetry tables, and other non-launchability data; - canonicalization rules covering stable ordering, normalization, and null or default handling before hashing; and - `digestSchemaVersion` bump criteria, where any include, exclude, or canonicalization change requires an explicit schema bump and replay or re-record workflow. Publish gating must fail closed if this service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. +### Selected-Release Rule Inputs and Intake + +This is the Game Logic owner contract under the canonical [selected-full publication profile](../game-design-service/version-control.md#selected-full-publication-profile). It defines required target behavior; the implementation-status section and linked trackers describe what is implemented or proved. + +Game Design remains the authoring and revision-history owner for authored gameplay rule inputs. Game Logic owns validation and immutable retention of the selected release's rule-input evidence, and attests only the exact selected tenant, version, and applied commit received through an authenticated, operation-bound source operation. A workload identity by itself does not authorize that mutation; the current authority and the source operation's mutation authorization must remain bound through commit. The producer handoff and retained manifest are target behavior and are not established by the current digest receiver. + +The retained input set must be complete for the supported command inputs effective in that version. It includes supported ability and action definitions and the referenced actor-state, resource, condition, and effect catalogs; command and action metadata including admission tags; disposition and continuous-overlay policy; observation, targeting, target-selection, and default target-set bindings; and cost, cooldown, feedback, or lifecycle declarations when they are part of the selected authoritative source. The authoring shapes and ownership remain defined by [Ability & Action Design Tools](../game-design-service/ability-action-tools.md) and the owning domain contracts. This list defines the completeness boundary, not a new wire schema or an additional execution engine. Unknown or unsupported authored inputs make intake and attestation fail closed; they must not be filtered out to produce an apparently empty or partial manifest. + +Intake is a separate, mutation-authorized source operation. `GetDraftDesignDigest` remains a read-only full-version publication read over the already retained, exact-version evidence; it does not populate or repair that evidence. An empty selected input set is attestable only when an authenticated source operation proves the complete owner inventory for the exact selected commit is empty. Missing storage, a missing producer, or absent rows are not evidence of an empty authored set. + +The content-selection binding is distinct from the unchanged `publicationDigestRequest/v1` authorization/replay context. Its `game-logic-publication-source-read/v1` preimage consists of exactly three unsigned canonical ASCII byte-length frames, in order: the UTF-8 schema name, the exact existing publication request canonical preimage, and the complete original finalized Account Game Logic intake authorization bytes retained by Game Design's immutable selected receipt. Lengths use canonical decimal digits followed by `:` and exactly that many bytes; missing, extra, trailing or noncanonical frames deny. Segment and total limits, including framing and transport overhead, must be enforced before allocation. Hash the exact bytes using the existing SHA-256 representation and freeze executable preimage/hash vectors. This binding selects content; it creates no read or mutation authority and does not reinterpret the shared publication schema. + +Game Design derives that binding only from its immutable selected receipt, never from caller-selected historical authorization or latest state. Game Logic authenticates the exact Game Design workload and publication method before decoding, independently validates both bindings, then reads the exact genuine retained intake operation and its successful terminal. The complete authorization, canonical tenant/version, selected commit and source must agree byte-for-byte with retained owner evidence. Authorization bytes and digest alone prove neither Account issuance nor successful retention. The numeric Game Design Version row in the unchanged publication scope must agree with the original selected binding's persisted target; retain its canonical UUID and source-row provenance rather than inventing a UUID/numeric alias. + +The response binds the complete original lookup, source and commit provenance, positive participant schema/canonicalization evidence, aggregate digest and dedicated ability-schema digest. Game Design exact-checks each before recording an attestation. Missing or mismatched retained evidence denies; there is no tenant/version-only or latest fallback, read-side repair, fresh mutation reauthorization of historical intake, or reuse of the Account-only terminal-read permission for Game Design. Game Logic is not a script-patch participant. This selection plumbing does not establish complete source/settlement or final release-attestation proof; current construction and proof limits remain in the [authoring tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#current-status). + +The original Game Design author operation settles before this intake. Game Logic obtains the complete synchronized source from Game Design's authenticated exact-commit owner read and verifies a distinct [Account intake authorization](../account-service/api-contracts.md#grpc-apis) for that same immutable source. That exact finalized authorization also accompanies its [operation-authorized source read](../game-design-service/api-contracts.md#operation-authorized-gameplay-source-read); Game Logic cannot reuse Account's preliminary read-only branch or omit independent Account readback. It does not retrospectively join the original Draft's participant vector or allocate another selected commit. Account source participation remains held through Game Logic's local commit and exact terminal settlement; a remote `HELD` sample alone is insufficient. Retained source, complete manifest/provenance and the immutable intake result commit atomically. A definitive abort uses the same operation serialization and prevents later retention; missing rows or expired waits do not prove abort. Identical recovery returns the original result, never a latest source or replacement manifest. These obligations do not make Game Logic a publication-workflow mutation participant. + +The standalone [`RetainGameplayRuleIntake`](../../../../protos/game-logic/v1/gameplay_rule_intake_service.proto) transport admits only verified same-namespace Game Design, authenticated before decoding. It invokes the existing distinct-order intake, not publication authorization. Exact namespace, independent transport correlation and complete original authorization bytes/digest are echoed with the immutable original terminal; both retained and definitive-abort retries preserve their original outcome. The client verifies Game Logic's workload and exact response binding. Game Design obtains the subsequent settlement receipt through the [Account-owned settlement transport](../account-service/api-contracts.md#grpc-apis), never by calling the Account-only terminal reader. Intake and terminal adapters remain standalone and unregistered; their existence does not establish a genuine authorization producer or publication completion. The intake owner rejects the canonical original Draft and Game Logic intake-authorization credential contexts; those creator credentials do not accompany the owner-to-owner intake. Player or operator context supplies no intake mutation authority. + +The authenticated publication read must preserve the exact source-operation and selected-commit correlation through its retained-manifest lookup and readback. Validating the publication request and then resolving content by tenant/version alone is insufficient when it can select a different source operation; neither a latest lookup nor request authentication repairs missing immutable provenance. + +The full-version manifest and the dedicated `abilitySchemaDigest` share the selected commit and Game Logic's existing canonicalization and `digestSchemaVersion` contract, but they attest distinct scopes. The aggregate full-manifest `contentDigest` is not an ability-schema digest, and neither the Automation & Scripting digest nor Game Design's control-plane digest substitutes for either Game Logic attestation. Any change to the dedicated ability-schema input set or its canonicalization requires the same explicit schema bump and digest replay or re-record process as other manifest changes. This contract governs publication evidence only; it does not authorize activation of unpublished rules or make Game Logic a participant in Game Design's publication workflow mutations. Game Logic does not read an admin database for runtime rules. + +### Dedicated Ability-Schema Projection v1 + +The dedicated content preimage is RFC 8785 canonical UTF-8 JSON with exactly `{"schema":"gameplay-ability-schema/v1","families":{...}}`. `families` contains all 15 names in the closed `gameplay-rule-manifest/v1` grammar, including explicit empty arrays. Validate the complete selected manifest before projecting: unknown fields or definitions, missing families, unresolved references and unsupported shapes fail even outside the selected closure. Seed every `ABILITIES` and every `ACTIONS` definition, then retain the complete typed-reference closure keyed by `(family, logical key)`. Preserve every field of each retained definition, its original selected-manifest family order, and every nested-array order. A visited set terminates reachable cycles while retaining all reachable definitions; this does not establish execution support for an otherwise unsupported cycle. + +The closed grammar's reference edges are exhaustive: + +| Definition family | Typed reference edges | +| --- | --- | +| `ABILITIES` | `actionSequenceId` → `ACTIONS`. | +| `ACTIONS` | `admissionTags` → `ADMISSION_TAGS`; target sets → targeting/selection policies and optional unresolved feedback; costs → `RESOURCES`; effect bindings → `EFFECTS`; `feedbackKeys` → `FEEDBACK`. | +| `CONDITIONS` | `effectKeys` → `EFFECTS`. | +| `EFFECTS` | `statKey` → declared numeric `STATS` or `RESOURCES`; `ADJUST_RESOURCE` and `MAXIMUM` require `RESOURCES`; `conditionKey` → `CONDITIONS`. | +| `OBSERVATION_POLICIES` | Predicate references below. | +| `TARGETING_POLICIES` | `observationPolicyKey` → `OBSERVATION_POLICIES`; eligibility predicate references; `safeFailureFeedbackKey` → `FEEDBACK`. | +| `SELECTION_POLICIES` | Comparator `statKey` → numeric `STATS` or `RESOURCES`; `MAXIMUM` requires `RESOURCES`. | +| `DISPOSITIONS` | `deniedAdmissionTags` → `ADMISSION_TAGS`; `safeFeedbackKey` → `FEEDBACK`. | +| `COMMANDS` | `actionSequenceId` → `ACTIONS`; `admissionTags` → `ADMISSION_TAGS`; commands are not roots or reverse dependencies. | +| `CONTINUOUS_OVERLAYS` | Eligibility predicate references; `deniedAdmissionTags` → `ADMISSION_TAGS`; `effectKeys` → `EFFECTS`. | +| `DEFAULT_BINDINGS` | Target sets → targeting/selection policies and optional unresolved feedback. | +| `STATS`, `RESOURCES`, `ADMISSION_TAGS`, `FEEDBACK` | No external definition references. Their complete fields, tags and feedback arguments remain retained when reached. | + +Target-set policy fields are `targetingPolicyKey` → `TARGETING_POLICIES`, `targetSelectionPolicyKey` → `SELECTION_POLICIES`, and non-null `unresolvedFeedbackKey` → `FEEDBACK`. Predicate operands are traversed recursively: `STAT_COMPARE.factKey` selects its declared numeric stat/resource; `CONDITION_PRESENT.factKey` → `CONDITIONS`; `DISPOSITION_EQUALS.factKey` → `DISPOSITIONS`. `SOURCE` and declared target-set keys are action-local, not catalog aliases. Cooldown keys, names, tags, player-selector slots and feedback argument/message identifiers create no guessed external edges. The closed grammar rejects stat/resource key collisions before resolving a numeric reference. Unreferenced catalogs, commands, overlays and default bindings stay outside this dedicated digest, while remaining in the aggregate manifest. An effective implicit runtime dependency not expressible by this grammar must be reported and denied, not silently omitted or guessed from names. + +Hash these exact bytes with the existing lowercase `sha256:` encoding. Carry the positive participant `digestSchemaVersion`, canonicalization evidence and exact selected-commit/source-operation provenance separately; source/auth receipts, publication metadata and commit IDs never enter this content-only preimage. A valid explicit-empty manifest has a defined content hash but cannot establish authenticated empty-source provenance: the original complete owner inventory and immutable intake must independently prove it. The executable [projection vectors](../../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GameplayAbilitySchemaProjectionTest.java) freeze empty preimage/hash `sha256:0207783645e944996b4f7589d2662d5b8309231769681e162ee05de51d34db2a` and the complete two-action/all-root preimage/hash `sha256:659a321a8fd1a02a4825a81568d67dee5039a1cb538756fb91c212aeaea1c536`, plus transitive-field, ordering, unrelated-input and negative cases. Any include/exclude, edge or canonicalization change requires the existing explicit schema bump and replay/re-record process; do not reinterpret retained evidence. Projection construction alone does not register the digest receiver, authorize publication or activate gameplay. + ## Redis Role and Prefixes ### Coordination Redis diff --git a/design/architecture/system-architecture-asset-store-runbook.md b/design/architecture/system-architecture-asset-store-runbook.md index 5aa44b6e28..4cf8f36e0a 100644 --- a/design/architecture/system-architecture-asset-store-runbook.md +++ b/design/architecture/system-architecture-asset-store-runbook.md @@ -2,28 +2,26 @@ This runbook describes operational procedures for the **asset store** backing game content (binary design assets such as icons, audio, themes, and exported bundles). -For the architecture of asset storage, see `design/architecture/microservices/game-design-service/asset-storage.md`. +The canonical contract is [Asset Storage Setup](./microservices/game-design-service/asset-storage.md). Game Design owns publication coordination, release descriptors, asset lifecycle, CAS state, and purge eligibility. Platform Operations owns MinIO/object-storage, CDN, credentials, availability, and delivery infrastructure. Operators use the Game Design control-plane evidence for lifecycle decisions; bucket listings and CDN responses are not lifecycle authority. ## Implementation Status -- `CanDeleteVersionAssets`, `GetVersionAssetArtifactState`, `RepairPublishedVersionAssets`, `TombstoneVersionAssets`, `BeginPurgeVersionAssets`, `FinalizePurgeVersionAssets`, and `GetVersionAssetPurgeStatus` are live Game Design control-plane APIs. The `version_asset_artifact` proof row currently records lifecycle state, state epoch, manifest hash, exported version number, and exported manifest asset keys. In the current first slice, `RepairPublishedVersionAssets` repairs ordinary assets from `game_assets.data` to those persisted exported version-scoped keys only while the process-local frozen version selection remains available; the proof row alone is not restart-safe, and an unavailable selection fails closed with `REPAIR_VERSION_SCOPE_UNAVAILABLE`. -- Content-addressed private-candidate publication and producer-owned derived-artifact handoff remain target-state. The current first slice still repairs ordinary bytes from `game_assets.data`, exports version-scoped objects, and persists a narrower `published_release_bundle` that lacks the complete target manifest-schema and mandatory actual-byte artifact-digest fields. -- The live `TombstoneVersionAssets` implementation accepts only `FAILED` and `PURGE_FAILED`; target tombstoning of an eligible retired `PUBLISHED` release is not implemented. The runbook must fail closed for that path rather than claim the current API supports it. -- The target failed-candidate path requires the Game Design-owned, idempotent `AbandonFailedVersionAssets` record/read proof bound to the caller tenant, `FAILED` version/artifact epochs, request identity/digest, and no release reachability. That abandonment record/API is not implemented; the current tombstone path does not enforce it. -- The current `CanDeleteVersionAssets` implementation has a fail-open gap: when the artifact exists but no caller-tenant version authority exists (including when only a wrong-tenant row exists), and no caller-tenant release bundle remains, it can return `deletable=true`. Operators must treat both absent and wrong-tenant-only authority as non-eligible and must not tombstone or purge until this guard is closed; the owning target contract and focused proof are tracked in [Asset Storage](./microservices/game-design-service/asset-storage.md#deletion-eligibility-authority). -- Lifecycle CAS/lock serialization described below is target-only. The current repositories compare artifact/Version epochs in service memory and then update each row by ID without an epoch predicate or affected-row check; neither update is concurrency-safe and neither proves serialization against a competing lifecycle writer. This blocks using `expectedVersionStateEpoch` as durable abandonment/retirement invalidation proof. -- The live `CompareAndSetVersionState` operation has an additional transition-safety gap: it accepts any non-null lifecycle enum after its in-memory epoch check, without requiring a committed release bundle/artifact for `DRAFT -> PUBLISHED` or enforcing active-instance/template/in-flight-activation predicates before retirement. Operators must not treat this API as activation- or retirement-safe until the legal transition matrix and focused proof are implemented. -- The target destructive lifecycle operations share the ADR 0048 owner-local operation envelope and durable result ledger: caller-supplied operation/workflow identity, canonical `mutationDigest/v1`, exact replay, and `IDEMPOTENCY_CONFLICT` for changed input. The current first slice has no shared ledger/digest contract; `BeginPurgeVersionAssets` still mints a random workflow ID, so lost responses cannot be reliably replayed. -- Purge failure status is not currently durable: `FinalizePurgeVersionAssets` saves `PURGE_FAILED`/failed-workflow markers and rethrows inside `@Transactional`, so rollback can discard the markers after object deletion. A resulting `PURGE_IN_PROGRESS` row has no reliable resume evidence until an independent durable failure/reconciliation boundary and focused deletion/post-delete-save proof are added. -- If publish fails after `published_release_bundle` may have committed, target recovery reads back bundle/attestation state and never deletes Version as compensation. The current catch path still attempts that delete; the non-cascading bundle foreign key can make the delete fail, so the promised terminal result is not reliable. -- The current first slice has one `ASSET_STORE_ENDPOINT` used by the S3 client and generated manifest URLs; it does not implement the target private-origin/public-delivery split or `ASSET_STORE_PUBLIC_BASE_URL`. The current Gateway has no `/assets/**` route or asset-store route ID, and private MinIO is not public delivery; target `/assets/**` delivery remains deferred pending a separate approved public origin/provisioner. +The canonical current implementation and remaining lifecycle gaps are maintained in [Asset Storage Setup](./microservices/game-design-service/asset-storage.md#implementation-status). Operators must distinguish the implemented source and object-writer checks from physical deployment proof: + +- Repair reads the durable per-version export snapshot twice and compares the selections. It reads the retained export candidate, stages and verifies the original source bytes, and checks the candidate against the published release attestation before shared object writes. Missing or mismatched evidence fails closed; repair does not fall back to a new tenant-wide selection after process loss. +- The exporter writes schema-versioned manifests and content-addressed artifact objects, uses conditional object creation, and verifies exact byte readback. These code paths do not establish physical S3/MinIO proof, a deployed public origin, complete release-attestation transport, global publication/purge fencing, or producer-owned derived-artifact handoff. +- Purge eligibility requires an existing caller-tenant `RETIRED` Version, including when no release bundle remains. Artifact-row updates use an epoch predicate and require one affected row, but Version lifecycle serialization and the complete reachability fence remain incomplete. State-changing `CompareAndSetVersionState` requests fail closed; that API cannot substitute for retirement. +- Prefix-based object deletion is hard-disabled with `CONTENT_ADDRESSED_PURGE_PROOF_REQUIRED`. The exposed purge workflow is not a supported physical deletion procedure. Destructive-operation replay, durable purge-failure reconciliation, failed-candidate abandonment and retired-release tombstoning remain incomplete; preserve their owner-defined stop conditions. +- Private publish-failure handling retains the Version row and marks failure only after exact owner-local absence or empty staged-candidate readback. Committed, partial, mismatched or ambiguous evidence remains pending for reconciliation. This does not prove external-write recovery or make fresh full-version publication ingress available. +- Upload ingress refuses before file access or persistence because Account commit-bound authority is not wired. Existing source bytes remain retained. Generated links use a separately validated public base URL, but no public `/assets/**` origin, Gateway route or approved provisioner is implemented. Private MinIO remains private storage. +- Production attestation and lifecycle reads authenticate their exact candidate peers and deny before owner access pending genuine operation-specific authority. The separate operator-diagnostic read path remains unimplemented; source-local repair and readback code does not authorize an operator RPC invocation. See [launch and attestation read authorization](./microservices/game-design-service/version-control.md#launch-and-attestation-read-authorization-target-state). ## Health Checks - Monitor storage availability, latency, and error rates. -- Verify supported Game Design uploads and the persisted Game Design artifact/bundle metadata reads used by the current repair path. Game Design does not currently expose a version-asset object-store GET/HEAD or byte-readback operation; current repair re-exports from the process-local frozen snapshot and fails closed after process loss. Client-facing asset download remains target-only because the approved public `/assets/**` origin is not implemented. +- Preserve available owner-local artifact, snapshot, candidate and bundle evidence for an independently authorized investigation; current production read denial is not a health-check bypass. The internal exporter performs exact object-byte readback, but there is no client-facing asset download or operator object-byte GET/HEAD API. Upload admission remains denied, and public delivery remains unproved. Do not use a publication or repair mutation as a health probe. ## Incident Handling @@ -33,7 +31,7 @@ Game Design owns publication coordination, release descriptors, asset lifecycle, 2. **Degraded Performance** - Monitor throughput and latency; consider scaling the asset store or caching layers if documented. 3. **Data Integrity Concerns** - - **Target-state integrity check:** Verify the attested manifest digest and mandatory per-object SHA-256 content digests against delivery evidence. Missing object digests, mutable delivery keys, or an unattested manifest are publish contract violations; storage availability never makes a candidate launchable. The current first slice exposes only persisted `manifestHash`, exported manifest asset keys/version, and artifact/bundle metadata reads; it has no Game Design object-byte GET/HEAD or readback operation, and its narrower release bundle has no `artifactDigests[]`, so operators must not claim current actual-byte attestation from this check. + - **Target-state integrity check:** Verify the attested manifest digest and mandatory per-object SHA-256 content digests against delivery evidence. Missing object digests, mutable delivery keys, or an unattested manifest are publish contract violations; storage availability never makes a candidate launchable. The current exporter retains content-addressed candidate proofs and performs internal exact-byte readback. The release-bundle transport still lacks the complete target `artifactDigests[]`; operators must not synthesize missing attestation fields or treat internal readback as public delivery proof. - Coordinate with backup and recovery procedures if persistent corruption is suspected. ## MinIO Deployment and Configuration @@ -93,11 +91,11 @@ When using a self-hosted MinIO cluster as the asset store: - Once the trusted bootstrap has provisioned `firemud-assets-writer`, the Game Design Service is the **sole writer** to the asset bucket and uses `ASSET_STORE_*` environment variables to export assets and manifests during publish workflows. Target runtime services and clients consume published assets via CDN or gateway URLs derived from the manifest; they do not write directly to the bucket. The current private MinIO endpoint is not public delivery. - Keep the bucket private. The gateway or CDN origin uses authenticated object-store credentials and exposes only attested immutable published objects; private staging, quarantine, `FAILED`, and `EXPORTED_UNATTESTED` objects must not be publicly readable. - `ASSET_STORE_ENDPOINT` is the private authenticated MinIO/S3 API used by Game Design reads and writes, for example `http://minio:9000` inside the cluster. It is never the public gateway delivery URL. - - The target split uses `ASSET_STORE_PUBLIC_BASE_URL=https:///assets` only to generate public manifest links. That setting is not implemented in the current single-endpoint first slice; target `/assets/**` delivery remains pending a separate approved public origin/provisioner. Operators must not compensate by granting anonymous bucket-wide access. Any future public origin must expose only attested immutable published objects. + - `ASSET_STORE_PUBLIC_BASE_URL=https:///assets` generates manifest links separately from the private endpoint. The exporter validates its HTTPS `/assets` shape and rejects a host alias of the private endpoint; this setting does not deploy or authorize an origin. Target `/assets/**` delivery remains pending a separate approved public origin/provisioner. Operators must not compensate by granting anonymous bucket-wide access. Any future public origin must expose only attested immutable published objects. - Keep validation paths distinct: an unauthenticated GET to the private `ASSET_STORE_ENDPOINT` must be rejected, while a public-origin delivery test may request only an attested immutable published object. 5. **Scope of stored data** - The asset store holds only binary design-time assets and version-scoped `manifest.json` files managed by the Game Design Service. Logical world and entity templates remain in PostgreSQL schemas owned by World Management, Entity Management, and related domain services as described in their architecture documents; they are **not** stored in the object store. + The asset store holds binary design assets and schema-versioned manifests at content-addressed keys managed by the Game Design Service. The retained per-version snapshot and candidate bind the exact selected artifacts. Logical world and entity templates remain in PostgreSQL schemas owned by World Management, Entity Management, and related domain services as described in their architecture documents; they are **not** stored in the object store. 6. **Removing published versions** @@ -109,15 +107,15 @@ When using a self-hosted MinIO cluster as the asset store: - **Target-state procedure only:** For a published/release artifact, complete the canonical `RetireVersion` workflow before calling `CanDeleteVersionAssets(tenantId, versionId)`. It must leave the caller-tenant version authority in **`RETIRED`** state while removing launchability: no `game_instances` rows may reference the `version_id` as `runtime_version`, and no canonical Game Design release/version/launch descriptor may resolve that version for a new launch. Retirement does not delete the version authority or immutable release attestation; `GetPublishedReleaseBundle(tenantId, versionId)` remains queryable for lifecycle and reachability proof. The legacy untenant-qualified `game_manifest` is diagnostic/disposition-only and cannot gate retirement or launch. Retirement is necessary but not sufficient for asset deletion. No safe `RetireVersion` operation exists in the current service. Operators must stop rather than use `CompareAndSetVersionState` as a substitute, because that operation is not retirement-safe. An abandoned failed candidate follows the separate failed-candidate eligibility path below and must not be converted to `RETIRED` merely to enable purge. - Retired eligibility must also account for **design-time dependencies**: the version must not be referenced by any game templates. Operators should validate that no normalized `game_template_*_ref` rows in the Game Design Service still reference `(tenantId, versionId)` before requesting the corresponding purge through Game Design. - - Asset deletion eligibility must account for design-history reachability as well as version mappings. Use the Game Design control-plane check `CanDeleteVersionAssets(tenantId, versionId)` that validates no non-Retired `version_asset` references remain, no reachable `revision_asset` / branch references require retained bytes, and no template or launch metadata still points to the version prefix. Until the current fail-open guard is closed, a result for an artifact with no caller-tenant matching version authority—including a wrong-tenant-only row—must be treated as non-eligible regardless of the API's current boolean result. + - Asset deletion eligibility must account for design-history reachability as well as version mappings. Use the Game Design control-plane check `CanDeleteVersionAssets(tenantId, versionId)` that validates no non-Retired `version_asset` references remain, no reachable `revision_asset` / branch references require retained bytes, and no template or launch metadata still points to the version prefix. The current API fails closed when caller-tenant Version authority is absent, including a wrong-tenant-only row. A positive eligibility result still does not establish the complete global reachability/publication fence or authorize object deletion. - Before purge or repair, read `GetVersionAssetArtifactState(tenantId, versionId)` and treat its `artifactState`, `stateEpoch`, `manifestHash`, `exportedVersionNumber`, and exported manifest asset keys as the authoritative proof row. Do not infer lifecycle state from bucket listings. - - Do not run deletion as a separate check + manual delete sequence. The target order is `TombstoneVersionAssets(...)` first: it performs the pre-tombstone caller-tenant authority, retirement-or-abandonment, frozen-proof, and reachability checks and its CAS transition. For an abandoned failed candidate, record durable proof with `AbandonFailedVersionAssets(...)` before tombstoning; for an eligible retired `PUBLISHED` release, no abandonment proof is required. Reload the artifact row, run post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, then call `BeginPurgeVersionAssets(...)` with the caller-supplied workflow identity. Current implementation/order drift includes a fail-closed pre-tombstone state check: `CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED`, while tombstone lacks the target authority checks and retired `PUBLISHED` transition. Separately, the current `CanDeleteVersionAssets` authority lookup can fail open when no caller-tenant version row exists, including a wrong-tenant-only row; that remains a non-eligibility warning until the guard is fixed. + - Do not run deletion as a separate check + manual delete sequence. The target order is `TombstoneVersionAssets(...)` first: it performs the pre-tombstone caller-tenant authority, retirement-or-abandonment, frozen-proof, and reachability checks and its CAS transition. For an abandoned failed candidate, record durable proof with `AbandonFailedVersionAssets(...)` before tombstoning; for an eligible retired `PUBLISHED` release, no abandonment proof is required. Reload the artifact row, run post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, then call `BeginPurgeVersionAssets(...)` with the caller-supplied workflow identity. Current implementation/order drift includes a fail-closed pre-tombstone state check: `CanDeleteVersionAssets` rejects pre-tombstone `FAILED`/`PUBLISHED`, while tombstone lacks the target authority checks and retired `PUBLISHED` transition. The current `CanDeleteVersionAssets` authority lookup rejects absent or wrong-tenant-only Version authority; retain that denial while completing the remaining lifecycle checks. - Operators must verify the persisted artifact lifecycle row (`version_asset_artifact`) is `TOMBSTONED` before issuing purge actions. **Target-state procedure only:** `BeginPurgeVersionAssets` must re-check eligibility and transition state to `PURGE_IN_PROGRESS` before bytes are removed, and `FinalizePurgeVersionAssets` must transition to retained terminal state `PURGED` after bytes are removed. The current path is subject to the non-atomic implementation-status gap above; do not infer lifecycle state solely from object-store contents. - `EXPORTED_UNATTESTED` means bytes were exported but publish did not complete. Such prefixes are not launchable and must be repaired or failed through the documented workflow; operators must not treat them as equivalent to `PUBLISHED`. - - Published-asset discovery and post-tombstone deletion recheck use `CanDeleteVersionAssets(tenantId, versionId)` and `GetVersionAssetArtifactState(tenantId, versionId)`; pre-tombstone authority/reachability belongs to `TombstoneVersionAssets`. The `version_asset` mapping checks are target-state because the current implementation has no mapping authoring path; operators must never delete referenced objects or bypass the Game Design reachability/CAS lifecycle. In particular, absence of a caller-tenant matching version authority, including a wrong-tenant-only row, remains a fail-closed stop condition until the current guard is remediated. - - If object-store contents drift from the database (for example missing objects for a still-published version), do not use the current `RepairPublishedVersionAssets` path for Published/Active repair: it writes objects and `manifest.json` before `VersionAssetArtifactServiceImpl` performs the exact repair-match check, so a mismatch can write or overwrite live prefix keys before returning `REPAIR_ATTESTATION_MISMATCH`. Keep the release closed and escalate until repair either fails closed before every write or uses independently verified exact selection; process loss also remains `REPAIR_VERSION_SCOPE_UNAVAILABLE` for Published/Active, and a RETIRED version must not fall through to a fresh tenant-wide snapshot. The target content-addressed candidate and per-object digest procedure is defined in `asset-storage.md`. - - The target `RepairPublishedVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, repairWorkflowId)` operation may be used only after that pre-write exact-selection gate exists. It must produce deterministic `REPAIR_ATTESTATION_MISMATCH` or `ASSET_ARTIFACT_STATE_CONFLICT` outcomes and never mutate attested bytes on a mismatch; until then, operators must not recommend or invoke the current path as a repair procedure. - - **Target-state content-addressed repair:** Because Published/Active versions are immutable, the target workflow must produce bit-for-bit identical bytes matching the existing `published_release_bundle` attestation returned by `GetPublishedReleaseBundle(tenantId, versionId)`, verify mandatory per-object actual-byte digests, and restore only exact immutable content-addressed objects. Producer-owned derived artifacts must come from their immutable producer contracts. If any required artifact cannot reproduce the attested bytes, fail closed rather than “fixing” the published version in place; this target procedure does not describe the current first-slice version-scoped repair path above. + - Published-asset discovery and post-tombstone deletion recheck use `CanDeleteVersionAssets(tenantId, versionId)` and `GetVersionAssetArtifactState(tenantId, versionId)`; pre-tombstone authority/reachability belongs to `TombstoneVersionAssets`. Current `version_asset` mappings come from the synchronized ordinary source snapshot, while direct association remains denied. Operators must never delete referenced objects or bypass the Game Design reachability/CAS lifecycle; absent or wrong-tenant-only Version authority is a fail-closed stop condition. + - If object-store contents drift from the database, preserve the artifact, candidate, snapshot and release-attestation evidence. The current repair implementation verifies the retained selection and exact attestation before object writes, then conditionally writes and reads back content-addressed objects. It does not recreate missing selection or candidate evidence. Physical object-store and global-fence proof remain unavailable; escalate rather than using manual overwrite or assuming this source-level correction qualifies a deployment. + - For `RepairPublishedVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, repairWorkflowId)`, retain exact artifact epoch, caller-tenant scope and the original attestation. A pre-write mismatch fails closed, and an artifact epoch conflict requires owner readback. Code-level checks do not replace qualification of the actual object-store, failure and recovery boundary before operational use. + - **Target-state content-addressed repair:** Because Published/Active versions are immutable, the target workflow must produce bit-for-bit identical bytes matching the existing `published_release_bundle` attestation returned by `GetPublishedReleaseBundle(tenantId, versionId)`, verify mandatory per-object actual-byte digests, and restore only exact immutable content-addressed objects. Producer-owned derived artifacts must come from their immutable producer contracts. If any required artifact cannot reproduce the attested bytes, fail closed rather than “fixing” the published version in place. The implemented ordinary-asset writer checks described above cover only their named source boundary, not the complete producer, deployment or global-fence contract. - **Target-state workflow only:** Route deletion through pre-tombstone `TombstoneVersionAssets(...)`, post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, `BeginPurgeVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, purgeWorkflowId)`, and `FinalizePurgeVersionAssets(...)`. Every mutation carries the shared ADR 0048 operation envelope and caller-supplied workflow identity. The target workflow re-checks reachability and CAS state before deletion, and the lifecycle APIs retain terminal metadata after physical bytes are removed. The current path is subject to the order, idempotency, and non-atomic implementation gaps above. - Direct object-store commands such as `mc rm` are outside the supported lifecycle. Incident recovery may preserve or isolate evidence for escalation, but it must not bypass the Game Design reachability/CAS APIs or claim to finalize lifecycle state. @@ -126,31 +124,17 @@ When using a self-hosted MinIO cluster as the asset store: Occasionally the asset-export step of `PublishVersion` may fail in a way that leaves a version incomplete or unusable: -- **Target-state workflow only:** When the Game Design publication workflow - coordinated by Temporal marks a version as **Failed**, the canonical Game - Design release/version/launch descriptor and attestation surfaces must not - make it launchable, and operators must not attempt to start game instances - against it. Any retained legacy `game_manifest` row is - diagnostic/disposition-only and is neither evidence nor a launch gate. The - current first slice executes publication synchronously when Temporal is - disabled; its failure handling is incomplete as documented above and is not - equivalent to durable Temporal failure coordination. -- **Target-state only:** Failed versions may have partially written candidates in a private quarantine namespace; do not delete those candidates manually. If there is no intention to retry publish, use the target Game Design `AbandonFailedVersionAssets(...)` operation to record durable abandonment, then invoke pre-tombstone `TombstoneVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, tombstoneWorkflowId)` to prove caller-tenant `FAILED` authority, frozen proof, and no reachability before its CAS transition. **Target-state only:** the abandonment record and target authority/CAS transition are not implemented. The current exporter writes directly to the private `tenant/version/` prefix and has no separate quarantine namespace. +- **Target-state workflow only:** When the Game Design publication workflow coordinated by Temporal marks a version as **Failed**, the canonical Game Design release/version/launch descriptor and attestation surfaces must not make it launchable, and operators must not attempt to start game instances against it. Any retained legacy `game_manifest` row is diagnostic/disposition-only and is neither evidence nor a launch gate. Current fresh and `PENDING` full-version publication ingress is denied; the private owner-local failure mechanics described above do not establish operational Temporal failure coordination. +- **Target-state only:** Failed versions may have partially written candidates in a private quarantine namespace; do not delete those candidates manually. If there is no intention to retry publish, use the target Game Design `AbandonFailedVersionAssets(...)` operation to record durable abandonment, then invoke pre-tombstone `TombstoneVersionAssets(tenantId, versionId, expectedArtifactStateEpoch, tombstoneWorkflowId)` to prove caller-tenant `FAILED` authority, frozen proof, and no reachability before its CAS transition. **Target-state only:** the abandonment record and target authority/CAS transition are not implemented. The current exporter uses content-addressed keys, but complete private candidate isolation and the abandonment workflow remain unimplemented. - **Target-state only:** Failed or `EXPORTED_UNATTESTED` candidates are never launchable, never used as fallback, and never repaired in place while runtime admission continues. A retry creates a new approved workflow attempt and either completes a fully attested `PUBLISHED` release or remains non-launchable. In the current first slice, a failed `PublishAttempt` is terminal for that workflow identity and no retry-publish or repair-version orchestration is exposed; only the published-artifact repair API exists. - The canonical lifecycle states, transitions, bundle-readback rules, and target serialization fence are defined in [Asset Storage Setup](./microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). Operators must preserve these local consequences: - `FAILED` and `EXPORTED_UNATTESTED` remain non-launchable and non-fallback; retry uses the documented workflow, while failed-candidate purge requires caller-tenant `FAILED` authority plus durable explicit abandonment proof. - A published/release purge requires caller-tenant `RETIRED` authority, and target `PUBLISHED -> TOMBSTONED -> PURGE_IN_PROGRESS -> PURGED` proceeds only through the control-plane APIs after eligibility and epoch reload. `PURGED` retains lifecycle metadata; physical deletion never removes the artifact row. - A failed-candidate purge uses the separate abandoned-candidate path and must not invent a `FAILED -> RETIRED` transition. `PURGE_FAILED` retry/resume and abandonment remain explicit workflow actions. - - **Target-state only:** lifecycle transitions and publication/failure readback are CAS/lock serialized for both artifact and Version rows. The current row-ID updates have no database epoch predicate or affected-row check, so they must not be treated as concurrency protection; CAS loss requires fresh readback and approved workflow retry, never manual object-store edits. The target owner ledger also supplies exact operation replay/conflict handling under ADR 0048; the current random-only Begin workflow identity does not. + - **Target-state only:** lifecycle transitions and publication/failure readback are CAS/lock serialized for both artifact and Version rows. Artifact updates have a database epoch predicate and affected-row check; Version lifecycle and global-fence proof remain incomplete, so that artifact check must not be treated as complete concurrency protection; CAS loss requires fresh readback and approved workflow retry, never manual object-store edits. The target owner ledger also supplies exact operation replay/conflict handling under ADR 0048; the current random-only Begin workflow identity does not. - Preferred recovery is to: - Investigate and fix the underlying issue (for example missing assets or permission errors). - - **Target-state only:** Trigger a documented “retry publish” or “repair version” workflow through the Game Design Service, the publication workflow owner, so its Temporal-coordinated workflow re-runs the asset export step and transitions the version back to Draft/Published as appropriate. If the request starts in Logging & Admin, that service is only the audited operator facade forwarding the typed request to Game Design; it does not own or execute publication. No retry-publish or failed-candidate repair-version operation is currently exposed by Game Design or Logging & Admin. Game Design does expose `RepairPublishedVersionAssets(...)` for an already-published artifact; it is exact-bytes repair against the existing release attestation, not a retry of failed publication. The current first slice writes a plain filename-to-URL - `manifest.json` map without a `schemaVersion` field. The target manifest - contract adds an explicit schema version; until that target is implemented, - operators must not claim current schema-versioned manifest discovery. For - Published/Active releases, do not use repair to move the release to a newer - manifest schema version; repair is exact-bytes only unless a separate - re-attestation workflow is explicitly defined. + - **Target-state only:** Trigger a documented “retry publish” or “repair version” workflow through the Game Design Service, the publication workflow owner, so its Temporal-coordinated workflow re-runs the asset export step and transitions the version back to Draft/Published as appropriate. If the request starts in Logging & Admin, that service is only the audited operator facade forwarding the typed request to Game Design; it does not own or execute publication. No retry-publish or failed-candidate repair-version operation is currently exposed by Game Design or Logging & Admin. Game Design does expose `RepairPublishedVersionAssets(...)` for an already-published artifact; it is exact-bytes repair against the existing release attestation, not a retry of failed publication. The current exporter writes a schema-versioned manifest with per-artifact digests and content-addressed keys. This does not supply missing release-bundle transport fields or qualify public manifest discovery. For Published/Active releases, do not use repair to move the release to a newer manifest schema version; repair is exact-bytes only unless a separate re-attestation workflow is explicitly defined. - For Published/Active versions, treat the workflow as exact-bytes repair only: it must verify the current `GetPublishedReleaseBundle` attestation and fail if the regenerated bytes would change the attested `manifestHash`. - If clean-up is required after deciding to abandon a Failed version, first record the durable abandonment proof with `AbandonFailedVersionAssets(...)`, then use pre-tombstone `TombstoneVersionAssets(...)`, post-tombstone `CanDeleteVersionAssets(tenantId, versionId)`, and the **target-state CAS-guarded** `BeginPurgeVersionAssets(..., purgeWorkflowId)` / `FinalizePurgeVersionAssets(...)` workflow. The current abandonment, order, idempotency, and CAS paths are not implemented; do not remove the corresponding prefix directly. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index a6e08805a0..114fd46437 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -265,6 +265,53 @@ Entry format: - Expected pattern: Restored explicit RFC 8785 normalization of each fixture payload before binding creation. Updating a golden from one failing run alone did not establish a stable vector; retain equality/mutation checks and verify the normalized vector before claiming deterministic proof. - Outcome: No production digest or retained bytes were changed. R44 and the fresh R45 JVM agree on the normalized vector; all 686 GDS unit cases pass in R45. +- `2026-10-15`: Separate selected-publication owner proofs missed an Account settlement profile gap. + - Context: The actual GDS terminal → authenticated World completion → both real terminal reads composition reached Account V94 and failed with SQLSTATE 23514 because its inventory validator still admitted only inventory/1 + World/3, while the current canonical producer retains closure inventory/2 + World/4. + - Observation: Correction and qualification are in progress. + - Outcome: Forward V1011 converges both validation profiles; the following selected-publication settlement entry records the R14/R16 qualification and its controlled-proof limits. + - Expected pattern: Preserve that failed composition beside prior component passes; a forward validator correction needs exact profile/refusal and existing-settlement byte/row-version upgrade proof. Do not rewrite installed migrations or treat controlled terminal readbacks as actual producer composition. + +- `2026-10-15`: Selected-publication settlement profile follow-up. + - Context: Account's forward V1011 now converges the exact inventory/1 + World/3 and closure inventory/2 + World/4 validation profiles while retaining the original framing, digest, source and artifact guards. + - Observation: R14 passes the actual six-store terminal-to-settlement composition and nine malformed-profile refusals; R16 passes original PUBLISHED and NO_PUBLICATION settlement upgrade/replay with unchanged stored bytes and row versions. + - Outcome: A test-only V1010 predecessor allowlist omission was corrected separately. + - Expected pattern: These controlled component proofs supply no genuine creator, issuer, environment or deployed authority. + +- `2026-10-16`: Keep FireController briefs within the size limit + - Context: FireController job briefs are capped at 200,000 characters. + - Observation: Repeatedly prepending completed and running checkpoints caused a revision to be rejected before the active execution state could be saved. + - Expected pattern: Archive the full previous brief, retain standing instructions and superseding decisions, replace the active execution section, and put milestones in native updates/checkpoints. Consolidation restored guarded updates without losing source history or standing authority. + +- `2026-10-16`: Keep the original Logging claim-read client workload-only + - Context: A generic gRPC channel and stub customizer did not establish the original Logging claim-read client's workload-only boundary: the common customizer attaches bearer metadata, and a trusted TLS channel alone does not pin the expected SPIFFE workload. + - Observation: The corrected client uses the existing Common peer credentials and response verifier, preserves default-off composition, and rejects ambient SQL, synchronization and caller context before RPC. Controlled loopback mTLS and the existing native owner consumer now prove this bounded behavior; they do not establish genuine upstream authority. + - Expected pattern: Keep the configured server identity separate from mutation target data, and follow canonical usable TLS-material policy rather than copying a donor's regular-file predicate. + +- `2026-10-16`: Bound subprocess output and waits in the original claim-read test PKI fixture + - Context: Reading subprocess output to EOF before a timed wait leaves the supposed deadline unbounded. + - Observation: The original claim-read test PKI helper now redirects output to an owned temporary file, waits before reading it, and terminates/reaps a timed-out or interrupted child with interrupt preservation. Actual stalled-keytool timeout and interruption cases pass alongside the affected TLS and native owner proofs. + - Expected pattern: Keep this correction in the purpose-specific fixture; it does not require a general command framework or change production TLS material policy. + +- `2026-10-16`: Recheck original ControlUI expiry after owner locks + - Context: An initial ControlUI token expiry check became stale across later owner locks in both current-actor paths. Registry cleanup retention and authorization-reference expiry did not replace the original token's validity boundary. + - Observation: The focused native fixture advances the existing actor clock at the real locking read: the old code entered both callbacks after expiry; the correction rejects them without changing the original row while preserving exact held-order recovery. + - Expected pattern: Keep current authorization and historical recovery distinct when reconciling displaced guards. + +- `2026-10-16`: Compare the complete original validity interval at one owner boundary + - Context: original creator callbacks can wait for Account owner locks after initial token verification. + - Observation: an expiry-only final check misses a clock observation before the original not-before bound; registry cleanup retention and authorization-reference expiry do not define the original token's full interval. + - Expected pattern: use one existing-clock observation for the canonical original `issuedAt <= now < expiresAt` interval, test both denial bounds and exact lower-bound equality, preserve immutable evidence, and keep historical exact-order recovery separate from fresh authorization. + +- `2026-10-16`: Separate original signer provenance from present public-key acceptance + - Context: fresh signed and committed-JTI creator callbacks must retain their original key identity. + - Observation: an immutable source pin, historical committed-signer receipt and still-fresh signature cache do not independently establish that the original key remains in the current protected public snapshot. + - Expected pattern: load the existing trusted source outside SQL and synchronization, compare the original key ID and RFC 7638 fingerprint, preserve accepted retiring-key membership and historical exact recovery, and state the per-invocation snapshot limit beside the proof. + +- `2026-10-16`: Bound child waits in standalone receiver PKI fixtures + - Context: The standalone activation and World participation receiver PKI fixtures had the same output-before-wait pattern, leaving child execution unbounded. + - Observation: Both use the existing purpose-specific bounded-child pattern; four actual stalled-JDK-child timeout/interruption cases and all eight consuming receiver cases pass. + - Expected pattern: Compare each remaining fixture owner independently; an earlier Logging fixture pass does not prove these locations, and controlled socket proof does not establish real Account settlement or genuine PKI. + - `2026-10-19`: Independent maintenance temporarily becomes the product queue's parent - Context: Controller recovery maintenance PR #3271 was inserted before the existing product front to obtain the next admissible shared review slot. - Observation: the current controller queue is strictly linear and has no independent maintenance root. Inserting an open maintenance PR before the product front changes the product front's effective parent even though the patches are independent, creating an integration fence until maintenance merges. @@ -314,3 +361,9 @@ Entry format: - Expected pattern: Forward the existing CI environment contract explicitly and enable the documented repository-curation option while retaining global providers. Normalize only exact package/version metadata supported by upstream license text, and record a package-specific choice for an explicitly offered alternative. Custom licenses require their own policy decision; do not relabel them as SPDX aliases or waive unresolved policy errors. - Proof limit: Workflow wiring, YAML, failure guards and upstream metadata are checked locally. Only actual analyzer/evaluator results can qualify the hosted correction; the earlier Maven Central 403 response origin remains unknown. - Live-policy correction: The default evaluator rejects package curations inside `.ort.yml` even when the analyzer supports them. Keep exact package metadata in a read-only child mount under the existing global `DefaultDir` provider instead, preserving its other entries and rules; keep the valid OR-license choice in an NPM-scoped repository configuration so Gradle-only scans do not reject an absent package choice. Configuration-schema support alone did not establish policy acceptance, and actual hosted proof remains required. + +- `2026-10-24`: Distinguish PostgreSQL health from the Docker-published connection path + - Context: A forced Account integration run at `3534f58291439f7c059759cc57a7385106051e39` ran 333 cases with 13 mapped-localhost connection failures and no skips. One failed fixture recorded a running PostgreSQL container, successful internal Unix-socket `SELECT 1`, IPv4 localhost resolution and a Docker host-port binding while the test JVM's mapped JDBC connection was refused. The other twelve failures shared a different fixture without equivalent internal-health diagnostics. + - Observation: Those facts isolate the first failure to the test-to-published-port path without identifying a Docker Desktop, WSL, fixture or cleanup cause. Successful internal SQL or published binding metadata alone is insufficient host-path readiness proof. + - Outcome: A later focused run passed all seven source-evidence and twelve selected-owner cases without a Docker, host-setting or fixture change. This qualifies those nineteen cases separately; it neither turns the earlier failed aggregate green nor proves the connection problem repaired. + - Expected pattern: Retain exact fixture, host, mapped-port and internal SQL evidence beside the original failed run; qualify a focused retry independently and investigate recurrence without weakening readiness or cleaning unrelated containers. diff --git a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md index 2f6fabe7de..8077e84c2c 100644 --- a/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md +++ b/design/project-management/implementation-tracking/game-authoring-publishing-and-activation.md @@ -14,6 +14,32 @@ At source `f9e3f879d137b9a6fa54085e9c0b797586636a00`, the focused gate passed 1, The earlier independent four-module attempt at `6365c186390587f31c96aa5e442cbbc6cc7f43a0` completed 2,694 invocations but its aggregate failed when the existing `ScriptDefinitionRepositoryIntegrationTest` failed during initialization with a PostgreSQL connection refusal. All other owner unit and native scopes passed, including eleven Entity and eleven Automation selected-source PostgreSQL cases. The cause of that refusal remains unknown. The exact unchanged 12-case `ScriptDefinition` replacement and the unfinished four-module checks subsequently passed; that does not erase the original failed aggregate or establish a passing fresh whole-service Entity and Automation gate. +### Selected publication reservation preparation + +The unregistered reservation adapter independently reads the retained selection, exact Account HELD evidence, World freeze/inventory/selector and original World source/delivery before the existing local reservation transaction. The coherent continuation supplies Account's selected-publication producer, HELD read, typed order transport and exact terminal-settlement owner. Current terminal clients and binding guards remain authoritative; no parallel terminal codec is introduced. The ten GDS ordering/refusal units, twenty-five Account owner units and seven Common typed-order units pass with their original focused attribution. + +R14 freshly passes eleven Account native cases and the extended six-store Full composition with zero failures, errors or skips in those cases. The composition uses the actual Account store and normal Redis issuance fixture, authenticated Account HELD and World committed-freeze replay/read endpoints before real GDS admission/reservation and exact retry. The original GDS delivery intake identity is preserved through World application; mutable World retry readers are asserted unused. The atomic v4 bundle/terminal commit and immutable readback still execute. The actual Game Design terminal receiver, authenticated Game Design-to-World completion producer and World's independent Game Design terminal read then supply both real terminal owners to Account settlement. Settlement before World completion refuses without a receipt; successful settlement and exact retry preserve the original terminal bytes, receipt and row version. Nine direct malformed closure/profile mutations are refused by Account SQL. The local inbound Account caller context is explicitly controlled; its two outbound terminal reads execute real mTLS. Passive capture owns all eight run-created PostgreSQL containers without gaps or observer errors. + +The composed proof exposed Account V94's obsolete inventory profile. Forward V1011 converges the validator to the same exact legacy inventory/1 + World/3 and explicit closure inventory/2 + World/4 pairs already owned by Game Design and World. All remaining frame, digest, source, artifact, selected-commit and owner-correlation guards remain enforced; installed migrations and retained rows are unchanged. R14's sole failure was the new historical fixture's unsupported V1010 target. After adding that exact test-only predecessor, R16 freshly passes the V1010-to-current upgrade and replay case for both original terminal outcomes, retaining authorization, source, settlement, issuer and prior Flyway rows including row versions. Scoped generation, compilation, static analysis, formatting and documentation checks pass; the other native cases retain R14 attribution. + +FreshBeginR3 freshly passes the same six-store composition with a fresh authenticated World begin, rather than a fixture-created freeze. World starts with its owner OPEN and no attempt, Account correlation, inventory or canonical frozen capture. Actual Game Design selection and source-qualified Version handlers and Account HELD are called over mTLS. A controlled Account transport outage refuses before World effects, preserving all five owner tables including row versions; enabling the real read creates the exact FROZEN checkpoint, Account correlation, complete inventory and selector capture. An exact begin retry succeeds with both mutable upstream transports denied and without repeating any owner reads or changing retained rows. The World fixture now only reads the independently committed result. The later actual reservation, v4 bundle and terminal-to-Account settlement still pass in that same fresh native case. FreshBeginR3 has zero failures, errors or skips; all six run-owned PostgreSQL containers are passively identified without ownership gaps or observer errors. Compilation, scoped static analysis, formatting and documentation checks pass. + +ActualOrderR2 freshly passes that same native composition after replacing the directly invoked Account producer with the real selected-order transport. Game Design calls the actual Account receiver with the original creator credential; Account independently authenticates the actual retained Game Design selection through its existing owner client before its local producer transaction. A controlled Game Design transport outage preserves Account authorization, source, settlement and issuer rows including row versions. Successful ordering creates one original held order from the single committed creator issuance; exact retry rereads the real selection, returns identical original binding bytes and preserves retained rows. That returned binding drives the fresh World begin and later actual publication and settlement. The case has zero failures, errors or skips, with all six run-created PostgreSQL containers passively owned without gaps or observer errors. Scoped compilation, static analysis and formatting pass. These are actual component transports with controlled upstream creator, issuer, environment and PKI; the public-finalizer/currentness/recovery holds remain unchanged. + +Original World source/version registration and APPLIED input remain controlled fixture preparation. Upstream creator, issuer, environment, PKI and other declared source/candidate inputs remain controlled. These components remain unregistered and do not supply accepted through-commit production authority, failed-selection recovery, a reachable publication finalizer or a production entrypoint. Fresh/PENDING publication and runtime authority remain denied. All genuine Gameplay handoffs remain open. The complete boundary is assigned to Gameplay's existing receiving PR, with no additional extraction PR. + +### Selected publication settlement transport receiving + +The canonical source continuation also preserves the donor's unique asset requiredness, identity, canonical payload, command closed-field, gameplay catalog/reference and realm-policy provenance regressions at their current owners. Terminal-read request and response refusal vectors use the current framed grammar, including explicit UNKNOWN, complete request echo, malformed or substituted terminal rejection and defensive original bytes. These structural and owner-local units use controlled values; they do not establish original authority, production activation or genuine physical handoffs. + +Current Account settlement and World terminal-completion requests require the complete v2 operation tag before owner access. The shared decoder preserves historical v1 operation and terminal bytes for history reads; that support does not widen either current transport contract. Both codecs reject the historical profile from direct request construction and protobuf decoding, following the existing rule that retained history does not widen consumers that lack older-profile support. + +The selected Account order, held-read and settlement clients, Game Design selection and terminal-read clients, and World terminal-read client release their local monitor before the shared certificate watcher drains an in-flight reload callback. Their close flags still deny reuse; the existing selected-owner lifecycle matrix covers callback contention, idempotent shutdown and closed-client initialization denial. + +The canonical Game Design publication terminal client retains the original donor's local transaction exclusion: active owner SQL and synchronization-only contexts fail before transport access. This guard stays on the current closed framed terminal-read API; the alternate donor client, evidence type and service are not reintroduced. + +The current-carrier continuation retains the standalone, unregistered Account selected-publication settlement receiver, explicit file-backed mTLS client and closed request/receipt codec from the preserved #3105 donor. Account still derives settlement from its two independent authenticated Game Design and World owner reads; the caller supplies only the complete original operation and transport correlation. The codec validates the unchanged six-frame receipt, exact operation and owner terminal/outcome agreement within the serialized wire bound. The selected full-owner fixture now invokes this actual Account receiver over loopback mTLS, requires a World workload caller to be denied, retains no settlement before World completion and checks unchanged receipt bytes and row metadata on retry. Original creator/issuer/environment, source provenance, selected inputs and ephemeral PKI remain controlled. No production service registration, migration, activation or genuine Gameplay handoff is established. + ### Gameplay source catalog and legacy handoff proof The existing Game Design gameplay source PostgreSQL owner test now retains a nonempty action, ability, effect, resource and admission-tag catalog beside an ordinary asset in one owner outcome. Exact retry and independent repository reads preserve the original source bytes. A disjoint asset change inherits the gameplay epoch and original binding; explicit ability and action deletion advances the gameplay epoch while preserving the prior snapshot. Additional cases deny legacy effective commands and generic gameplay-rule history before or after the typed snapshot, including an explicitly emptied rule inventory. Generic history under a different private tenant or Version does not contaminate the exact selected source. @@ -32,6 +58,12 @@ The restored Version identity native owner test preserves the original retained All six native cases freshly pass with zero failures, errors or skips against the canonical PostgreSQL image and owning filesystem migrations. Canonical formatting, style, Integration Checkstyle and SpotBugs pass; passive capture identifies the one run-owned PostgreSQL container and independently confirms its absence after completion. This proves owner-local identity and historical retention mechanics with controlled setup. It does not establish creator or issuer authority, currentness, publication enablement, an immutable production release, activation or a genuine Gameplay handoff. No production, installed migration or registration changes are included. +### Selected-full release profile and exact retry storage proof + +Three further native cases use the current test fixture's schema-4 World input from its first construction, actual Game Design source inheritance, reviewed policy, selection, source captures and local publication storage. Direct SQL rejects an incorrect digest schema independently for each of the five participant owners, without creating a bundle or changing the original Game and Version rows or their row versions. A valid v4 bundle retains its original World and participant bytes on independent read and exact retry; changed generation configuration refuses without changing the complete bundle row or its row version. Two concurrent exact storage calls return the same single retained bundle, followed by another unchanged-row retry. Their start latch establishes submitted calls and outcomes; it does not independently measure precommit blocking. A separate SQL case refuses missing selectors, malformed text or numeric epochs, changed request bindings, missing opaque evidence and empty or changed participants, preserving the original Game and Version rows and their row versions without creating a bundle. The unchanged eligible input then commits through actual SQL and independently reads back its original selector bytes. + +All eight native bundle cases freshly passed on donor code source `2226e1ca6a4929bea9611255dd5d2f84177e6faa`, with zero failures, errors or skips. Canonical formatting, style, Integration Checkstyle and SpotBugs passed; the one passively identified PostgreSQL container was independently absent after completion. On receiving source `fc11e3c1a353537c433ea480b3332d0057df3afc`, all eight bundle cases, ten publication-transaction cases and two historical selector-migration cases freshly passed together with zero failures, errors or skips (2026-10-16 08:14:55–08:16:25 UTC). Integration Checkstyle, SpotBugs, formatting and documentation checks also passed. Main verified fresh reports, unchanged source and independent absence of all four strictly run-owned PostgreSQL containers after forced removal. This is separate receiving evidence; donor attribution remains unchanged. The proof uses stipulated Account, World and other remote participant evidence and a controlled empty-asset candidate. It does not establish a genuine immutable release, authenticated creator or issuer, currentness, public finalizer enablement, activation, settlement or a Gameplay handoff. The three selected-full fixture helpers are already present at their inherited shared-test blobs in this receiver. No production, installed migration or registration changes are included. + ### Selected-full owner publication preparation The source candidate prepares complete selected-owner publication consumption under the [canonical selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). It reuses the actual parent World closure producer, adds its full-profile consumer mapping, and composes the selected Game Design digest read/collector with independently retained Entity, Automation and Game Logic receipts. The Game Logic adapter reads the exact retained terminal, selected source and manifest through the existing owner repository and returns both manifest and ability projections; its default Spring composition remains denied. Private selected writer mechanics use the exact canonical selection/request binding and selected gate. Public Game Design fresh/PENDING publication remains denied. Existing Game Design V1020 storage is reused; no Game Design migration is added. diff --git a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md index c33e1e799b..62932e1d86 100644 --- a/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md +++ b/design/project-management/implementation-tracking/gameplay-rules-entities-and-effects.md @@ -129,6 +129,8 @@ Damage, mitigation, resistances, combat timing, body-region resolution, defeat, ## Validation and Proof +- A restored positive Entity terminal-read socket case freshly passes with affected Common Platform Core test Checkstyle, SpotBugs and formatting. The actual `GrpcEntitySelectedSourceIntakeTerminalReadClient` receives a complete canonical receipt larger than the ordinary 4 MiB gRPC default over loopback mTLS, within the declared wire bound; the server verifies the Account workload and original request, and the client returns the exact original receipt and authorization bytes. The existing [terminal client test](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamelogic/GrpcEntitySelectedSourceIntakeTerminalReadClientMtlsTest.java) previously covered only missing-receipt transport and server pinning; that case retains its earlier execution attribution. The complete authorization, World inventory and Entity receipt are controlled fixtures, and the shared test PKI differs from the donor's inline PKI helper. This is client/codec transport proof, not genuine issuer or recipient storage, currentness, settlement, runtime registration or handoff closure. + - The 2026-10-14 current-parent source correction keeps the assignment/roster family unregistered under ordinary component scanning, including when the former activation flags are true, and excludes both roster methods from the JWT public-method allowlist. The initial consolidated gate executed 281 Entity unit cases with one stale allowlist assertion failure, 30 native PostgreSQL cases with no failures, errors or skips, and 17 focused Game Session roster-client cases with no failures, errors or skips. After correcting that assertion, all 11 focused registration, manual-composition and peer-policy cases passed with no failures, errors or skips; affected formatting, static analysis and documentation checks passed. These combined results qualify the bounded source and unchanged retained storage, not production registration, ADR 0163 disposal, genuine authenticated caller completion or a fresh packaged player journey. - On 2026-10-20, the locked combined Entity/Common gate completed at 03:44:51 NZDT. It freshly executed 321 Entity unit cases, 47 native Entity PostgreSQL integration cases, and 11 focused Common cases (379 total), with zero failures, errors, or skips. Full Entity checks and affected static, style, and documentation checks passed. Post-run inspection found 12 exact logged containers absent. The qualified correction postimages were published as `490bf9b6fa941c01004e6b20df99bd5363c2d2fb`. This proves bounded passive source and controlled-storage behavior only, not genuine owner issuance, production registration, runtime activation, public admission, or a packaged player journey. The existing [GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/service/impl/GameSessionPreseededActorAssignmentOwnerEvidenceAdapterTest.java) covers mapping source evidence to the exact eligible target and rejecting a response bound to a different assignment; its synthetic fixture does not establish live owner authority. diff --git a/design/project-management/implementation-tracking/player-access-and-session.md b/design/project-management/implementation-tracking/player-access-and-session.md index 2c3656bec0..c24a1263ed 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,56 @@ This is a non-normative implementation tracker for player access and session. Ca ## Current Status +### Retained Draft authorization fence migrations + +The [Account fence history fixture](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java) executes the owning filesystem migrations from V75 through V76 and then the current default migration set. Its Account UUID and provenance come from PostgreSQL defaults; it retains the original v1 binding, commit order, stipulated World committed readback, missing Game Design outcome, pending source change and 512-byte source key. Every original column and row version in all six authorization ledger tables, and every prior complete Flyway history row, survives both upgrades. The expected V87 addition of one Global Roles serialization lock is checked separately; it supplies no authority evidence. Exact replay, current pending-mutation refusal and denied binding/readback rewrites leave the retained rows unchanged. + +At source `6a9be6e90decee3c478f36fa4d5ba9f41ddcc313`, the focused native case and affected integration static analysis and formatting pass: one fresh case, zero failures, errors or skips. The actual local run completed on 2026-10-16 from 10:01:32Z to 10:02:08Z. Its strict passive observer owns one PostgreSQL container with an inherited resource-session descriptor, no ownership gaps or observer errors, and independent confirmation that the exact container is absent afterward. Fixture cleanup emits kill 9 and exit 137; this is not graceful shutdown proof. Source capture and World terminal authority are stipulated. This proves retained storage and migration behavior, without genuine World application, final Account settlement, issuer/currentness authority, runtime activation, gameplay admission, Entity delivery or completion of a genuine handoff. + +On Gameplay receiving source `c2f04d797179710e81df08033b16d4f596997e1e`, the same native case freshly passed once with zero failures, errors or skips, together with affected Account integration static analysis, formatting and documentation checks (2026-10-16 10:14:00–10:15:37 UTC). Main read the complete receiving test and saved XML, verified its unchanged qualified Java postimage and independently confirmed its exact run-owned PostgreSQL container absent. Later parent propagation changes no Account implementation or this test. This is focused receiving evidence for retained history; the separate failed whole-Account invocation retains its original outcome. + +### Retained StartSession owner tuples + +The focused Game Session owner fixture retains original unsafe numeric v1 fence carriers through current-execution rejection, including exactly representable values above the safe JSON integer range. It checks the original stored bytes and row version after decoder refusal, conflicting current-spelling replay, Account-projection attachment, evidence continuation and current-attempt reads; the original attempt remains the only row and runtime/admission pointers stay absent. This is controlled PostgreSQL integrity proof, without issuer or deployment provenance. The focused case passes once with two unsafe numeric vectors at source `c6bf1b202b55d0b2616a26d72e4af50c543793fb`; affected integration static analysis, formatting and documentation checks pass. The strict passive observer owns its single PostgreSQL container, with an inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Account source-protection and six-store publication cases retain their separate proof boundaries. + +The existing [World original-owner composition](../../../services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java) now passes its positive operation at fence values 9,007,199,254,740,992, 9,007,199,254,740,993 and 9,223,372,036,854,775,807. Actual Account issuance/redemption, native Game Session storage and the authenticated Account-to-Game Session current-attempt mTLS read preserve each exact fence, original tuple and redemption projection; the authenticated read leaves the complete stored row and row version unchanged. All three fresh parameterized cases pass with zero failures, errors or skips at source `f1ba70374fab5c7d7a4b733c0bea2bd842a2cd7b`, together with affected cross-service static analysis, formatting and documentation checks. The strict passive observer owns all three run-created PostgreSQL containers, with an inherited resource-session descriptor, no ownership gaps or observer errors, and all three absent after completion. This closes the two focused owner-tuple proof gaps within these controlled fixtures. Creator, Logging claims, publication/launch evidence and PKI remain controlled; the existing World preparation/activation and Account settlement composition uses unregistered owners and a test-local World transport wrapper. It does not establish genuine issuer/environment authority, deployed composition, gameplay admission, Entity placement or completion of any genuine handoff. + +### Original creator validity at the callback boundary + +Both fresh current-actor paths implement [Account's original creator callback authorization contract](../../architecture/microservices/account-service/api-contracts.md#original-creator-callback-authorization) in `AccountControlUiActorService`. + +The existing Account original-order PostgreSQL fixture changes its injected actor clock when the real final owner locking read completes. The earlier expiry-only code enters both callbacks when that clock moves before the original not-before boundary. The corrected fixture denies both early and expired callbacks without changing the original row JSON or row version, permits both callbacks at exact original `issuedAt` equality, and preserves the existing expired-creator exact-recovery case. These seven native cases plus the unchanged healthy secured Account owner case pass at `cefccc984d6154b9d1b8c3e439541584d2844fc8` with zero failures, errors or skips and affected integration static analysis and formatting. Seven existing Actor unit cases and Main/unit static analysis retain their passing attribution at `774864935ba9783dab410507689ad2848c00fe15`, with the identical production blob. That earlier aggregate failed only because the fixture used an unavailable assertion overload; the test-only correction retains its exact Boolean predicate. Strict passive capture owns the final run's two PostgreSQL containers with inherited resource-session descriptor, no ownership gaps or observer errors, and neither container remaining afterward. This establishes a controlled temporal boundary at a real locking read, not measured physical contention, continuous production protection, genuine upstream authority, activation, admission or Entity delivery. + +### Original creator key acceptance + +Both fresh current-actor paths implement [Account's original creator callback authorization contract](../../architecture/microservices/account-service/api-contracts.md#original-creator-callback-authorization) in `AccountControlUiActorService`. + +The existing native original-order fixture proves missing-key and same-key-ID replacement refusal in both paths, accepted-original membership alongside another key, untrusted-source and protected-read failure refusal, and rejection before protected reads under ambient SQL or synchronization. Each parameter compares complete original row JSON and row version. Current snapshot membership is explicitly stipulated through the same concrete source fixture; the source-failure cases execute its real protected observation failure. This models accepted retiring-key membership and does not prove actual signer rotation, publication, withdrawal or compromise authority. At source `5c5363a5ba7caf3af5e6ca9dd93ea212ce3b0c5f`, all fourteen parameters, seven existing native time/equality/recovery cases, the healthy secured Account owner case and seven existing Actor unit cases pass: twenty-nine fresh cases with zero failures, errors or skips. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test-only old-code source `fff5a48653bbcf6e0cd04610dd264c9e1b65c243` first preserves the original row, then fails all four missing/replaced-key callback-denial assertions. The successful run’s strict passive observer owns two PostgreSQL containers with an inherited resource-session descriptor, no ownership gaps or observer errors, and both containers absent afterward. These are bounded component proofs, without genuine upstream authority, runtime registration, gameplay admission or Entity delivery. + +### Original Logging claim-read client + +The existing Account StartSession reservation-evidence client pins the configured Logging & Admin workload URI with the shared pre-request credentials and response verifier. It uses workload-only mTLS without the generic bearer-token stub customizer, rejects caller context and ambient SQL transactions or synchronization before RPC, and preserves the original tuple, purpose, deadline and exact response binding checks. The server identity comes from the existing configured workload namespace, independently of the mutation target namespace. Usable configured certificate, key and CA resources are required without adding a universal regular-file storage restriction; the existing default-off registration stays unchanged. + +The focused source `3357125badc6ad36f6d2e77ea1105685960e86c4` passes ten secured-client cases, two fixture child-process cases, the default-off bean-definition case and the existing Account original-owner PostgreSQL case: fourteen fresh cases with zero failures, errors or skips. Actual loopback mTLS rejects wrong workload, wrong namespace or missing server URI before request delivery; plaintext, missing client credentials, caller context and ambient SQL/synchronization are denied separately. The native owner case uses the actual Logging socket and certificate-derived approved Account leaf; remaining inbound Account and upstream authority contexts stay controlled. Its strict passive observer owns the single run-created PostgreSQL container with the inherited resource-session descriptor, no ownership gaps or observer errors, and no remaining container after completion. Affected main, unit, integration and test-fixture static analysis, formatting and documentation checks pass. The test PKI helper now waits within its deadline before reading child output, then terminates and reaps on timeout or interruption while preserving interrupt status; the two new cases prove those paths with actual stalled JDK children. Earlier client/owner passes did not establish this child-process deadline. These controlled component results do not establish genuine creator, issuer, environment or PKI authority, deployed registration, gameplay admission, Entity placement or any genuine handoff. + +### Standalone activation receiver test PKI + +The purpose-specific PKI fixtures in the [activation acquisition receiver test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionActivationProtectionAcquisitionGrpcMtlsTest.java) and [World participation settlement receiver test](../../../services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java) now redirect child output to an owned temporary file and wait within the execution deadline before reading it. Timeout or interruption terminates and reaps the child within the bounded cleanup wait and preserves interrupt status. The existing activation settlement receiver test consumes the corrected acquisition fixture; the World participation fixture retains its separate ownership. + +At source `7bc64728ded6619058c926e93ee58f693ae440a5`, all twelve selected cases pass freshly with zero failures, errors or skips: four actual stalled-JDK-child timeout/interruption cases and eight controlled-PKI loopback receiver cases across those three suites. Affected unit static analysis and formatting pass. The receivers use mocked Account owners; acquisition and activation settlement exercise authenticated caller access to malformed-request decoding, while World participation reaches its controlled owner lookup or rejects invalid callers. These results do not establish successful real settlement, owner SQL, genuine PKI or upstream authority, runtime registration or a genuine Gameplay handoff. The prior Logging client and native owner proofs retain their separate source attribution. + +### Selected publication owner preparation + +Activation settlement preserves the canonical source-first lock order: the repository locks exact original source keys in Java canonical order with NOWAIT before locking and rereading the immutable protection row. The focused PostgreSQL refusal fixture controls historical lookup and terminal evidence to exercise only source contention, lock ordering, rollback and absence of settlement effects; it does not prove authenticated terminal production or a complete Java settlement write/readback. + +The disclosure source-lock adapter preserves complete keys through the canonical 2,048 UTF-8 byte bound already owned by shared source evidence and V76 storage. It no longer applies the obsolete 512-byte Java limit. The focused unit covers legacy and longer keys, ASCII and Unicode at the exact byte boundary, and rejection beyond it without truncation or aliasing; physical source-lock and disclosure behavior retain their separately attributed native proof. + +The isolated continuation prepares Account's distinct selected-publication order, exact HELD read and authenticated two-terminal settlement composition over existing authorization/settlement storage. The owner reuses current creator issuance, sorted source locks and writer-exclusion guards; the typed Game Design order read completes before Account's local producer transaction. R14 freshly passes eleven focused Account native cases and the real six-store Game Design/World terminal-to-Account settlement composition, including refusal before World completion, exact post-commit receipt replay and nine malformed closure/profile refusals. The latter uses both actual terminal owners and mTLS reads; the local inbound Account caller context remains explicitly controlled. Forward V1011 accepts only the canonical paired legacy and closure inventory profiles, preserving the existing frame, correlation, source and artifact guards. No installed migration is rewritten. + +R16 freshly passes the added V1010-to-current retained-settlement upgrade case for both original terminal outcomes after the test fixture explicitly supports that predecessor. Authorization, source, settlement, issuer and prior Flyway rows retain their exact bytes and row versions through upgrade and replay. The other twelve passing native cases retain R14 attribution; all have zero skips. Account's twenty-five focused units and Common's seven typed-order units retain their preceding pass, and affected generation, static, formatting and documentation checks pass. R14's passive capture owns all eight exact run-created PostgreSQL containers; R16 owns its one, with no ownership gaps or observer errors. Upstream creator, issuer, environment and PKI remain controlled. These owners remain unregistered and grant no publication finalizer, player admission, genuine authority or runtime activation. + +ActualOrderR2 freshly passes the six-store owner composition with actual Game Design-to-Account selected-publication ordering and Account-to-Game-Design immutable selection reads over mTLS. Account captures the environment internally and authenticates the original creator through its existing owner. A controlled Game Design transport outage creates no authorization/source/settlement state and preserves the original issuer rows and row versions. Successful ordering and exact retry retain one held order and unchanged binding/source rows from the single committed issuance; the returned actual order then drives fresh World freeze, publication and exact both-owner terminal settlement. One fresh native case passes with zero skips, six exact PostgreSQL containers passively owned and no observer gaps or errors; affected compilation, static analysis and formatting pass. No new production code, migration, registration or runtime authority is added. Upstream creator, issuer, environment and PKI remain controlled, and the local inbound settlement caller context remains a separate controlled component seam. + ### Selected recipient source intake preparation This preparation is owned by [AA-1.3](#capability-status), which remains `partial` / `drift-found`. Its production and focused proof anchors are recorded in that row. @@ -72,6 +122,8 @@ Focused proof is split by unchanged source attribution: twelve shared validator ### Original StartSession source-protection storage +Preceding isolated receiving qualification at `9f48ef606ffe1f73d99adc17f9f88dbb5677624e` on immutable #2967 input `ec4ca374f95d94c130d3578269744477f20b8085` passes 34 focused physical PostgreSQL cases: 18 admission, nine activation and seven credential-cleanup cases, with zero failures, errors or skips. Affected integration static analysis, formatting and documentation checks pass. This canonical lineage installs complete original-tuple byte equality and the independent nested issuance-operation identity checks directly in V1003; it does not install the historical donor V163-to-V164 scalar-guard replacement. The passing canonical predecessor proof retains the actual 112-script history, row bytes and metadata, relation/function identities and prior guard definitions. The activation suite additionally defines a direct contradictory-owner-issuance regression alongside the existing admission case; upstream rows are deliberately stipulated while current acquisition guards remain enabled. These are controlled Account integrity checks and do not establish genuine creator/issuer/environment continuity, authenticated World production, activation or any Gameplay handoff. + The bounded V1003 receiving cut, hardened by forward V1004, adds passive Account admission and activation protection storage and immutable terminal-settlement integrity, while preserving every canonical parent migration and original owner evidence. Its existing source-writer hooks retain World participation and other published owner guards. Forward [Account V1007 preliminary selected-owner reservation storage and source-writer hooks](../../../services/account-service/src/main/resources/db/migration/V1007__selected_owner_intake_source_reservations.sql) are now received for Entity and Automation participation. Forward V1008–V1010 prepare finalized owner authorization/recovery and exact terminal settlement, with focused owner-storage and upgrade proof; this receiving stage also prepares bounded recovery for expired abandoned preliminary reservations. Authenticated cross-owner composition, full qualification and registration remain open as recorded in the [selected-recipient intake tracker](#selected-recipient-source-intake-preparation). AA-1.3 stays `partial` / `drift-found`; all genuine Gameplay handoffs remain open and broader Unit 1B remains paused. The pre-review preparation on actual develop `d0b0743c09e15aeeffd52bde4aa0e8fca159c40c` passed all 15 focused Account PostgreSQL cases with zero failures/errors/skips: 13 admission and two activation cases, including the default-location fresh 113-artifact manifest and unchanged actual 112-artifact parent upgrade. jOOQ generation, compilation, formatting, Checkstyle, integration SpotBugs and documentation checks pass. The broader local 236-case Account integration run had two unavailable endpoint fixtures and remains a failed local gate; identical Account/Common/proto/build inputs at published `a1a6d13f0f4953261e1fdd7154f50f83e17be84e` pass the own Account source-CI artifact 11822625688 with 240 integration cases (zero failures, errors or skips) and 1,295 unit cases (zero failures or errors, four existing filesystem skips). Fresh rebuilt images also pass both unchanged legacy LOGIN/PLAY/LOOK transport baselines. These results qualify the bounded protection storage and existing behavior only. Those pre-review results did not exercise the activation acquisition guards. The corrected [admission storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionAdmissionProtectionPostgresIntegrationTest.java) and [activation storage suite](../../../services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java) stipulate upstream data while leaving the protection/source-writer guards enabled; they establish no genuine owner production, authenticated terminal settlement, continuous canonical admission, actor placement or region delivery. Canonical obligations remain in [ADR 0047](../../architecture/decisions/adr-0047-logging-admin-as-external-operator-write-ingress.md), with local consequences in [Account Runtime and Data](../../architecture/microservices/account-service/runtime-and-data.md#original-startsession-source-protection-storage). diff --git a/design/project-management/implementation-tracking/world-runtime-and-movement.md b/design/project-management/implementation-tracking/world-runtime-and-movement.md index 43e5a853d9..c8d4531ac0 100644 --- a/design/project-management/implementation-tracking/world-runtime-and-movement.md +++ b/design/project-management/implementation-tracking/world-runtime-and-movement.md @@ -86,6 +86,8 @@ Registered mutation ingress remains refused. The existing internal mutation pref ### Selected publication World owner source +FreshBeginR3 freshly passes the six-store selected-publication composition with actual authenticated fresh World begin. The initial World owner is OPEN and no freeze attempt, Account correlation, inventory or canonical frozen capture exists. World independently reads the actual retained Game Design selection, source-qualified current Version and Account HELD through real mTLS handlers. A controlled Account transport outage leaves all five World owner tables and row versions unchanged. The successful request commits the original FROZEN checkpoint, Account correlation and complete inventory, then captures the exact canonical selector. Repeating the same begin with mutable upstream transports denied performs no further owner reads and preserves retained rows. The fixture's former manual freeze/capture is replaced by independent committed readback. The existing actual Game Design reservation, v4 bundle and terminal-to-Account settlement still execute in that one fresh native case, with zero failures, errors or skips. All six run-created PostgreSQL containers are passively owned without gaps or observer errors; affected compilation, static analysis and formatting pass. Upstream original source/APPLIED preparation, creator, issuer, environment and PKI remain controlled. This proves the fresh component path and does not register ingress, supply continuous production authority, implement failed-selection recovery or close any genuine handoff. + The standalone consumer succeeds the shared fence/Common foundation published in [PR #3217](https://github.com/benhook1013/FireMUD/pull/3217) at `8afceb8` on parent `7b2ce634`. Its 66-path scope contains 37 World production files, the existing Common codec and test, 20 World unit/transport files, one current-default PostgreSQL chain, the World Common test-fixtures dependency, four documentation files and an observation. All published migration postimages remain unchanged. Standalone unregistered components cover original Account-order-bound APPLIED application, selected freeze/checkpoint, immutable authored graph, complete artifact inventory, canonical selector/frozen graph, and default-denied terminal completion/readback. The terminal path uses the canonical `GameDesignPublicationTerminalClient` directly and denies UNKNOWN evidence. Existing cumulative V1014 supports exact six-family counts with owner-proved zeros; the selected source explicitly declares all seven inbound families empty. No new migration or generator registry was added, and unsupported nonempty generation rules remain denied. The [World runtime/data manifest](../../architecture/microservices/world-management-service/runtime-and-data.md#digest-input-manifest) owns family/input/digest storage, [procedural generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md#derived-world-artifact-publication) owns derived-artifact/read consequences, and the [World API contract](../../architecture/microservices/world-management-service/api-contracts.md#publication-freeze-and-terminal-handoff-target-state) owns operations. diff --git a/protos/account/v1/selected_publication_order_service.proto b/protos/account/v1/selected_publication_order_service.proto new file mode 100644 index 0000000000..a23b205803 --- /dev/null +++ b/protos/account/v1/selected_publication_order_service.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package account.v1; +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone, unregistered Game Design-only producer. No environment authority is caller supplied. +service AccountSelectedPublicationOrderService { + rpc AuthorizeSelectedPublication(AuthorizeSelectedPublicationRequest) + returns (AuthorizeSelectedPublicationResponse); +} + +message AuthorizeSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Transport correlation only; the selected publication request owns durable identity. + string request_id = 3; + bytes original_selection = 4; + // The original creator credential travels only in protected per-call metadata. + reserved 5; + reserved "original_creator_credential"; +} + +message AuthorizeSelectedPublicationResponse { + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_selection = 4; + bytes publication_authorization_binding = 5; +} diff --git a/protos/account/v1/selected_publication_settlement_service.proto b/protos/account/v1/selected_publication_settlement_service.proto new file mode 100644 index 0000000000..205166bb73 --- /dev/null +++ b/protos/account/v1/selected_publication_settlement_service.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package account.v1; + +option java_package = "net.firedevops.firemud.account.v1"; +option java_multiple_files = true; + +// Standalone authenticated settlement of one exact selected-publication authorization. +service AccountSelectedPublicationSettlementService { + rpc SettleSelectedPublication(SettleSelectedPublicationRequest) + returns (SettleSelectedPublicationResponse); +} + +message SettleSelectedPublicationRequest { + int32 schema_version = 1; + string target_namespace = 2; + // Independent transport correlation; the retained Account order remains the settlement key. + string request_id = 3; + // Complete canonical game-design-publication-operation/v2 bytes. + bytes original_operation = 4; +} + +message SettleSelectedPublicationResponse { + // Exact unchanged request echo. + int32 schema_version = 1; + string target_namespace = 2; + string request_id = 3; + bytes original_operation = 4; + // Existing six-frame account-selected-publication-settlement/v1 receipt. + bytes settlement_receipt = 5; +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java index 96fa1d078a..ec905e7362 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceRepository.java @@ -295,9 +295,9 @@ public void lockDisclosureSources(List exactSources) { throw new IllegalArgumentException("Distinct exact disclosure source evidence required"); } for (SourceEvidence source : sources) { - if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 512) { + if (source.key().getBytes(java.nio.charset.StandardCharsets.UTF_8).length > 2048) { throw new IllegalArgumentException( - "Disclosure source key exceeds the existing Account source-lock bound"); + "Disclosure source key exceeds the Account source-lock bound"); } } lockSources(sources); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java index ff072c2bf7..08fc966d17 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClient.java @@ -12,17 +12,23 @@ import javax.net.ssl.SSLException; 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.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.common.grpc.GrpcTlsMaterialResolver; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.stereotype.Component; +import org.springframework.transaction.support.TransactionSynchronizationManager; /** * Reads and validates Logging/Admin's current StartSession reservation claim snapshot. @@ -43,30 +49,30 @@ public final class StartSessionReservationEvidenceClient private static final long CALL_DEADLINE_SECONDS = 5L; private static final UUID NIL_UUID = new UUID(0L, 0L); + private final String expectedLoggingPeerUri; private final Clock clock; + private final CommonGrpcClientProperties transportTlsProperties; @Autowired public StartSessionReservationEvidenceClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer) { - this(endpoints, tlsProperties, channelFactory, stubCustomizer, Clock.systemUTC()); + @Value("${firemud.grpc.workload-namespace:}") String workloadNamespace) { + this(endpoints, tlsProperties, channelFactory, workloadNamespace, Clock.systemUTC()); } StartSessionReservationEvidenceClient( ServiceEndpointsProperties endpoints, CommonGrpcClientProperties tlsProperties, GrpcChannelFactory channelFactory, - BlockingGrpcStubCustomizer stubCustomizer, + String workloadNamespace, Clock clock) { - super( - endpoints, - tlsProperties, - channelFactory, - stubCustomizer, - StartSessionReservationEvidenceClient.class); + super(endpoints, tlsProperties, channelFactory, StartSessionReservationEvidenceClient.class); + this.expectedLoggingPeerUri = loggingAdminServerUri(workloadNamespace); this.clock = Objects.requireNonNull(clock, "clock is required"); + this.transportTlsProperties = + Objects.requireNonNull(tlsProperties, "TLS properties are required").copy(); } @PostConstruct @@ -88,9 +94,10 @@ protected String defaultTarget() { protected StartSessionReservationEvidenceServiceGrpc .StartSessionReservationEvidenceServiceBlockingStub buildStub(io.grpc.ManagedChannel channel) { - return applyStubCustomizer( - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) - .withCompression("gzip")); + return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedLoggingPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedLoggingPeerUri)) + .withCompression("gzip"); } /** Reads the exact active claim for ISSUE or RECOVER and validates every returned binding. */ @@ -101,6 +108,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( UUID currentClaimOwnerId, long currentClaimFence, Purpose purpose) { + requireWorkloadOnlyContext(); Objects.requireNonNull(tuple, "reservation tuple is required"); requireNonNilUuid(reservationOwnerId, "reservationOwnerId"); requireNonNilUuid(currentClaimOwnerId, "currentClaimOwnerId"); @@ -123,6 +131,7 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( .setPurpose(toWirePurpose(purpose)) .build(); + requireWorkloadMtls(); var currentStub = stub(); if (currentStub == null) { throw new IllegalStateException("Logging/Admin reservation evidence client is unavailable"); @@ -143,6 +152,47 @@ public ReadCurrentClaimEvidenceResponse readCurrentClaimEvidence( return response; } + static String loggingAdminServerUri(String targetNamespace) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("StartSession target namespace is invalid"); + } + return "spiffe://firemud/ns/" + targetNamespace + "/sa/logging-admin-service"; + } + + private void requireWorkloadMtls() { + if (transportTlsProperties.isPlaintext()) { + throw new IllegalStateException("Logging/Admin reservation evidence requires workload mTLS"); + } + try { + var material = new GrpcTlsMaterialResolver().resolve(transportTlsProperties); + if (material == null) { + throw new IllegalStateException("Missing workload TLS material"); + } + try (var certificate = material.certChain().openStream(); + var privateKey = material.privateKey().openStream(); + var ca = material.caCert().openStream()) { + if (certificate.read() < 0 || privateKey.read() < 0 || ca.read() < 0) { + throw new IllegalStateException("Empty workload TLS material"); + } + } + } catch (IOException | RuntimeException unavailable) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires usable workload mTLS", unavailable); + } + } + + private static void requireWorkloadOnlyContext() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires no ambient SQL or synchronization"); + } + if (SessionContext.hasAuthenticatedCallerContext()) { + throw new IllegalStateException( + "Logging/Admin reservation evidence requires a workload-only caller context"); + } + } + private void validateResponse( ReadCurrentClaimEvidenceResponse response, StartSessionPreAuthorizationReservationTuple tuple, diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java index ff49f47dc6..439fd2c64e 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionRepository.java @@ -211,6 +211,16 @@ public StoredSettlement settleExact( accountEvidence.accountProtectionId(), accountEvidence.accountProtectionFence()) .orElseThrow(AccountStartSessionActivationProtectionRepository::unavailable); requireSameEvidence(protection.evidence(), accountEvidence); + lockOriginalSourceRows(protection.evidence()); + Record locked = + dsl.fetchOne( + "SELECT * FROM " + + PROTECTIONS + + " WHERE activation_protection_id = ? FOR UPDATE NOWAIT", + accountEvidence.accountProtectionId()); + if (locked == null) throw unavailable(); + protection = decodeProtection(locked, readSources(accountEvidence.accountProtectionId())); + requireSameEvidence(protection.evidence(), accountEvidence); dsl.execute( "INSERT INTO " @@ -240,6 +250,22 @@ public StoredSettlement settleExact( return stored; } + private void lockOriginalSourceRows(AccountStartSessionActivationProtectionEvidence evidence) { + for (SourceEvidence source : + evidence.sourceEvidenceVector().stream() + .sorted(java.util.Comparator.comparing(SourceEvidence::key)) + .toList()) { + Record locked = + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks " + + "WHERE source_key = ? FOR UPDATE NOWAIT", + source.key()); + if (locked == null || !source.key().equals(text(locked, "source_key"))) { + throw unavailable(); + } + } + } + private Record selectProtectionByRequestId(String requestId) { return dsl.fetchOne( "SELECT * FROM " + PROTECTIONS + " WHERE control_plane_request_id = ?", requestId); diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java index 2c42841b14..c441393805 100644 --- a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiActorService.java @@ -144,6 +144,7 @@ T withCurrent( Function action) { outsideSql(); var signed = verifySigned(compactJwt); + var acceptedKey = readAcceptedSignerKey(signed.claims.keyId()); String tokenHash = AccountControlUiIssuanceRepository.hash(compactJwt.getBytes(StandardCharsets.US_ASCII)); byte[] exactRegistry = registry.readActive(tokenHash); @@ -159,6 +160,7 @@ T withCurrent( throw denied(); } requireSignerIdentity(stored, signed); + requireAcceptedSignerKey(stored, acceptedKey); signers.requireOriginal(stored.signerReceipt); var current = authority.capture(stored.accountId, selectedTenant, environment); if (!Arrays.equals(current.evidence(), stored.sources)) { @@ -168,6 +170,7 @@ T withCurrent( if (!committed.tokenHash().equals(tokenHash)) { throw denied(); } + requireCurrentOriginalToken(stored); return action.apply(new Current(stored, current)); }); } @@ -202,6 +205,13 @@ T withCurrentCommitted( throw denied(); } + Object receiptKeyId = + AccountControlUiIssuanceRepository.object(original.signerReceipt).get("kid"); + if (!(receiptKeyId instanceof String keyId)) { + throw denied(); + } + var acceptedKey = readAcceptedSignerKey(keyId); + requireAcceptedSignerKey(original, acceptedKey); byte[] exactRegistry = registry.readActive(original.tokenHash); return transaction.execute( ignored -> { @@ -223,10 +233,44 @@ T withCurrentCommitted( || !Arrays.equals(committed.activeRegistry, exactRegistry)) { throw denied(); } + requireCurrentOriginalToken(committed); return action.apply(new Current(committed, current)); }); } + /** + * One protected snapshot per fresh call; this does not promise acceptance through later locks. + */ + private AcceptedSignerKey readAcceptedSignerKey(String keyId) { + outsideSql(); + String fingerprint = + AccountJwtJwksTrustedSource.publicKeyFingerprint( + publicSource.load(), publicSourcePin, keyId) + .orElseThrow(AccountControlUiActorService::denied); + return new AcceptedSignerKey(keyId, fingerprint); + } + + private static void requireAcceptedSignerKey( + AccountControlUiIssuanceRepository.Stored original, AcceptedSignerKey accepted) { + var receipt = AccountControlUiIssuanceRepository.object(original.signerReceipt); + if (!accepted.keyId().equals(receipt.get("kid")) + || !accepted.fingerprint().equals(receipt.get("publicKeyFingerprint"))) { + throw denied(); + } + } + + private record AcceptedSignerKey(String keyId, String fingerprint) {} + + private void requireCurrentOriginalToken(AccountControlUiIssuanceRepository.Stored original) { + var now = clock.instant(); + if (original.issuedAt == null + || original.expiresAt == null + || now.isBefore(original.issuedAt) + || !now.isBefore(original.expiresAt)) { + throw denied(); + } + } + /** Production asymmetric/profile verification, also used before any candidate is persisted. */ SignedObservation verifySigned(String compactJwt) { outsideSql(); @@ -365,8 +409,9 @@ public String toString() { } private static void outsideSql() { - if (TransactionSynchronizationManager.isActualTransactionActive()) { - throw new IllegalStateException("Signature/registry reads must precede owner SQL locks"); + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Signature/registry/JWKS reads must precede owner SQL locks"); } } diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java new file mode 100644 index 0000000000..3bedfb6d7e --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadGrpcService.java @@ -0,0 +1,78 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountPublicationAuthorizationReadServiceGrpc; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadGrpcCodec; + +/** Standalone endpoint only: peer authentication precedes decoding and persistence lookup. */ +public final class AccountPublicationAuthorizationReadGrpcService + extends AccountPublicationAuthorizationReadServiceGrpc + .AccountPublicationAuthorizationReadServiceImplBase { + private final AccountPublicationAuthorizationReadService owner; + private final String trustedNamespace; + + public AccountPublicationAuthorizationReadGrpcService( + AccountPublicationAuthorizationReadService owner, String trustedNamespace) { + this.owner = Objects.requireNonNull(owner); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + } + + @Override + public void readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest request, + StreamObserver observer) { + try { + AccountPublicationAuthorizationReadService.requirePeer(trustedNamespace); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + final net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request + decoded; + try { + decoded = AccountPublicationAuthorizationReadGrpcCodec.fromRequest(request); + } catch (IllegalArgumentException malformed) { + observer.onError( + Status.INVALID_ARGUMENT + .withDescription("Canonical Account publication read required") + .asRuntimeException()); + return; + } + if (!trustedNamespace.equals(decoded.targetNamespace())) { + observer.onError( + Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException()); + return; + } + final ReadHeldPublicationAuthorizationResponse response; + try { + owner.requireHeld(decoded); + response = AccountPublicationAuthorizationReadGrpcCodec.toHeldResponse(decoded); + } catch (StatusRuntimeException failure) { + observer.onError( + Status.fromCode(Status.fromThrowable(failure).getCode()) + .withDescription("Account publication authorization owner read denied or unavailable") + .asRuntimeException()); + return; + } catch (RuntimeException unavailable) { + observer.onError( + Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException()); + return; + } + observer.onNext(response); + observer.onCompleted(); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java new file mode 100644 index 0000000000..df26c62b31 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** Unregistered owner read of a distinct retained publication order; never a terminal result. */ +public final class AccountPublicationAuthorizationReadService { + private final AccountPublicationAuthorizationRepository repository; + private final String trustedNamespace; + private final TransactionTemplate ownerTransaction; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") + public AccountPublicationAuthorizationReadService( + AccountPublicationAuthorizationRepository repository, + PlatformTransactionManager transactions, + String trustedNamespace) { + this.repository = Objects.requireNonNull(repository); + if (!GrpcPeerIdentity.isValidNamespace(trustedNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.trustedNamespace = trustedNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactions)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + public void requireHeld(AccountPublicationAuthorizationReadEvidence.Request request) { + requirePeer(trustedNamespace); + Objects.requireNonNull(request); + if (!trustedNamespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED + .withDescription("Account publication namespace differs from peer") + .asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Independent Account publication owner transaction required") + .asRuntimeException(); + } + try { + ownerTransaction.execute( + status -> { + repository.readHeld(request.binding()); + return null; + }); + } catch (StatusRuntimeException failure) { + throw failure; + } catch (IllegalArgumentException inconsistent) { + throw Status.FAILED_PRECONDITION + .withDescription("Exact held Account publication authorization unavailable") + .asRuntimeException(); + } catch (RuntimeException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Account publication owner read unavailable") + .asRuntimeException(); + } + } + + static void requirePeer(String namespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + String peerUri = peer.uri(); + if (SessionContext.hasAuthenticatedCallerContext() + || (!("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peerUri) + && !("spiffe://firemud/ns/" + namespace + "/sa/world-management-service") + .equals(peerUri))) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design or World Management workload required") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java new file mode 100644 index 0000000000..1f326c852d --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationRepository.java @@ -0,0 +1,333 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.sql.Connection; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Internal owner-transaction storage; remote evidence must first be authenticated by composition. + */ +public final class AccountPublicationAuthorizationRepository { + private final DSLContext dsl; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner persistence collaborator.") + public AccountPublicationAuthorizationRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl); + } + + AccountPublicationAuthorizationBinding authorize( + AccountPublicationAuthorizationBinding.PreallocationInput input, + AccountControlUiActorService.Current current, + Runnable admission) { + requireTransaction(); + Record prior = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE tenant_uuid = ? AND publish_request_id = ? FOR UPDATE", + current.stored().tenantId, + input.selection().intent().publishRequestId()); + if (prior != null) { + var original = + AccountPublicationAuthorizationBinding.fromStored(prior.get("binding", byte[].class)); + requireExact(prior, original, input, current); + return original; + } + admission.run(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), UUID.randomUUID(), input, current.source().sources()); + dsl.execute( + "INSERT INTO account_selected_publication_authorizations" + + " (operation_id, fence_id, actor_account_uuid, tenant_uuid, publish_request_id," + + " input_digest, binding, issuance_operation_id, issuance_fence," + + " source_payload, issuance_bundle, outbox_checkpoints) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + binding.operationId(), + binding.fenceId(), + input.actorAccountId(), + binding.tenantId(), + binding.publishRequestId(), + input.digest(), + binding.canonicalBytes(), + current.stored().operationId, + current.source().issuanceFence(), + current.stored().sources, + current.stored().bundle, + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints())); + for (var source : binding.sources()) { + dsl.execute( + "INSERT INTO account_selected_publication_sources" + + " (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + source.key(), + source.canonicalBytes()); + } + Record retained = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations WHERE operation_id = ? FOR UPDATE", + binding.operationId()); + requireExact(retained, binding, input, current); + return binding; + } + + /** Exact owner read; caller-carried structure alone can never establish HELD. */ + public void readHeld(AccountPublicationAuthorizationBinding requested) { + readOriginal(requested); + if (dsl.fetchOne( + "SELECT 1 FROM account_selected_publication_settlements WHERE operation_id = ?", + requested.operationId()) + != null) { + throw new IllegalArgumentException("Publication authorization is already settled"); + } + } + + /** Historical validation uses the original committed issuance, never current credentials. */ + private void readOriginal(AccountPublicationAuthorizationBinding requested) { + requireTransaction(); + Objects.requireNonNull(requested); + // Sources precede the operation. No transport is permitted in this owner transaction. + for (var source : + requested.sources().stream() + .sorted( + java.util.Comparator.comparing(DraftAuthorizationFenceBinding.SourceEvidence::key)) + .toList()) { + if (dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks" + + " WHERE source_key = ? FOR UPDATE", + source.key()) + == null) { + throw new IllegalArgumentException("Original publication source lock is absent"); + } + } + Record row = + dsl.fetchOne( + "SELECT * FROM account_selected_publication_authorizations" + + " WHERE operation_id = ? FOR UPDATE", + requested.operationId()); + if (row == null + || !Arrays.equals(requested.canonicalBytes(), row.get("binding", byte[].class))) { + throw new IllegalArgumentException("Exact held publication authorization is absent"); + } + var retained = + AccountPublicationAuthorizationBinding.fromStored(row.get("binding", byte[].class)); + validateRetainedWorldIfPresent(row, retained); + // Issuance producers acquire this row before source capture. Do not wait backwards while + // holding sources; a concurrent issuer/source writer must cause a retry, never a lock cycle. + Record issuance = + dsl.fetchOne( + "SELECT * FROM account_control_ui_issuance_operations" + + " WHERE operation_id = ? FOR UPDATE NOWAIT", + row.get("issuance_operation_id", UUID.class)); + if (issuance == null) { + throw new IllegalArgumentException("Original committed issuance is absent"); + } + var originalIssuer = new AccountControlUiIssuanceRepository.Stored(issuance); + var bundle = AccountControlUiIssuanceRepository.object(originalIssuer.bundle); + var sources = AccountControlUiIssuanceRepository.object(originalIssuer.sources); + var rawVector = sources.get("sources"); + if (!"COMMITTED".equals(originalIssuer.status) + || !retained.operationId().equals(row.get("operation_id", UUID.class)) + || !retained.fenceId().equals(row.get("fence_id", UUID.class)) + || !retained.input().actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !retained.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !retained.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !retained.input().digest().equals(row.get("input_digest", String.class)) + || !retained.input().actorAccountId().equals(originalIssuer.accountId) + || !retained.tenantId().equals(originalIssuer.tenantId) + || !originalIssuer.operationId.equals(row.get("issuance_operation_id", UUID.class)) + || !Arrays.equals(originalIssuer.sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(originalIssuer.bundle, row.get("issuance_bundle", byte[].class)) + || !(bundle.get("issuanceFence") instanceof Number fence) + || fence.longValue() != row.get("issuance_fence", Long.class) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + bundle.get("outboxCheckpoints")), + row.get("outbox_checkpoints", byte[].class)) + || !originalIssuer.accountId.toString().equals(sources.get("accountId")) + || !originalIssuer.tenantId.toString().equals(sources.get("tenantId")) + || !(rawVector instanceof java.util.List vector) + || vector.size() != retained.sources().size()) { + throw new IllegalArgumentException("Changed original publication issuance evidence"); + } + var participation = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + retained.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (participation.size() != retained.sources().size()) { + throw new IllegalArgumentException("Incomplete original publication source participation"); + } + for (int i = 0; i < retained.sources().size(); i++) { + var source = retained.sources().get(i); + if (!(vector.get(i) instanceof String encoded) + || !Arrays.equals(source.canonicalBytes(), java.util.Base64.getDecoder().decode(encoded)) + || !source.key().equals(participation.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), participation.get(i).get("source_evidence", byte[].class))) { + throw new IllegalArgumentException("Changed original publication source participation"); + } + } + } + + /** + * Persist only after strict authenticated reads from both owners, outside this transaction. + * Structure alone is not owner authentication. World retains the same complete terminal bytes + * with PUBLISHED or ABORTED phase. Transport request IDs deliberately do not enter identity. + */ + public byte[] settle( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + requireTransaction(); + Objects.requireNonNull(operation, "operation"); + Objects.requireNonNull(gameDesign, "gameDesign"); + byte[] retainedWorldTerminal = + Objects.requireNonNull(worldTerminalEvidence, "worldTerminalEvidence").clone(); + String expectedPhase = + gameDesign.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!expectedPhase.equals(worldOutcome) + || !Arrays.equals(operation.canonicalBytes(), gameDesign.operationBytes()) + || !Arrays.equals(gameDesign.canonicalBytes(), retainedWorldTerminal)) { + throw new IllegalArgumentException("Exact publication owner outcomes disagree"); + } + readOriginal(operation.account()); + byte[] receipt = settlementReceipt(operation, gameDesign, worldOutcome, retainedWorldTerminal); + Record prior = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (prior != null) { + if (!Arrays.equals(receipt, prior.get("receipt", byte[].class))) { + throw new IllegalArgumentException("Changed original publication settlement"); + } + return prior.get("receipt", byte[].class); + } + dsl.execute( + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation," + + " game_design_outcome, game_design_terminal, world_outcome, world_terminal, receipt)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + operation.account().operationId(), + operation.account().fenceId(), + operation.account().canonicalBytes(), + operation.canonicalBytes(), + gameDesign.outcome().name(), + gameDesign.canonicalBytes(), + worldOutcome, + retainedWorldTerminal, + receipt); + Record retained = + dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + operation.account().operationId()); + if (retained == null || !Arrays.equals(receipt, retained.get("receipt", byte[].class))) { + throw new IllegalStateException("Exact publication settlement readback is absent"); + } + return retained.get("receipt", byte[].class); + } + + private static byte[] settlementReceipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence gameDesign, + String worldOutcome, + byte[] worldTerminalEvidence) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, gameDesign.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, worldOutcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminalEvidence); + return out.toByteArray(); + } + + private void requireExact( + Record row, + AccountPublicationAuthorizationBinding binding, + AccountPublicationAuthorizationBinding.PreallocationInput input, + AccountControlUiActorService.Current current) { + validateRetainedWorldIfPresent(row, binding); + if (row == null + || !binding.operationId().equals(row.get("operation_id", UUID.class)) + || !binding.fenceId().equals(row.get("fence_id", UUID.class)) + || !input.actorAccountId().equals(row.get("actor_account_uuid", UUID.class)) + || !binding.tenantId().equals(row.get("tenant_uuid", UUID.class)) + || !binding.publishRequestId().equals(row.get("publish_request_id", String.class)) + || !input.digest().equals(row.get("input_digest", String.class)) + || !Arrays.equals(input.canonicalBytes(), binding.input().canonicalBytes()) + || !Arrays.equals(binding.canonicalBytes(), row.get("binding", byte[].class)) + || !current.stored().operationId.equals(row.get("issuance_operation_id", UUID.class)) + || current.source().issuanceFence() != row.get("issuance_fence", Long.class) + || !Arrays.equals(current.stored().sources, row.get("source_payload", byte[].class)) + || !Arrays.equals(current.stored().bundle, row.get("issuance_bundle", byte[].class)) + || !Arrays.equals( + net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority.canonical( + current.source().outboxCheckpoints()), + row.get("outbox_checkpoints", byte[].class))) { + throw new IllegalArgumentException("Changed immutable selected-publication authorization"); + } + var stored = + dsl + .fetch( + "SELECT source_key, source_evidence FROM account_selected_publication_sources" + + " WHERE operation_id = ?", + binding.operationId()) + .stream() + .sorted(java.util.Comparator.comparing(r -> r.get("source_key", String.class))) + .toList(); + if (stored.size() != binding.sources().size() + || stored.size() != current.source().sources().size()) { + throw new IllegalStateException("Incomplete publication source participation"); + } + for (int i = 0; i < stored.size(); i++) { + var source = binding.sources().get(i); + if (!source.key().equals(stored.get(i).get("source_key", String.class)) + || !Arrays.equals( + source.canonicalBytes(), stored.get(i).get("source_evidence", byte[].class)) + || !Arrays.equals( + source.canonicalBytes(), current.source().sources().get(i).canonicalBytes())) { + throw new IllegalArgumentException("Changed original publication source vector"); + } + } + } + + /** + * Historical pre-freeze World evidence remains immutable and is checked when a row contains it. + */ + private static void validateRetainedWorldIfPresent( + Record row, AccountPublicationAuthorizationBinding binding) { + byte[] worldEvidence = row == null ? null : row.get("world_evidence", byte[].class); + if (worldEvidence != null) { + GameDesignPublicationOperationBinding.requireAccountWorldCorrelation( + binding, WorldPublishedStartLocationEvidence.fromStored(worldEvidence)); + } + } + + private static void requireTransaction() { + if (!TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isCurrentTransactionReadOnly() + || !Objects.equals( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel(), + Connection.TRANSACTION_READ_COMMITTED)) { + throw new IllegalStateException("Writable READ_COMMITTED Account owner transaction required"); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java new file mode 100644 index 0000000000..6e51691691 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationService.java @@ -0,0 +1,50 @@ +package net.firedevops.firemud.accountservice.service.session; + +import java.util.Objects; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; + +/** + * Unregistered Account producer for a distinct selected-publication order. Authenticates the + * current initial creator through the real issuance owner and retains the immutable Draft selection + * before World freezes it. World capture and correlation are a separate later boundary. No remote + * calls, terminalization, or activation occur here. + */ +public final class AccountPublicationAuthorizationService { + private final AccountControlUiActorService actors; + private final DraftAuthorizationFenceRepository fences; + private final AccountPublicationAuthorizationRepository publications; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal Account owner transaction collaborators.") + public AccountPublicationAuthorizationService( + AccountControlUiActorService actors, + DraftAuthorizationFenceRepository fences, + AccountPublicationAuthorizationRepository publications) { + this.actors = Objects.requireNonNull(actors); + this.fences = Objects.requireNonNull(fences); + this.publications = Objects.requireNonNull(publications); + } + + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding selection, + CapturedEnvironmentBoundary environment) { + Objects.requireNonNull(selection); + return actors.withCurrent( + compactJwt, + selection.intent().canonicalTenantId(), + environment, + current -> { + fences.lockProducerSourcesNowait(current.source().sources()); + return publications.authorize( + new AccountPublicationAuthorizationBinding.PreallocationInput( + current.stored().accountId, selection), + current, + () -> fences.requirePublicationAdmission(current.source().sources())); + }); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java new file mode 100644 index 0000000000..e8f7b6a823 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcService.java @@ -0,0 +1,162 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.BindableService; +import io.grpc.Context; +import io.grpc.Contexts; +import io.grpc.Metadata; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.ServerServiceDefinition; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone, unregistered producer; Account obtains environment authority internally. Any future + * receiving server must allow at least {@link + * AccountSelectedPublicationOrderGrpcCodec#MAX_METADATA_BYTES} inbound metadata before registering + * this service; binding it does not configure that server limit. + */ +public final class AccountSelectedDraftPublicationOrderGrpcService implements BindableService { + private final AccountSelectedDraftPublicationOrderService owner; + private final AccountHostedTermsService terms; + private final String namespace; + + public AccountSelectedDraftPublicationOrderGrpcService( + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms, + String namespace) { + this.owner = Objects.requireNonNull(owner); + this.terms = Objects.requireNonNull(terms); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + /** + * Binding always includes the method-local credential interceptor; peer identity runs outside it. + */ + @Override + public ServerServiceDefinition bindService() { + var handler = + new AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceImplBase() { + @Override + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest request, + StreamObserver observer) { + AccountSelectedDraftPublicationOrderGrpcService.this.authorizeSelectedPublication( + request, observer); + } + }; + return ServerInterceptors.intercept( + handler, + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, Metadata headers, ServerCallHandler next) { + Status denied = peerDenial(); + if (denied != null) { + call.close(sanitized(denied), new Metadata()); + return new ServerCall.Listener<>() {}; + } + final AccountSelectedPublicationOrderCredentials.Credential credential; + try { + credential = AccountSelectedPublicationOrderCredentials.readAuthenticated(headers); + } catch (IllegalArgumentException malformed) { + call.close(sanitized(Status.UNAUTHENTICATED), new Metadata()); + return new ServerCall.Listener<>() {}; + } + var context = + Context.current() + .withValue(AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, credential); + return Contexts.interceptCall(context, call, headers, next); + } + }); + } + + public void authorizeSelectedPublication( + AuthorizeSelectedPublicationRequest wire, + StreamObserver observer) { + Status denied = peerDenial(); + if (denied != null) { + deny(observer, denied); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + final AccountSelectedPublicationOrderGrpcCodec.Request request; + final String credential; + try { + var protectedCredential = AccountSelectedPublicationOrderCredentials.CONTEXT_KEY.get(); + if (protectedCredential == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + credential = protectedCredential.value(); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + try { + request = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, credential); + } catch (IllegalArgumentException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + final AuthorizeSelectedPublicationResponse response; + try { + var captured = terms.captureCurrentEnvironmentBoundary(); + var binding = + owner.authorize(request.originalCreatorCredential(), request.selection(), captured); + response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + } catch (StatusRuntimeException failure) { + deny(observer, Status.fromCode(failure.getStatus().getCode())); + return; + } catch (IllegalArgumentException conflict) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + return; + } + observer.onNext(response); + observer.onCompleted(); + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError(sanitized(status).asRuntimeException()); + } + + private Status peerDenial() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) return Status.UNAUTHENTICATED; + if (SessionContext.hasAuthenticatedCallerContext()) return Status.PERMISSION_DENIED; + return ("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri()) + ? null + : Status.PERMISSION_DENIED; + } + + private static Status sanitized(Status status) { + return status.withDescription("Account selected-publication order denied or unavailable"); + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java new file mode 100644 index 0000000000..45180b793b --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderService.java @@ -0,0 +1,88 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Standalone, unregistered composition of authenticated Game Design selection read and distinct + * Account publication ordering. SELECTED attests immutable reservation only; Account's existing + * owner primitive remains the authority for the original creator, currentness and source holds. + * World freeze/capture, settlement and runtime admission are separate boundaries. + */ +public final class AccountSelectedDraftPublicationOrderService { + private final AuthoredDraftPublishSelectionReadClient selectionClient; + private final AccountPublicationAuthorizationService owner; + private final String workloadNamespace; + + public AccountSelectedDraftPublicationOrderService( + AuthoredDraftPublishSelectionReadClient selectionClient, + AccountPublicationAuthorizationService owner, + String workloadNamespace) { + this.selectionClient = Objects.requireNonNull(selectionClient, "selectionClient"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + /** + * The caller's selection is lookup data. Only the exact authenticated Game Design read is passed + * to Account's local producer, with the original creator JWT and environment unchanged. The + * remote read completes before the producer opens its own owner transaction. + */ + public AccountPublicationAuthorizationBinding authorize( + String compactJwt, + AuthoredDraftPublishSelectionBinding lookupSelection, + CapturedEnvironmentBoundary environment) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + Objects.requireNonNull(lookupSelection, "lookupSelection"); + var request = + AuthoredDraftPublishSelectionReadEvidence.Request.create( + workloadNamespace, lookupSelection); + var evidence = selectionClient.read(request); + if (evidence == null + || !request.equals(evidence.request()) + || !Arrays.equals( + lookupSelection.canonicalBytes(), evidence.request().binding().canonicalBytes()) + || !lookupSelection.digest().equals(evidence.request().binding().digest())) { + throw new IllegalStateException( + "Authenticated Game Design selection differs from the exact publication order request"); + } + requireNoAmbientTransaction(); + return owner.authorize(compactJwt, evidence.request().binding(), environment); + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Selected publication ordering requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java new file mode 100644 index 0000000000..14ebe403b7 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementService.java @@ -0,0 +1,139 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered composition of two authenticated owner reads and Account's immutable receipt. + * Historical settlement grants neither creator authority nor runtime admission. + */ +public final class AccountSelectedDraftPublicationSettlementService { + private final AccountPublicationAuthorizationRepository repository; + private final GameDesignPublicationTerminalClient gameDesignClient; + private final WorldPublicationTerminalReadClient worldClient; + private final TransactionTemplate ownerTransaction; + private final String workloadNamespace; + + @edu.umd.cs.findbugs.annotations.SuppressFBWarnings( + value = "EI_EXPOSE_REP2", + justification = "Internal owner persistence and strict mTLS clients.") + public AccountSelectedDraftPublicationSettlementService( + AccountPublicationAuthorizationRepository repository, + GameDesignPublicationTerminalClient gameDesignClient, + WorldPublicationTerminalReadClient worldClient, + PlatformTransactionManager transactionManager, + String workloadNamespace) { + this.repository = Objects.requireNonNull(repository); + this.gameDesignClient = Objects.requireNonNull(gameDesignClient); + this.worldClient = Objects.requireNonNull(worldClient); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + ownerTransaction = new TransactionTemplate(Objects.requireNonNull(transactionManager)); + ownerTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + ownerTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + ownerTransaction.setReadOnly(false); + } + + /** Caller bytes identify the original order; only independent authenticated owners settle it. */ + public byte[] settle(byte[] originalOperation) { + requireGameDesignPeer(); + requireNoAmbientTransaction(); + var operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + if (!Arrays.equals(originalOperation, operation.canonicalBytes()) + || !workloadNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException("Exact original publication operation namespace required"); + } + var gameDesignRequest = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + workloadNamespace, operation.canonicalBytes()); + var gameDesign = gameDesignClient.read(gameDesignRequest); + var terminal = gameDesign == null ? null : gameDesign.terminalEvidence().orElse(null); + if (gameDesign == null || !gameDesignRequest.equals(gameDesign.request()) || terminal == null) { + throw new IllegalStateException("Game Design terminal differs from exact owner read request"); + } + if (!Arrays.equals(operation.canonicalBytes(), terminal.operationBytes())) { + throw new IllegalStateException("Game Design terminal substitutes original operation"); + } + requireNoAmbientTransaction(); + var worldRequest = + WorldPublicationTerminalReadEvidence.Request.create( + workloadNamespace, operation.canonicalBytes(), terminal.canonicalBytes()); + var world = worldClient.read(worldRequest); + var expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + if (world == null + || !worldRequest.equals(world.request()) + || world.worldOutcome() != expectedWorldOutcome + || world.terminalEvidence() == null + || !Arrays.equals(operation.canonicalBytes(), world.terminalEvidence().operationBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.terminalEvidence().canonicalBytes()) + || !Arrays.equals(terminal.canonicalBytes(), world.worldTerminalEvidence())) { + throw new IllegalStateException("World terminal differs from exact independent owner read"); + } + requireNoAmbientTransaction(); + byte[] receipt = + Objects.requireNonNull( + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence()))); + // A second transaction establishes post-commit historical readback; no new issuer or + // credential capture is involved. Neither SQL phase can contain an owner RPC. + requireNoAmbientTransaction(); + byte[] committed = + ownerTransaction.execute( + ignored -> + repository.settle( + operation, + terminal, + world.worldOutcome().name(), + world.worldTerminalEvidence())); + if (!Arrays.equals(receipt, committed)) { + throw new IllegalStateException("Committed Account settlement readback differs from receipt"); + } + return receipt; + } + + private void requireGameDesignPeer() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED + .withDescription("Verified workload identity required") + .asRuntimeException(); + } + if (!("spiffe://firemud/ns/" + workloadNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw Status.PERMISSION_DENIED + .withDescription("Exact same-namespace Game Design workload required") + .asRuntimeException(); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION + .withDescription("Publication settlement requires no ambient transaction") + .asRuntimeException(); + } + } +} diff --git a/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java new file mode 100644 index 0000000000..56eb571a39 --- /dev/null +++ b/services/account-service/src/main/java/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcService.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.accountservice.service.session; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementGrpcCodec.Request; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone unregistered authenticated ingress for exact selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementGrpcService + extends AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceImplBase { + private final AccountSelectedDraftPublicationSettlementService owner; + private final String namespace; + + public AccountSelectedPublicationSettlementGrpcService( + AccountSelectedDraftPublicationSettlementService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-publication settlement owner required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + this.namespace = namespace; + } + + @Override + public void settleSelectedPublication( + SettleSelectedPublicationRequest wire, + StreamObserver observer) { + Objects.requireNonNull(observer, "response observer required"); + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + deny(observer, Status.UNAUTHENTICATED); + return; + } + if (SessionContext.hasAuthenticatedCallerContext() + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + deny(observer, Status.FAILED_PRECONDITION); + return; + } + if (wire == null + || wire.getSerializedSize() + > AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + + final Request request; + try { + request = AccountSelectedPublicationSettlementGrpcCodec.fromRequest(wire); + } catch (RuntimeException malformed) { + deny(observer, Status.INVALID_ARGUMENT); + return; + } + if (!namespace.equals(request.targetNamespace())) { + deny(observer, Status.PERMISSION_DENIED); + return; + } + + try { + byte[] receipt = owner.settle(request.originalOperation()); + observer.onNext(AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt)); + observer.onCompleted(); + } catch (StatusRuntimeException failure) { + Status.Code code = Status.fromThrowable(failure).getCode(); + if (code != Status.Code.UNAUTHENTICATED + && code != Status.Code.PERMISSION_DENIED + && code != Status.Code.INVALID_ARGUMENT + && code != Status.Code.FAILED_PRECONDITION) { + code = Status.Code.UNAVAILABLE; + } + deny(observer, Status.fromCode(code)); + } catch (IllegalArgumentException invalidEvidence) { + deny(observer, Status.FAILED_PRECONDITION); + } catch (RuntimeException unavailable) { + deny(observer, Status.UNAVAILABLE); + } + } + + private static void deny(StreamObserver observer, Status status) { + observer.onError( + status + .withDescription("Account selected-publication settlement denied or unavailable") + .asRuntimeException()); + } +} diff --git a/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql b/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql new file mode 100644 index 0000000000..2168ef26f4 --- /dev/null +++ b/services/account-service/src/main/resources/db/migration/V1011__selected_publication_closure_inventory.sql @@ -0,0 +1,73 @@ +-- Preserve retained Account settlement rows and the original v1 inventory profile. Admit only the explicit closure-qualified v2 +-- profile. Publication-operation bytes and historical migration definitions remain immutable. +-- [jooq ignore start] +DO $migration$ +DECLARE + inventory_function REGPROCEDURE := + '"${serviceSchema}".require_selected_inventory_operation_v2(bytea)'::REGPROCEDURE; + original_definition TEXT; + model_shape_anchor TEXT := $anchor$ (model, ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'])$anchor$; + model_shape_replacement TEXT := $replacement$ (model, CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + THEN ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs','inboundSourceClosure'] + ELSE ARRAY['modelId','graphSchemaVersion','graphDigest','topologyResultDigest','familyCounts','regionGeneratorInputs','generationRuleFields','regionFields','zoneFields','roomFields','roomExitFields','spawnBindingFields','spawnBindingInputs','generationRuleInputCount','spawnBindingCount','appliedEpochs'] + END)$replacement$; + profile_anchor TEXT := $anchor$ OR inventory->>'schema' IS DISTINCT FROM 'world-selected-publication-artifact-inventory/v1' + OR inventory->'schemaVersion' IS DISTINCT FROM '1'::JSONB OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$anchor$; + profile_replacement TEXT := $replacement$ OR (( + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v1' + AND inventory->'schemaVersion' = '1'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + AND model->'graphSchemaVersion' = '2'::JSONB + AND checkpoint->'digestSchemaVersion' = '3'::JSONB + AND selector->'request'->'digestSchemaVersion' = '3'::JSONB + AND NOT (model ? 'inboundSourceClosure') + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 16) + OR + (inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB + AND model->>'modelId' = 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_INBOUND_EMPTY_V1' + AND model->'graphSchemaVersion' = '3'::JSONB + AND checkpoint->'digestSchemaVersion' = '4'::JSONB + AND selector->'request'->'digestSchemaVersion' = '4'::JSONB + AND (SELECT count(*) FROM jsonb_object_keys( + CASE WHEN jsonb_typeof(model) = 'object' THEN model ELSE '{}'::JSONB END)) = 17 + AND model ?& ARRAY['modelId', 'graphSchemaVersion', 'graphDigest', + 'topologyResultDigest', 'familyCounts', 'regionGeneratorInputs', + 'generationRuleFields', 'regionFields', 'zoneFields', 'roomFields', + 'roomExitFields', 'spawnBindingFields', 'spawnBindingInputs', + 'generationRuleInputCount', 'spawnBindingCount', 'appliedEpochs', + 'inboundSourceClosure'] + AND model->'inboundSourceClosure' IS NOT DISTINCT FROM + '{"schemaVersion":1,"familyCounts":[{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE","count":0},{"family":"WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING","count":0}]}'::JSONB) + ) IS NOT TRUE) OR inventory->>'completeness' IS DISTINCT FROM 'COMPLETE'$replacement$; + model_count_anchor TEXT := $anchor$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> 16$anchor$; + model_count_replacement TEXT := $replacement$ OR (SELECT count(*) FROM jsonb_object_keys(model)) <> (CASE + WHEN inventory->>'schema' = 'world-selected-publication-artifact-inventory/v2' + AND inventory->'schemaVersion' = '2'::JSONB THEN 17 ELSE 16 END)$replacement$; + legacy_model_anchor TEXT := $anchor$ OR model->>'modelId' IS DISTINCT FROM 'WORLD_LOGICAL_ROOM_EXIT_ADJACENCY_V1' + OR model->'graphSchemaVersion' IS DISTINCT FROM '2'::JSONB$anchor$; +BEGIN + SELECT pg_get_functiondef(inventory_function) INTO STRICT original_definition; + IF (length(original_definition) - length(replace(original_definition, model_shape_anchor, ''))) + / length(model_shape_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, profile_anchor, ''))) + / length(profile_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, legacy_model_anchor, ''))) + / length(legacy_model_anchor) <> 1 + OR (length(original_definition) - length(replace(original_definition, model_count_anchor, ''))) + / length(model_count_anchor) <> 1 THEN + RAISE EXCEPTION 'Expected exact Account V94 inventory profile and complete model guards'; + END IF; + original_definition := replace(original_definition, model_shape_anchor, model_shape_replacement); + original_definition := replace(original_definition, profile_anchor, profile_replacement); + -- The paired profile guard above checks both model identifiers and graph schemas. Keep the + -- generation-rule and artifact-decision restrictions below unchanged for both profiles. + original_definition := replace(original_definition, legacy_model_anchor, ''); + original_definition := replace(original_definition, model_count_anchor, model_count_replacement); + EXECUTE original_definition; +END; +$migration$; +-- [jooq ignore stop] diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..5984a479e7 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/authordraft/AccountDraftFenceHistoryPostgresIntegrationTest.java @@ -0,0 +1,390 @@ +package integration.net.firedevops.firemud.accountservice.authordraft; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import integration.net.firedevops.firemud.accountservice.repository.AccountPostgresIntegrationFixture; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Ordering; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.Settlement; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository.SourceChange; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Outcome; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.OwnerReadback; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionTemplate; + +/** Retained V75 storage only; source capture and World terminal authority are test stipulations. */ +class AccountDraftFenceHistoryPostgresIntegrationTest { + private static final AccountPostgresIntegrationFixture POSTGRES = + new AccountPostgresIntegrationFixture(); + private static final List TABLES = + List.of( + "account_draft_authorization_source_locks", + "account_draft_authorization_fences", + "account_draft_authorization_sources", + "account_draft_authorization_owner_readbacks", + "account_draft_authorization_source_changes", + "account_draft_authorization_changed_scopes"); + + @BeforeAll + static void startPostgres() { + POSTGRES.start(); + } + + @AfterAll + static void stopPostgres() { + POSTGRES.stop(); + } + + @Test + void retainedV1OrderReadbackAndPendingChangeSurviveRequiredOwnerAndCurrentMigrations() { + String schema = "account_fence_history_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource source = POSTGRES.dataSource(schema); + migrate(source, schema, "75"); + DSLContext dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + TransactionTemplate transaction = + new TransactionTemplate(new DataSourceTransactionManager(source)); + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + + // V75 predates restriction birth. Let PostgreSQL generate the UUID and its real provenance; + // current AccountRepository insertion must not be used to invent a historical birth receipt. + UUID account = insertHistoricalAccount(dsl); + DraftAuthorizationFenceBinding binding = binding(account); + SourceEvidence legacyKey = binding.sources().get(1); + assertThat(legacyKey.key().getBytes(StandardCharsets.UTF_8)).hasSize(512); + var world = + new OwnerReadback( + Owner.WORLD, + Outcome.COMMITTED, + binding.operationId(), + binding.commitId(), + binding.fenceId(), + binding.inputDigest(), + binding.canonicalBytes(), + new byte[] {8}); + var change = new SourceChange(UUID.randomUUID(), binding.sources(), new byte[] {12}); + seedHistoricalState(dsl, transaction, binding, world, change); + + // Freeze the original columns so later additions cannot disguise a rewrite of retained data. + Map queries = originalRowQueries(dsl); + Map> rows = rows(dsl, queries); + assertThat(rows.values()).allSatisfy(tableRows -> assertThat(tableRows).isNotEmpty()); + int rank75 = historyRank(dsl); + List history75 = history(dsl, rank75); + migrate(source, schema, "76"); + assertThat(rows(dsl, queries)).isEqualTo(rows); + assertThat(history(dsl, rank75)).isEqualTo(history75); + assertRetained(dsl, transaction, binding, world, change, legacyKey); + assertThat(rows(dsl, queries)).isEqualTo(rows); + + int rank76 = historyRank(dsl); + List history76 = history(dsl, rank76); + Flyway current = migrate(source, schema, null); + assertThat(current.info().pending()).isEmpty(); + assertThat(historyRank(dsl)).isGreaterThan(rank76); + assertThat(history(dsl, rank76)).isEqualTo(history76); + Map> currentRows = rows(dsl, queries); + rows.forEach( + (table, originalRows) -> { + if (table.equals("account_draft_authorization_source_locks")) { + // V87 adds a serialization lock from the real Account scope, never authority evidence. + assertThat(currentRows.get(table)) + .containsAll(originalRows) + .hasSize(originalRows.size() + 1); + } else { + assertThat(currentRows.get(table)).isEqualTo(originalRows); + } + }); + assertThat( + dsl.fetch("SELECT source_key FROM account_draft_authorization_source_locks") + .getValues(0, String.class)) + .containsExactlyInAnyOrder( + binding.sources().get(0).key(), legacyKey.key(), "GLOBAL_ROLES:" + account); + assertRetained(dsl, transaction, binding, world, change, legacyKey); + transaction.executeWithoutResult( + ignored -> + assertThat(new DraftAuthorizationFenceRepository(dsl).sourceMutationPermitted(change)) + .isFalse()); + assertThat(rows(dsl, queries)).isEqualTo(currentRows); + assertHistoricalProvenance(dsl, account); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE account_draft_authorization_fences SET binding = ? WHERE operation_id = ?", + new byte[] {99}, + binding.operationId())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "DELETE FROM account_draft_authorization_owner_readbacks WHERE operation_id = ?", + binding.operationId())) + .isInstanceOf(DataAccessException.class); + assertThat(rows(dsl, queries)).isEqualTo(currentRows); + } + + private static void assertRetained( + DSLContext dsl, + TransactionTemplate transaction, + DraftAuthorizationFenceBinding binding, + OwnerReadback world, + SourceChange change, + SourceEvidence legacyKey) { + var repository = new DraftAuthorizationFenceRepository(dsl); + transaction.executeWithoutResult( + ignored -> { + assertThat( + repository + .readOriginalBinding(binding.operationId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + assertThat(repository.reserve(binding).binding()) + .containsExactly(binding.canonicalBytes()); + assertThat(repository.read(binding).ordering()).isEqualTo(Ordering.COMMIT_ORDER); + assertThat(repository.readOwnerResult(binding, Owner.WORLD).orElseThrow().readback()) + .containsExactly(world.canonicalBytes()); + assertThat(repository.readOwnerResult(binding, Owner.GAME_DESIGN)).isEmpty(); + assertThat(repository.readSettlement(binding)).isEqualTo(Settlement.PENDING); + assertThat(repository.readSourceChange(change).status()).isEqualTo("WAITING"); + }); + assertThat( + Objects.requireNonNull( + dsl.fetchOne( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ?", + legacyKey.key())) + .get(0, String.class)) + .isEqualTo(legacyKey.key()); + } + + private static void seedHistoricalState( + DSLContext dsl, + TransactionTemplate transaction, + DraftAuthorizationFenceBinding binding, + OwnerReadback world, + SourceChange change) { + // Preserve V75's actual guarded insert/order lifecycle. Current source-change APIs also + // inspect later publication owners, which do not exist in this predecessor schema. + transaction.executeWithoutResult( + ignored -> { + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_source_locks (source_key) VALUES (?) ON CONFLICT DO NOTHING", + evidence.key()); + } + dsl.execute( + "INSERT INTO account_draft_authorization_fences (operation_id, request_id, commit_id, fence_id, binding, ordering) VALUES (?, ?, ?, ?, ?, 'RESERVED')", + binding.operationId(), + binding.requestId(), + binding.commitId(), + binding.fenceId(), + binding.canonicalBytes()); + for (SourceEvidence evidence : binding.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_sources (operation_id, source_key, source_evidence) VALUES (?, ?, ?)", + binding.operationId(), + evidence.key(), + evidence.canonicalBytes()); + } + dsl.execute( + "UPDATE account_draft_authorization_fences SET ordering = 'COMMIT_ORDER', ordered_at = CURRENT_TIMESTAMP WHERE operation_id = ?", + binding.operationId()); + dsl.execute( + "INSERT INTO account_draft_authorization_owner_readbacks (operation_id, owner, outcome, readback) VALUES (?, 'WORLD', 'COMMITTED', ?)", + binding.operationId(), + world.canonicalBytes()); + dsl.execute( + "INSERT INTO account_draft_authorization_source_changes (change_id, binding, status) VALUES (?, ?, 'WAITING')", + change.changeId(), + change.canonicalBytes()); + for (SourceEvidence evidence : change.sources()) { + dsl.execute( + "INSERT INTO account_draft_authorization_changed_scopes (change_id, source_key) VALUES (?, ?)", + change.changeId(), + evidence.key()); + } + }); + } + + private static UUID insertHistoricalAccount(DSLContext dsl) { + UUID suffix = UUID.randomUUID(); + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "INSERT INTO accounts (username, email, password_hash, role, email_verified, " + + "login_auth_modes, lifecycle_state) VALUES (?, ?, 'historical-test-verifier', " + + "'player', FALSE, 'PASSWORD,EMAIL_OTP', 'active') RETURNING account_uuid", + "fence-history-" + suffix, + suffix + "@example.test")); + UUID account = Objects.requireNonNull(row.get(0, UUID.class)); + assertThat(account.version()).isEqualTo(4); + assertHistoricalProvenance(dsl, account); + return account; + } + + private static void assertHistoricalProvenance(DSLContext dsl, UUID account) { + Record row = + Objects.requireNonNull( + dsl.fetchOne( + "SELECT id, account_uuid_provenance, account_uuid_source_numeric_id, " + + "account_repository_insert_transaction_id FROM accounts WHERE account_uuid = ?", + account)); + assertThat(row.get("id", Long.class)).isPositive(); + assertThat(row.get("account_uuid_provenance", String.class)) + .isEqualTo("ACCOUNT_DATABASE_INSERT"); + assertThat(row.get("account_uuid_source_numeric_id", Long.class)) + .isEqualTo(row.get("id", Long.class)); + assertThat(row.get("account_repository_insert_transaction_id", Long.class)).isNull(); + } + + private static DraftAuthorizationFenceBinding binding(UUID account) { + var complete = + DraftCommitBinding.create( + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1, + "tenant-key", + 2, + "tenant-key", + "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "historical/base:9007199254740993", + List.of( + new RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "historical-world-payload")), + List.of( + new AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "region", + "region-1", + "aggregate", + "region-1", + "9007199254740999"))); + return new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + complete.requestId(), + complete.commitId(), + UUID.randomUUID(), + account, + complete.target().canonicalTenantId(), + complete.target().canonicalVersionId(), + complete.baseCommitId(), + "2", + complete.canonicalBytes(), + complete.canonicalBytes(), + complete.digest(), + List.of( + new SourceEvidence( + SourceKind.ACCOUNT, + account.toString(), + "3", + "5", + "stream/" + account, + "2", + new byte[] {7}), + new SourceEvidence( + SourceKind.ISSUER, + "x".repeat(505), + "3", + "5", + "stream/legacy512", + "2", + new byte[] {9}))); + } + + private static Map originalRowQueries(DSLContext dsl) { + Map queries = new LinkedHashMap<>(); + for (String table : TABLES) { + List columns = + dsl.fetch( + "SELECT column_name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ? ORDER BY ordinal_position", + table) + .getValues(0, String.class); + assertThat(columns).isNotEmpty(); + String projection = + String.join(",", columns.stream().map(name -> "\"" + name + "\"").toList()); + queries.put( + table, + "SELECT to_jsonb(original)::text FROM (SELECT " + + projection + + ",xmin::text AS row_xmin FROM " + + table + + ") original ORDER BY to_jsonb(original)::text"); + } + return queries; + } + + private static Map> rows(DSLContext dsl, Map queries) { + Map> rows = new LinkedHashMap<>(); + queries.forEach((table, query) -> rows.put(table, dsl.fetch(query).getValues(0, String.class))); + return rows; + } + + private static int historyRank(DSLContext dsl) { + return Objects.requireNonNull( + dsl.fetchOne("SELECT max(installed_rank) FROM flyway_schema_history")) + .get(0, Integer.class); + } + + private static List history(DSLContext dsl, int rank) { + return dsl.fetch( + "SELECT to_jsonb(h)::text FROM flyway_schema_history h WHERE installed_rank <= ? ORDER BY installed_rank", + rank) + .getValues(0, String.class); + } + + private static Flyway migrate(DriverManagerDataSource source, String schema, String target) { + Path root = Path.of("").toAbsolutePath(); + while (root != null && !Files.isRegularFile(root.resolve("gradlew"))) root = root.getParent(); + root = Objects.requireNonNull(root, "Repository filesystem migrations required"); + var configuration = + Flyway.configure() + .dataSource(source) + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .locations( + "filesystem:" + + root.resolve("services/account-service/src/main/resources/db/migration"), + "filesystem:" + + root.resolve("services/common-saga/src/main/resources/db/migration/saga")); + if (target != null) configuration.target(target); + Flyway flyway = configuration.load(); + flyway.migrate(); + return flyway; + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java index 627d60ce9d..012428b62e 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountSourceCurrentnessForwardMigrationsPostgresIntegrationTest.java @@ -915,7 +915,7 @@ private static void exerciseSelectedPublicationV2Settlement( "publishWorkflowId", jsonString(workflowId.toString()), "appliedCommitId", jsonString(selectedCommit.commitId().toString()), "contentDigest", jsonString(contentDigest), - "digestSchemaVersion", "1", + "digestSchemaVersion", "3", "worldAffectedTuples", expectedTuples); String selectorJson = jsonObject( @@ -1021,7 +1021,7 @@ private static void exerciseSelectedPublicationV2Settlement( jsonObject( "appliedCommitId", jsonString(selectedCommit.commitId().toString()), "contentDigest", jsonString(contentDigest), - "digestSchemaVersion", "1"), + "digestSchemaVersion", "3"), "sourceModel", modelJson, "artifactDecisions", "[{\"artifactKind\":\"NAVMESH\",\"state\":\"NOT_REQUIRED\"," diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java index 9cb3db2f17..b73c907fc6 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionActivationProtectionPostgresIntegrationTest.java @@ -2,6 +2,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; @@ -17,17 +21,23 @@ import java.util.Locale; import java.util.Map; import java.util.UUID; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository; +import net.firedevops.firemud.accountservice.repository.AccountStartSessionActivationProtectionRepository.StoredProtection; +import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceKind; import net.firedevops.firemud.common.json.Rfc8785CanonicalJson; import net.firedevops.firemud.common.testing.AuthoringFixtures; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; +import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import net.firedevops.firemud.test.TestContainerImages; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; +import org.jooq.ExecuteListener; import org.jooq.Field; import org.jooq.SQLDialect; import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListenerProvider; import org.junit.jupiter.api.Test; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -54,6 +64,134 @@ class AccountStartSessionActivationProtectionPostgresIntegrationTest { private static final JsonMapper JSON = JsonMapper.builder().build(); + @Test + void settlementLocksCanonicalSourceKeysBeforeProtectionRowAccess() throws Exception { + Fixture fixture = fixture(); + var first = + new SourceEvidence( + SourceKind.HOSTED_TERMS, + "activation-\uD800\uDC00", + null, + "1", + null, + null, + bytes("first")); + var last = + new SourceEvidence( + SourceKind.HOSTED_TERMS, "activation-\uE000", null, "1", null, null, bytes("last")); + for (var source : List.of(first, last)) { + fixture + .dsl() + .execute( + "INSERT INTO account_draft_authorization_source_locks(source_key) VALUES (?)", + source.key()); + } + UUID protectionId = UUID.randomUUID(); + var evidence = mock(AccountStartSessionActivationProtectionEvidence.class); + when(evidence.accountProtectionId()).thenReturn(protectionId); + when(evidence.accountProtectionFence()).thenReturn(7L); + when(evidence.canonicalBytes()).thenReturn(bytes("controlled protection lookup")); + when(evidence.sourceEvidenceVector()).thenReturn(List.of(last, first)); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + when(terminal.accountProtectionEvidence()).thenReturn(evidence); + var repository = spy(new AccountStartSessionActivationProtectionRepository(fixture.dsl())); + // Only the lock boundary is physical here; historical lookup and terminal authority are + // controlled. + doReturn(java.util.Optional.of(new StoredProtection(evidence, 1L))) + .when(repository) + .findHistoricalExact(protectionId, 7L); + var sourceLocks = new java.util.ArrayList(); + var protectionLocks = new java.util.ArrayList(); + fixture + .dsl() + .configuration() + .setAppending( + new DefaultExecuteListenerProvider( + ExecuteListener.onExecuteStart( + context -> { + String sql = context.sql(); + var query = context.query(); + if (sql == null || query == null || !sql.contains("FOR UPDATE NOWAIT")) + return; + if (sql.contains("account_draft_authorization_source_locks")) { + sourceLocks.add((String) query.getBindValues().getFirst()); + } else if (sql.contains("account_start_session_activation_protections")) { + protectionLocks.add(query.getBindValues().getFirst()); + } + }))); + for (var contended : List.of(first, last)) { + sourceLocks.clear(); + protectionLocks.clear(); + try (var holder = fixture.dataSource().getConnection()) { + holder.setAutoCommit(false); + try (var statement = + holder.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE")) { + statement.setString(1, contended.key()); + try (var rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + } + } + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult(ignored -> repository.settleExact(terminal))) + .hasRootCauseInstanceOf(org.postgresql.util.PSQLException.class) + .satisfies( + failure -> { + Throwable root = failure; + while (root.getCause() != null) root = root.getCause(); + assertThat(((org.postgresql.util.PSQLException) root).getSQLState()) + .isEqualTo("55P03"); + }); + assertThat(protectionLocks).isEmpty(); + assertThat(sourceLocks) + .containsExactlyElementsOf( + contended == first ? List.of(first.key()) : List.of(first.key(), last.key())); + assertThat( + fixture + .dsl() + .fetchCount( + DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + holder.rollback(); + } + } + sourceLocks.clear(); + protectionLocks.clear(); + // Once both sources are available, row lookup follows them; no parent is manufactured by this + // test. + assertThatThrownBy( + () -> + fixture + .transaction() + .executeWithoutResult(ignored -> repository.settleExact(terminal))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Exact original StartSession activation protection unavailable"); + assertThat(sourceLocks).containsExactly(first.key(), last.key()); + assertThat(protectionLocks).containsExactly(protectionId); + assertThat( + fixture + .dsl() + .fetchCount(DSL.table("account_start_session_activation_protection_settlements"))) + .isZero(); + try (var verifier = fixture.dataSource().getConnection()) { + verifier.setAutoCommit(false); + try (var statement = + verifier.prepareStatement( + "SELECT source_key FROM account_draft_authorization_source_locks WHERE source_key = ? FOR UPDATE NOWAIT")) { + for (var source : List.of(first, last)) { + statement.setString(1, source.key()); + try (var rows = statement.executeQuery()) { + assertThat(rows.next()).isTrue(); + } + } + } + verifier.rollback(); + } + } + @Test void digestAlignmentUpgradePreservesRetainedParentAndRequiresCanonicalWorldPrefix() throws Exception { @@ -1342,6 +1480,59 @@ void currentnessRequiresCommittedPreparationExactAttemptAndUnexpiredLease() thro expiredFixture, expired.requestBytes(), expired.operationIdentityBytes()); } + @Test + void fullTupleDoesNotBypassIndependentActivationIssuanceOperationBinding() throws Exception { + Fixture fixture = fixture(); + CurrentnessCase current = currentnessCase(fixture, Instant.now().plusSeconds(60)); + Map request = readJson(current.requestBytes()); + byte[] tuple = + Base64.getDecoder() + .decode((String) request.get("originalPostAuthorizationTupleBytesBase64")); + byte[] projection = + Base64.getDecoder().decode((String) request.get("accountRedemptionProjectionBytesBase64")); + assertThat(projection).containsExactly(tuple); + String requestId = (String) readJson(tuple).get("controlPlaneRequestId"); + + fixture + .transaction() + .executeWithoutResult( + status -> + fixture + .dsl() + .execute( + "SELECT account_ss_activation_assert_current(?, ?, ?, FALSE)", + current.requestBytes(), + current.operationIdentityBytes(), + current.operationIdentityDigest())); + // Stipulate one contradictory retained owner row to isolate the independent SQL conjunct. + // Current activation/acquisition guards stay enabled; this is not authenticated producer proof. + fixture + .transaction() + .executeWithoutResult( + status -> { + fixture.dsl().execute("SET LOCAL session_replication_role = replica"); + assertThat( + fixture + .dsl() + .execute( + "UPDATE account_start_session_operator_authorizations SET issuance_operation_id = ? " + + "WHERE control_plane_request_id = ?", + UUID.randomUUID(), + requestId)) + .isEqualTo(1); + fixture.dsl().execute("SET LOCAL session_replication_role = origin"); + }); + assertThatThrownBy(() -> acquireProtection(fixture, current)) + .hasMessageContaining( + "Activation protection differs from original Account redemption or capture"); + for (String table : + List.of( + "account_start_session_activation_protections", + "account_start_session_activation_protection_sources")) { + assertThat(fixture.dsl().fetchCount(DSL.table(table))).as(table).isZero(); + } + } + @Test void abortedSettlementPreservesTerminalCodeFenceWithoutRequiringActiveLifecycle() throws Exception { diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java index d8ed35617a..6925708488 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/repository/AccountStartSessionWorldParticipationPostgresIntegrationTest.java @@ -150,8 +150,10 @@ void originalTupleRecoversCommittedParticipationAfterLostResponseAndLeaseExpiry( "tuple-recovery-world", GAME_TEMPLATE_ID); String preparationDigest = digest(preparationInput); + // Bounded synthetic headroom lets initial retention reach its currentness gate; later reads + // use this same expiry. Instant leaseExpiresAt = - Instant.ofEpochMilli(databaseNow(proof.sourceDsl()).toEpochMilli()).plusSeconds(4L); + Instant.ofEpochMilli(databaseNow(proof.sourceDsl()).toEpochMilli()).plusSeconds(10L); // The Game Session point-in-time observation is stipulated; Account's original issue, // redemption, source capture, acquisition gates, and PostgreSQL retention are real. var acquisition = @@ -496,7 +498,7 @@ private static Instant databaseNow(DSLContext dsl) { } private static void awaitDatabaseExpiry(DSLContext dsl, Instant expiresAt) throws Exception { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(10L); + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(15L); while (!databaseNow(dsl).isAfter(expiresAt)) { if (System.nanoTime() >= deadline) { throw new IllegalStateException("PostgreSQL clock did not pass the retained lease expiry"); diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java index 56dca09c66..2736f558c8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountControlUiPositiveOwnerPostgresIntegrationTest.java @@ -2,8 +2,6 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; import com.google.protobuf.ByteString; import io.grpc.Context; @@ -19,15 +17,18 @@ import io.grpc.StatusRuntimeException; import io.grpc.inprocess.InProcessChannelBuilder; import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.lettuce.core.ClientOptions; import io.lettuce.core.RedisClient; import io.lettuce.core.RedisURI; import io.lettuce.core.codec.ByteArrayCodec; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.cert.CertificateEncodingException; -import java.security.cert.X509Certificate; import java.time.Clock; import java.time.Instant; import java.util.ArrayList; @@ -49,14 +50,15 @@ import net.firedevops.firemud.accountservice.repository.AccountStartSessionOperatorAuthorizationRepository; import net.firedevops.firemud.accountservice.service.impl.StartSessionOperatorAuthorizationGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountOperatorAuthorizationFingerprintKeyring.OwnerKeySource; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; 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.GrpcPeerCertificateEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; import net.firedevops.firemud.common.redis.contracts.RedisScriptCatalog; @@ -110,7 +112,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @Container static final PostgreSQLContainer postgres = - AccountControlUiOwnerWorkflowPostgresIntegrationTest.postgres; + new PostgreSQLContainer<>(TestContainerImages.postgres()); @Container static final GenericContainer redis = @@ -150,7 +152,7 @@ class AccountControlUiPositiveOwnerPostgresIntegrationTest { @TempDir Path temporary; - private InProcessLoggingTransport loggingTransport; + private MtlsLoggingTransport loggingTransport; @AfterEach void clearLoggingTransport() throws Exception { @@ -414,21 +416,25 @@ void realSignerLifecycleIssuesAuthenticatesAndClaimsExactOriginalAccountOrder() var reservationFixture = StartSessionReservationMutationTestFixtures.forRunOwnedPostgres(postgres, loggingSchema); var reservationService = reservationFixture.service(); - var approvedAccountLeaf = testAccountLeafEvidence(); + var loggingPki = + AccountStartSessionReservationProofPki.create( + temporary.resolve("logging-claim-pki"), "control-ui-owner-proof"); + String approvedAccountLeaf = + java.util.HexFormat.of() + .formatHex( + java.security.MessageDigest.getInstance("SHA-256") + .digest(loggingPki.accountIdentity().certificate().getEncoded())); Path approvedLeafFile = temporary.resolve("account-reservation-evidence-approved-test-leaf.txt"); Files.writeString( - approvedLeafFile, - "active=" + approvedAccountLeaf.leafSha256() + "\n", - StandardCharsets.US_ASCII); + approvedLeafFile, "active=" + approvedAccountLeaf + "\n", StandardCharsets.US_ASCII); loggingTransport = - inProcessLoggingTransport( + mtlsLoggingTransport( new StartSessionReservationEvidenceGrpcService( reservationService, new StartSessionReservationEvidenceLeafApproval(approvedLeafFile.toString()), "control-ui-owner-proof"), - "spiffe://firemud/ns/control-ui-owner-proof/sa/account-service", - approvedAccountLeaf); + loggingPki); var acquisition = reservationService.acquire(loggingTuple); assertThat(acquisition.newlyAcquired()).isTrue(); @@ -862,69 +868,43 @@ private static Path loggingMigrations() { } /** - * Test-only in-process composition supplies the Account URI and a run-owned approved leaf; it - * exercises receiver authorization, not a TLS handshake or mTLS certificate binding. + * Controlled Logging socket uses certificate-derived Account identity and actual approved leaf. */ - private static InProcessLoggingTransport inProcessLoggingTransport( + private static MtlsLoggingTransport mtlsLoggingTransport( StartSessionReservationEvidenceGrpcService receiver, - String accountPeerUri, - GrpcPeerCertificateEvidence accountLeafEvidence) + AccountStartSessionReservationProofPki pki) throws Exception { - String serverName = InProcessServerBuilder.generateName(); - var peer = GrpcPeerIdentity.parseUri(accountPeerUri).orElseThrow(); + var identity = pki.server("logging"); Server server = - InProcessServerBuilder.forName(serverName) - .directExecutor() - .addService( - ServerInterceptors.intercept( - receiver, - new ServerInterceptor() { - @Override - public ServerCall.Listener interceptCall( - ServerCall call, - Metadata headers, - ServerCallHandler next) { - Context peerContext = - Context.current() - .withValue(GrpcPeerIdentity.CONTEXT_KEY, peer) - .withValue( - GrpcPeerCertificateEvidence.CONTEXT_KEY, accountLeafEvidence); - return Contexts.interceptCall(peerContext, call, headers, next); - } - })) + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(receiver, new GrpcPeerIdentityInterceptor())) .build() .start(); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + server.getPort()); + var tls = pki.clientProperties(); + var factory = new GrpcChannelFactory(); ManagedChannel receiverChannel = - InProcessChannelBuilder.forName(serverName).directExecutor().build(); - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - endpoints.setLoggingAdminService(serverName); - CommonGrpcClientProperties testTransport = new CommonGrpcClientProperties(); - testTransport.setPlaintext(true); - GrpcChannelFactory channelFactory = - new GrpcChannelFactory() { - @Override - public ManagedChannel buildChannel( - String target, - int defaultPort, - CommonGrpcClientProperties properties, - boolean keepAlive) { - if (!serverName.equals(target) || !properties.isPlaintext()) { - throw new IllegalArgumentException( - "Only the named in-process test transport is valid"); - } - return InProcessChannelBuilder.forName(serverName).directExecutor().build(); - } - }; - StartSessionReservationEvidenceClient accountClient = + factory.buildChannel(endpoints.getLoggingAdminService(), 6565, tls, true); + var accountClient = new StartSessionReservationEvidenceClient( - endpoints, testTransport, channelFactory, BlockingGrpcStubCustomizer.noop()); + endpoints, tls, factory, "control-ui-owner-proof"); try { ReflectionTestUtils.invokeMethod(accountClient, "init"); - return new InProcessLoggingTransport( + String loggingUri = "spiffe://firemud/ns/control-ui-owner-proof/sa/logging-admin-service"; + return new MtlsLoggingTransport( server, receiverChannel, accountClient, - StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel)); + StartSessionReservationEvidenceServiceGrpc.newBlockingStub(receiverChannel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(loggingUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(loggingUri))); } catch (RuntimeException | Error failure) { accountClient.close(); receiverChannel.shutdownNow(); @@ -933,18 +913,6 @@ public ManagedChannel buildChannel( } } - private static GrpcPeerCertificateEvidence testAccountLeafEvidence() { - X509Certificate leaf = mock(X509Certificate.class); - try { - when(leaf.getEncoded()) - .thenReturn( - "run-owned Account test leaf certificate".getBytes(StandardCharsets.US_ASCII)); - } catch (CertificateEncodingException exception) { - throw new AssertionError(exception); - } - return GrpcPeerCertificateEvidence.fromCertificate(leaf).orElseThrow(); - } - private static InProcessAccountTransport inProcessAccountTransport( StartSessionOperatorAuthorizationGrpcService receiver, String namespace) throws Exception { return new InProcessAccountTransport( @@ -1060,10 +1028,10 @@ public void close() { } /** - * Test-only in-process composition. Its injected peer context exercises receiver authorization; - * it is deliberately not a TLS or mTLS proof. + * Controlled Logging socket composition with actual workload certificates and leaf approval. + * Account's separate inbound owner transport remains explicitly controlled. */ - private static final class InProcessLoggingTransport implements AutoCloseable { + private static final class MtlsLoggingTransport implements AutoCloseable { private final Server server; private final ManagedChannel receiverChannel; private final StartSessionReservationEvidenceClient accountClient; @@ -1071,7 +1039,7 @@ private static final class InProcessLoggingTransport implements AutoCloseable { .StartSessionReservationEvidenceServiceBlockingStub receiverStub; - private InProcessLoggingTransport( + private MtlsLoggingTransport( Server server, ManagedChannel receiverChannel, StartSessionReservationEvidenceClient accountClient, diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java index b5baf98e77..e40b6882e8 100644 --- a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.java +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountOriginalDraftOrderPostgresIntegrationTest.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 io.grpc.Context; import java.nio.file.Path; @@ -12,15 +13,23 @@ import java.time.ZoneOffset; import java.util.List; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderGrpcCodec; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.ExecuteContext; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; 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.CsvSource; +import org.junit.jupiter.params.provider.ValueSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.PostgreSQLContainer; @@ -78,6 +87,364 @@ class AccountOriginalDraftOrderPostgresIntegrationTest { @TempDir Path temporary; + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorExpiryAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLock( + signedCredential, proofDirectory, Duration.ofMinutes(10)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorNotBeforeAtFinalOwnerLockDeniesCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLock( + signedCredential, proofDirectory, Duration.ofMinutes(-10)); + } + + @ParameterizedTest + @ValueSource(booleans = {true, false}) + void originalCreatorIssuedAtEqualityAtFinalOwnerLockAllowsCurrentCallback( + boolean signedCredential, @TempDir Path proofDirectory) throws Exception { + assertOriginalCreatorTimeAtFinalOwnerLock(signedCredential, proofDirectory, Duration.ZERO); + } + + private void assertOriginalCreatorTimeAtFinalOwnerLock( + boolean signedCredential, Path proofDirectory, Duration clockChange) throws Exception { + var clock = new ActorClock(); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + proofDirectory, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + String tokenHash = + AccountControlUiCoordination.digest( + "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + var jti = + f.tx( + () -> + f.dsl + .fetchSingle( + "SELECT token_jti FROM account_control_ui_issuance_operations " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash) + .get("token_jti", UUID.class)); + long issuedAt = + java.util.Objects.requireNonNull( + f.tx( + () -> + f.dsl + .fetchSingle( + "SELECT issued_at_epoch_second FROM account_control_ui_issuance_operations " + + "WHERE token_jti=?", + jti) + .get("issued_at_epoch_second", Long.class))); + var before = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti)); + var callback = new AtomicBoolean(); + var clockChanged = new AtomicBoolean(); + var originalListeners = f.dsl.configuration().executeListenerProviders(); + var timeChangeAtOwnerLock = + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql != null + && sql.contains("account_control_ui_issuance_operations") + && sql.contains("FOR UPDATE") + && clockChanged.compareAndSet(false, true)) { + // The real locking read has completed; simulate elapsed time at this precise + // boundary. + // This is deterministic temporal-boundary proof, not physical lock-contention + // proof. + if (clockChange.isZero()) { + clock.freezeAt(Instant.ofEpochSecond(issuedAt)); + } else { + clock.advance(clockChange); + } + } + } + }); + var listeners = java.util.Arrays.copyOf(originalListeners, originalListeners.length + 1); + listeners[originalListeners.length] = timeChangeAtOwnerLock; + f.dsl.configuration().set(listeners); + try { + Throwable failure = + catchThrowable( + () -> { + if (signedCredential) { + issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } else { + issued + .actors() + .withCurrentCommitted( + f.account.getAccountUuid(), + f.tenant, + jti, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } + }); + assertThat(clockChanged).isTrue(); + assertThat(clock.instant().isBefore(Instant.ofEpochSecond(issuedAt))) + .isEqualTo(clockChange.isNegative()); + assertThat(callback.get()).isEqualTo(clockChange.isZero()); + if (clockChange.isZero()) { + assertThat(clock.instant()).isEqualTo(Instant.ofEpochSecond(issuedAt)); + assertThat(failure).isNull(); + } else { + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); + } + assertThat( + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_jti=?", + jti))) + .isEqualTo(before); + } finally { + f.dsl.configuration().set(originalListeners); + } + } + } + + @ParameterizedTest + @CsvSource({ + "true, ABSENT", "false, ABSENT", "true, REPLACED", "false, REPLACED", + "true, RETAINED", "false, RETAINED", "true, UNTRUSTED", "false, UNTRUSTED", + "true, SOURCE_FAILURE", "false, SOURCE_FAILURE", "true, SQL", "false, SQL", + "true, SYNCHRONIZATION", "false, SYNCHRONIZATION" + }) + void originalCreatorRequiresExactKeyInCurrentProtectedSnapshot( + boolean signedCredential, String keyState, @TempDir Path proofDirectory) throws Exception { + var clock = new ActorClock(); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + proofDirectory, + UUID.randomUUID(), + clock)) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + clock.freezeAt(clock.instant()); + var originalSnapshot = fixture.publicSource.load(); + var pin = fixture.publicSource.sourceIdentity(); + String tokenHash = + AccountControlUiCoordination.digest( + "SHA-256", issued.compact().getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + var original = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT token_jti, signer_receipt, row_to_json(a)::TEXT AS payload, " + + "a.xmin::TEXT AS row_version FROM account_control_ui_issuance_operations a " + + "WHERE token_hash=? AND status='COMMITTED'", + tokenHash)); + UUID jti = original.get("token_jti", UUID.class); + var receipt = + AccountControlUiIssuanceRepository.object(original.get("signer_receipt", byte[].class)); + String originalKid = (String) receipt.get("kid"); + assertThat( + AccountJwtJwksTrustedSource.publicKeyFingerprint(originalSnapshot, pin, originalKid)) + .contains((String) receipt.get("publicKeyFingerprint")); + byte[] changed = originalSnapshot.jwksBytes(); + if (java.util.Set.of("ABSENT", "REPLACED", "RETAINED").contains(keyState)) { + var generator = java.security.KeyPairGenerator.getInstance("RSA"); + generator.initialize(3072); + var replacement = + AccountControlUiSignerFixture.publicJwk( + "REPLACED".equals(keyState) ? originalKid : "other-accepted-key", + (java.security.interfaces.RSAPublicKey) generator.generateKeyPair().getPublic()); + var keys = new java.util.ArrayList(); + keys.add( + AccountControlUiIssuanceRepository.object( + replacement.json().getBytes(java.nio.charset.StandardCharsets.UTF_8))); + if ("RETAINED".equals(keyState)) { + // Controlled retiring-key membership: another current key precedes the accepted original. + // This is not a real signer-rotation or publication proof. + var originalKeys = + (List) + AccountControlUiIssuanceRepository.object(originalSnapshot.jwksBytes()) + .get("keys"); + keys.addAll(originalKeys); + } + changed = AccountControlUiAuthority.canonical(java.util.Map.of("keys", keys)); + } + var observedPin = + "UNTRUSTED".equals(keyState) + ? new net.firedevops.firemud.common.security.AccountPublicJwksCache.SourceIdentity( + pin.environmentId(), + pin.clusterId(), + pin.clusterIncarnationUid(), + pin.namespace(), + pin.namespaceUid(), + UUID.randomUUID().toString(), + pin.bindingRevision(), + pin.apiServerOrigin(), + pin.servingCaSha256()) + : pin; + var controlledCurrent = + new net.firedevops.firemud.common.security.AccountPublicJwksCache.PublicJwksSnapshot( + observedPin, changed); + var protectedFailures = new java.util.concurrent.atomic.AtomicInteger(); + if ("SOURCE_FAILURE".equals(keyState)) { + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + protectedFailures.incrementAndGet(); + throw new IllegalStateException("controlled protected-source transport failure"); + }) + .when(fixture.signerFixture.client) + .observe(); + } + var reads = new java.util.concurrent.atomic.AtomicInteger(); + // Current snapshot membership is an explicit upstream stipulation here; this does not prove + // a production key withdrawal or publication. Original issuance, SQL and Redis remain real. + org.mockito.Mockito.doAnswer( + invocation -> { + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isActualTransactionActive()) + .isFalse(); + assertThat( + org.springframework.transaction.support.TransactionSynchronizationManager + .isSynchronizationActive()) + .isFalse(); + reads.incrementAndGet(); + if ("SOURCE_FAILURE".equals(keyState) + || "SQL".equals(keyState) + || "SYNCHRONIZATION".equals(keyState)) { + return invocation.callRealMethod(); + } + return controlledCurrent; + }) + .when(fixture.publicSource) + .load(); + var callback = new AtomicBoolean(); + java.util.function.Supplier action = + () -> { + if (signedCredential) { + return issued + .actors() + .withCurrent( + issued.compact(), + f.tenant, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + } + return issued + .actors() + .withCurrentCommitted( + f.account.getAccountUuid(), + f.tenant, + jti, + issued.environment(), + current -> { + callback.set(true); + return "callback invoked"; + }); + }; + Throwable failure = + catchThrowable( + () -> { + if ("SQL".equals(keyState)) { + f.tx(action::get); + } else if ("SYNCHRONIZATION".equals(keyState)) { + org.springframework.transaction.support.TransactionSynchronizationManager + .initSynchronization(); + try { + action.get(); + } finally { + org.springframework.transaction.support.TransactionSynchronizationManager + .clearSynchronization(); + } + } else { + action.get(); + } + }); + var after = + f.tx( + () -> + f.dsl.fetchSingle( + "SELECT row_to_json(a)::TEXT AS payload, a.xmin::TEXT AS row_version " + + "FROM account_control_ui_issuance_operations a WHERE token_hash=?", + tokenHash)); + assertThat(after.get("payload", String.class)) + .isEqualTo(original.get("payload", String.class)); + assertThat(after.get("row_version", String.class)) + .isEqualTo(original.get("row_version", String.class)); + assertThat(callback.get()).isEqualTo("RETAINED".equals(keyState)); + if ("RETAINED".equals(keyState)) { + assertThat(failure).isNull(); + } else if (List.of("ABSENT", "REPLACED").contains(keyState)) { + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Exact current authenticated initial creator required"); + } else if ("SOURCE_FAILURE".equals(keyState) || "UNTRUSTED".equals(keyState)) { + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Account trusted public JWKS source was rejected"); + } else if ("SQL".equals(keyState) || "SYNCHRONIZATION".equals(keyState)) { + assertThat(failure) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Signature/registry/JWKS reads must precede owner SQL locks"); + } else { + throw new AssertionError("Unexpected key state " + keyState); + } + if ("SQL".equals(keyState) || "SYNCHRONIZATION".equals(keyState)) { + assertThat(reads.get()).isZero(); + } else { + assertThat(reads.get()).isGreaterThanOrEqualTo(1); + } + if ("SOURCE_FAILURE".equals(keyState)) { + assertThat(protectedFailures.get()).isGreaterThanOrEqualTo(1); + } + } + } + @Test void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrSubstitute() throws Exception { @@ -145,7 +512,9 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS var before = f.tx(() -> f.fences.read(original)); clock.advance(Duration.ofMinutes(10)); assertThatThrownBy(() -> issued.actors().verifySigned(issued.compact())) - .isInstanceOf(RuntimeException.class); + .isInstanceOf( + net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier + .VerificationException.class); asPeer("test", "game-design-service", () -> invoke(receiver, request)); var owner = new AccountOriginalDraftOrderService(issued.actors(), "test"); @@ -184,7 +553,9 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS "test", "game-design-service", () -> owner.claim(issued.compact(), changed, issued.environment()))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .extracting(failure -> io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION); var absent = new DraftAuthorizationFenceBinding( UUID.randomUUID(), @@ -207,7 +578,9 @@ void lostOriginalOrderResponseRecoversAfterSignedCreatorExpiryButCannotCreateOrS "test", "game-design-service", () -> owner.claim(issued.compact(), absent, issued.environment()))) - .isInstanceOf(RuntimeException.class); + .isInstanceOf( + net.firedevops.firemud.common.security.AccountAsymmetricJwtVerifier + .VerificationException.class); assertThat(f.tx(() -> f.fences.readOriginalBinding(absent.operationId()))).isEmpty(); for (String[] peer : List.of( @@ -355,6 +728,11 @@ private static void asPeer(String namespace, String workload, Runnable action) { private static final class ActorClock extends Clock { private Duration offset = Duration.ZERO; + private Instant frozen; + + void freezeAt(Instant value) { + frozen = value; + } void advance(Duration amount) { offset = offset.plus(amount); @@ -365,11 +743,11 @@ public ZoneId getZone() { } public Clock withZone(ZoneId zone) { - return Clock.offset(Clock.system(zone), offset); + return frozen == null ? Clock.offset(Clock.system(zone), offset) : Clock.fixed(frozen, zone); } public Instant instant() { - return Instant.now().plus(offset); + return frozen == null ? Instant.now().plus(offset) : frozen; } } } diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java new file mode 100644 index 0000000000..1acb484eb8 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationMtlsPostgresIntegrationTest.java @@ -0,0 +1,966 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import io.grpc.Server; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadGrpcCodec; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Genuine Account issuance/current actor, publication producer/storage, loopback mutual TLS and + * production read client. Trust provisioning, legal sources, synchronized Draft and World APPLIED + * descriptors are explicitly stipulated test inputs. No real World handoff, Game Design release, + * deployed workload trust, public wiring, or activation is established by this isolated proof. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationMtlsPostgresIntegrationTest { + private static final String NAMESPACE = "test"; + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-mtls-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-mtls-primary", + "6379"); + + @TempDir Path temporary; + + /** + * Real creator issuance, automatic Account environment capture and publication transaction over + * loopback mTLS. The strict upstream Game Design reader serves a stipulated immutable selection, + * not an actual Game Design reservation/database. Platform/legal/trust inputs remain fixtures. + */ + @Test + void selectedOrderProducerTransportUsesOriginalCreatorAndReplaysOneDurableHeldOrder() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("producer-pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("producer-owner")))) { + // Exactly one issuance/OTP consumption; no owner order is fabricated or preseeded. + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var selection = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()) + .selection(); + var issuance = + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'"); + var reads = new java.util.concurrent.CopyOnWriteArrayList(); + var upstream = + new net.firedevops.firemud.gamedesign.v1.GameDesignSelectedDraftPublicationReadServiceGrpc + .GameDesignSelectedDraftPublicationReadServiceImplBase() { + @Override + public void readSelectedDraftPublication( + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1.ReadSelectedDraftPublicationResponse> + observer) { + try { + requireAccountClient(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = AuthoredDraftPublishSelectionReadGrpcCodec.fromRequest(wire); + assertThat(request.targetNamespace()).isEqualTo(NAMESPACE); + assertThat(request.originalSelection()).isEqualTo(selection.canonicalBytes()); + reads.add(wire.getReadRequestId()); + observer.onNext( + AuthoredDraftPublishSelectionReadGrpcCodec.toSelectedResponse(request)); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, upstream); + try (var selectionClient = selectionClient(gdServer.getPort(), pki.accountClient, pki.ca)) { + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var owner = + new AccountSelectedDraftPublicationOrderService( + selectionClient, + new AccountPublicationAuthorizationService( + issued.actors(), sources.fences, repository), + NAMESPACE); + var producer = + new AccountSelectedDraftPublicationOrderGrpcService(owner, sources.terms, NAMESPACE); + var held = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server accountServer = terminalServer(pki.server, pki.ca, producer, held); + try { + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + assertThat(wire.toString()).doesNotContain(issued.compact()); + var rawKey = + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER); + var malformed = new io.grpc.Metadata(); + malformed.put(rawKey, new byte[] {(byte) 128}); + var duplicate = new io.grpc.Metadata(); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + duplicate.put(rawKey, issued.compact().getBytes(StandardCharsets.US_ASCII)); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + assertProducerHeaderDenied( + accountServer.getPort(), + wrongPeer, + pki.ca, + wire, + malformed, + Status.Code.PERMISSION_DENIED); + } + for (var headers : List.of(new io.grpc.Metadata(), malformed, duplicate)) { + assertProducerHeaderDenied( + accountServer.getPort(), + pki.gameDesign, + pki.ca, + wire, + headers, + Status.Code.UNAUTHENTICATED); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + for (var wrongPeer : List.of(pki.worldManagement, pki.otherNamespace)) { + try (var client = producerClient(accountServer.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.authorize(request)); + } + assertThat(reads).isEmpty(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isZero(); + } + try (var client = producerClient(accountServer.getPort(), pki.gameDesign, pki.ca)) { + var first = client.authorize(request); + var retry = client.authorize(request); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, issued.compact()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalCreatorCredential()) + .isEqualTo(request.originalCreatorCredential()); + var correlatedRetry = client.authorize(fresh); + assertThat(retry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(correlatedRetry.canonicalBytes()).isEqualTo(first.canonicalBytes()); + assertThat(first.input().selection().canonicalBytes()) + .isEqualTo(selection.canonicalBytes()); + assertThat(first.input().actorAccountId()).isEqualTo(sources.account.getAccountUuid()); + assertThat(reads).hasSize(3).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_sources"))) + .isEqualTo(first.sources().size()); + var stored = + sources.dsl.fetchSingle( + "SELECT binding, issuance_operation_id FROM account_selected_publication_authorizations WHERE operation_id = ?", + first.operationId()); + assertThat(stored.get("binding", byte[].class)).isEqualTo(first.canonicalBytes()); + assertThat(stored.get("issuance_operation_id", UUID.class)) + .isEqualTo(issuance.get("operation_id", UUID.class)); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_control_ui_issuance_operations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchSingle( + "SELECT operation_id, token_hash FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'")) + .isEqualTo(issuance); + assertPending(sources, repository, first); + try (var reader = client(accountServer.getPort(), pki.worldManagement, pki.ca)) { + var exactHeld = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, first); + assertThat(reader.read(exactHeld).request()).isEqualTo(exactHeld); + } + } + } finally { + accountServer.shutdownNow(); + assertThat(accountServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } finally { + gdServer.shutdownNow(); + assertThat(gdServer.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountSelectedPublicationOrderClient producerClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountSelectedPublicationOrderClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + /** Negative transport only: deliberately bypasses the production credential emitter. */ + private static void assertProducerHeaderDenied( + int port, + TestIdentity identity, + Path ca, + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest wire, + io.grpc.Metadata headers, + Status.Code expected) + throws Exception { + var channel = + new GrpcChannelFactory() + .buildChannel("127.0.0.1:" + port, 6565, identity.properties(ca), true); + try { + var peer = "spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service"; + var stub = + net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc + .newBlockingStub(channel) + .withCallCredentials( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials( + peer)) + .withInterceptors( + new net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor( + peer), + io.grpc.stub.MetadataUtils.newAttachHeadersInterceptor(headers)) + .withDeadlineAfter(5, TimeUnit.SECONDS); + assertCode(expected, () -> stub.authorizeSelectedPublication(wire)); + } finally { + channel.shutdownNow(); + assertThat(channel.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + + private static AuthoredDraftPublishSelectionReadClient selectionClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new AuthoredDraftPublishSelectionReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + /** + * Real Account storage and two strict loopback mTLS clients. Remote immutable terminals and the + * incoming Game Design request context are stipulated; remote owner databases are not exercised. + */ + @Test + void twoAuthenticatedTerminalOwnersSettleActualAccountOrderAndReadBackAfterCommit() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("settlement-pki"))); + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve(outcome.name())))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = + org.mockito.Mockito.spy(new AccountPublicationAuthorizationRepository(sources.dsl)); + var order = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository) + .authorize(issued.compact(), descriptor.selection(), issued.environment()); + var operation = + AccountPublicationAuthorizationPostgresIntegrationTest.operation( + order, descriptor.world()); + var terminal = + AccountPublicationAuthorizationPostgresIntegrationTest.terminal(operation, outcome); + var mode = new AtomicReference<>("exact"); + var gdReads = new java.util.concurrent.CopyOnWriteArrayList(); + var worldReads = new java.util.concurrent.CopyOnWriteArrayList(); + var gdEndpoint = + new net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceImplBase() { + @Override + public void readGameDesignPublicationTerminal( + net.firedevops.firemud.gamedesign.v1.ReadGameDesignPublicationTerminalRequest + wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.gamedesign.v1 + .ReadGameDesignPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = GameDesignPublicationTerminalReadGrpcCodec.fromRequest(wire); + gdReads.add(request.readRequestId().toString()); + if (mode.get().equals("gd-missing")) throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("gd-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var result = + new net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadResult( + request, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.Status.valueOf( + terminal.outcome().name()), + java.util.Optional.of(terminal)); + var response = + GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result) + .toBuilder(); + if (mode.get().startsWith("gd-") + && !mode.get().equals("gd-missing") + && !mode.get().equals("gd-unavailable")) { + byte[] echoedRequest = request.canonicalBytes(); + byte[] terminalBytes = terminal.canonicalBytes(); + if (mode.get().equals("gd-correlation")) { + echoedRequest = + new net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, + request.targetNamespace(), + UUID.randomUUID(), + request.operationBytes()) + .canonicalBytes(); + } else if (mode.get().equals("gd-operation")) { + var invalidRequest = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + invalidRequest, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadRequest.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalidRequest, "1"); + DraftAuthorizationFenceBinding.frame( + invalidRequest, request.targetNamespace()); + DraftAuthorizationFenceBinding.frame( + invalidRequest, request.readRequestId().toString()); + DraftAuthorizationFenceBinding.frame(invalidRequest, new byte[0]); + echoedRequest = invalidRequest.toByteArray(); + } else if (mode.get().equals("gd-unknown")) { + var invalid = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + invalid, GameDesignPublicationTerminalEvidence.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalid, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(invalid, "UNKNOWN"); + terminalBytes = invalid.toByteArray(); + } + var invalidResponse = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame( + invalidResponse, + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalReadEvidence.ReadResult.SCHEMA); + DraftAuthorizationFenceBinding.frame(invalidResponse, echoedRequest); + DraftAuthorizationFenceBinding.frame( + invalidResponse, terminal.outcome().name()); + DraftAuthorizationFenceBinding.frame(invalidResponse, terminalBytes); + response.setCanonicalResponseBytes( + com.google.protobuf.ByteString.copyFrom(invalidResponse.toByteArray())); + } + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + var worldEndpoint = + new net.firedevops.firemud.worldmanagement.v1.WorldPublicationTerminalReadServiceGrpc + .WorldPublicationTerminalReadServiceImplBase() { + @Override + public void readPublicationTerminal( + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalRequest wire, + io.grpc.stub.StreamObserver< + net.firedevops.firemud.worldmanagement.v1.ReadPublicationTerminalResponse> + observer) { + try { + requireAccountClient(); + var request = WorldPublicationTerminalReadGrpcCodec.fromRequest(wire); + worldReads.add(wire.getReadRequestId()); + if (mode.get().equals("world-missing")) + throw Status.NOT_FOUND.asRuntimeException(); + if (mode.get().equals("world-unavailable")) + throw Status.UNAVAILABLE.asRuntimeException(); + var response = + WorldPublicationTerminalReadGrpcCodec.toResponse(request, terminal) + .toBuilder(); + if (mode.get().equals("world-correlation")) + response.setReadRequestId(UUID.randomUUID().toString()); + if (mode.get().equals("world-operation")) + response.setOriginalOperation(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-terminal")) + response.setWorldTerminalEvidence(com.google.protobuf.ByteString.EMPTY); + if (mode.get().equals("world-unknown")) response.setWorldOutcomeValue(99); + if (mode.get().equals("world-phase")) + response.setWorldOutcomeValue( + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED ? 2 : 1); + observer.onNext(response.build()); + observer.onCompleted(); + } catch (RuntimeException failure) { + observer.onError(failure); + } + } + }; + Server gdServer = terminalServer(pki.gameDesignServer, pki.ca, gdEndpoint); + Server worldServer = terminalServer(pki.worldServer, pki.ca, worldEndpoint); + Server wrongServer = terminalServer(pki.server, pki.ca, gdEndpoint, worldEndpoint); + try (var gdClient = gameDesignClient(gdServer.getPort(), pki.accountClient, pki.ca); + var worldClient = worldClient(worldServer.getPort(), pki.accountClient, pki.ca)) { + var composition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, worldClient, sources.manager, NAMESPACE); + for (String failure : + List.of( + "gd-missing", + "gd-unavailable", + "gd-correlation", + "gd-operation", + "gd-unknown", + "world-missing", + "world-unavailable", + "world-correlation", + "world-operation", + "world-terminal", + "world-unknown", + "world-phase")) { + mode.set(failure); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + mode.set("exact"); + try (var wrongGd = gameDesignClient(wrongServer.getPort(), pki.accountClient, pki.ca); + var wrongWorld = worldClient(wrongServer.getPort(), pki.accountClient, pki.ca)) { + var wrongGdComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, wrongGd, worldClient, sources.manager, NAMESPACE); + var wrongWorldComposition = + new AccountSelectedDraftPublicationSettlementService( + repository, gdClient, wrongWorld, sources.manager, NAMESPACE); + assertThatThrownBy( + () -> asGameDesign(() -> wrongGdComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + assertThatThrownBy( + () -> + asGameDesign( + () -> wrongWorldComposition.settle(operation.canonicalBytes()))) + .isInstanceOf(RuntimeException.class); + assertPending(sources, repository, order); + } + var invocations = new AtomicInteger(); + var corruptReadback = new java.util.concurrent.atomic.AtomicBoolean(); + String schema = + java.util.Objects.requireNonNull( + sources.dsl.fetchOne("SELECT current_schema() AS schema")) + .get("schema", String.class); + org.mockito.Mockito.doAnswer( + call -> { + int invocation = invocations.incrementAndGet(); + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + if (invocation == 2) { + // Independent connection cannot see the first transaction's uncommitted + // insert. + // Seeing its exact row before the second owner invocation proves prior + // commit. + try (var connection = + java.sql.DriverManager.getConnection( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword())) { + connection.setSchema(schema); + try (var statement = + connection.prepareStatement( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?")) { + statement.setObject(1, order.operationId()); + try (var result = statement.executeQuery()) { + assertThat(result.next()).isTrue(); + assertThat(result.getBytes(1)).isEqualTo(terminal.canonicalBytes()); + assertThat(result.next()).isFalse(); + } + } + } + } + byte[] readback = (byte[]) call.callRealMethod(); + return corruptReadback.get() && invocation % 2 == 0 + ? new byte[] {99} + : readback; + }) + .when(repository) + .settle( + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.any(), + org.mockito.ArgumentMatchers.anyString(), + org.mockito.ArgumentMatchers.any()); + gdReads.clear(); + worldReads.clear(); + byte[] receipt = asGameDesign(() -> composition.settle(operation.canonicalBytes())); + assertThat(asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isEqualTo(receipt); + assertThat(invocations).hasValue(4); + assertThat(gdReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + var heldReader = + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + asGameDesign( + () -> { + heldReader.requireHeld( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, order)); + return null; + })); + assertThat(sources.tx(sources::changeRoleToAdmin).getRole()).isEqualTo("admin"); + corruptReadback.set(true); + assertThatThrownBy( + () -> asGameDesign(() -> composition.settle(operation.canonicalBytes()))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId())) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } finally { + for (Server server : List.of(gdServer, worldServer, wrongServer)) server.shutdownNow(); + for (Server server : List.of(gdServer, worldServer, wrongServer)) + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + } + + private static void assertPending( + AccountControlUiOwnerSourcesFixture sources, + AccountPublicationAuthorizationRepository repository, + AccountPublicationAuthorizationBinding order) { + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + sources.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy(() -> sources.tx(sources::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + } + + private static void requireAccountClient() { + var peer = GrpcPeerIdentity.current(); + if (peer == null + || !("spiffe://firemud/ns/" + NAMESPACE + "/sa/account-service").equals(peer.uri())) + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + + private static T asGameDesign(Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service") + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static Server terminalServer( + TestIdentity identity, Path ca, io.grpc.BindableService... endpoints) throws Exception { + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMetadataSize(AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var endpoint : endpoints) + builder.addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())); + return builder.build().start(); + } + + private static GameDesignPublicationTerminalClient gameDesignClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("127.0.0.1:" + port); + var client = + new GameDesignPublicationTerminalClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static WorldPublicationTerminalReadClient worldClient( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("127.0.0.1:" + port); + var client = + new WorldPublicationTerminalReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + @Test + void genuineProducerToGameDesignAndWorldMtlsReadersReplaysExactlyAndRejectsSubstitution() + throws Exception { + var pki = new TestPki(Files.createDirectories(temporary.resolve("pki"))); + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + Files.createDirectories(temporary.resolve("owner")))) { + var issued = fixture.issueCreator(); + var sources = issued.sources(); + var descriptor = + AccountPublicationAuthorizationPostgresIntegrationTest.proof( + sources, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var producer = + new AccountPublicationAuthorizationService(issued.actors(), sources.fences, repository); + var original = + producer.authorize(issued.compact(), descriptor.selection(), issued.environment()); + var request = AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + var endpoint = + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + repository, sources.manager, NAMESPACE), + NAMESPACE); + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.forServer( + pki.server.certificate().toFile(), pki.server.key().toFile()) + .trustManager(pki.ca.toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(endpoint, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + try { + try (var client = client(server.getPort(), pki.gameDesign, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + var freshRead = + AccountPublicationAuthorizationReadEvidence.Request.create(NAMESPACE, original); + assertThat(client.read(freshRead).request()).isEqualTo(freshRead); + var unknown = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + var changedFence = + new AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + for (var rejected : List.of(unknown, changedFence)) { + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> + client.read( + AccountPublicationAuthorizationReadEvidence.Request.create( + NAMESPACE, rejected))); + } + // A negative read cannot change the exact held owner row or prevent its next read. + assertThat(client.read(request).request()).isEqualTo(request); + } + try (var client = client(server.getPort(), pki.worldManagement, pki.ca)) { + var first = client.read(request); + var retry = client.read(request); + assertThat(first.request()).isEqualTo(request); + assertThat(retry.request()).isEqualTo(first.request()); + assertThat(first.request().originalPublicationAuthorizationBinding()) + .isEqualTo(original.canonicalBytes()); + } + for (var wrongPeer : + List.of(pki.wrongWorkload, pki.otherNamespace, pki.otherWorldNamespace)) { + try (var client = client(server.getPort(), wrongPeer, pki.ca)) { + assertCode(Status.Code.PERMISSION_DENIED, () -> client.read(request)); + } + } + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + sources.dsl.fetchCount( + org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + java.util.Objects.requireNonNull( + sources.dsl.fetchOne( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + original.operationId()), + "Expected exact retained publication after transport reads") + .get("binding", byte[].class)) + .isEqualTo(original.canonicalBytes()); + } finally { + server.shutdownNow(); + assertThat(server.awaitTermination(5, TimeUnit.SECONDS)).isTrue(); + } + } + } + + private static AccountPublicationAuthorizationReadClient client( + int port, TestIdentity identity, Path ca) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var client = + new AccountPublicationAuthorizationReadClient( + endpoints, identity.properties(ca), new GrpcChannelFactory(), NAMESPACE); + try { + client.init(); + return client; + } catch (Exception failure) { + client.close(); + throw failure; + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private record TestIdentity(Path certificate, Path key) { + CommonGrpcClientProperties properties(Path ca) { + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(key.toString()); + properties.setCaCert(ca.toString()); + return properties; + } + } + + /** Ephemeral keytool PKI, following Account's existing loopback test; no runtime credentials. */ + private static final class TestPki { + private static final String PASSWORD = "test-only-publication-mtls-password"; + final Path ca; + final TestIdentity server, + accountClient, + gameDesignServer, + worldServer, + gameDesign, + worldManagement, + wrongWorkload, + otherNamespace, + otherWorldNamespace; + + TestPki(Path root) throws Exception { + var authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + root, "ca.p12", "ca.crt", "test-ca", "CN=Account publication test CA", PASSWORD); + ca = authority.certificateFile(); + server = issue(root, authority, "account-server", NAMESPACE, "account-service", true); + accountClient = issue(root, authority, "account-client", NAMESPACE, "account-service", false); + gameDesignServer = + issue(root, authority, "game-design-server", NAMESPACE, "game-design-service", true); + worldServer = + issue(root, authority, "world-server", NAMESPACE, "world-management-service", true); + gameDesign = + issue(root, authority, "game-design-client", NAMESPACE, "game-design-service", false); + worldManagement = + issue(root, authority, "world-client", NAMESPACE, "world-management-service", false); + wrongWorkload = + issue(root, authority, "game-session-client", NAMESPACE, "game-session-service", false); + otherNamespace = + issue( + root, + authority, + "other-game-design-client", + "other-test", + "game-design-service", + false); + otherWorldNamespace = + issue( + root, + authority, + "other-world-client", + "other-test", + "world-management-service", + false); + } + + private static TestIdentity issue( + Path root, + AccountStartSessionReservationProofPki.TestCertificateAuthority authority, + String alias, + String namespace, + String workload, + boolean server) + throws Exception { + var issued = + AccountStartSessionReservationProofPki.issueIdentity( + root, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + ".crt", + "spiffe://firemud/ns/" + namespace + "/sa/" + workload, + server, + true, + false); + byte[] privateKey = + java.util.Objects.requireNonNull( + java.util.Objects.requireNonNull( + issued.identity().privateKey(), "Expected ephemeral test private key") + .getEncoded(), + "Expected encoded ephemeral test private key"); + Path key = root.resolve(alias + ".key"); + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(privateKey); + Files.writeString( + key, + "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n", + StandardCharsets.US_ASCII); + java.util.Arrays.fill(privateKey, (byte) 0); + return new TestIdentity(issued.certificateFile(), key); + } + } +} diff --git a/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java new file mode 100644 index 0000000000..74f59e9470 --- /dev/null +++ b/services/account-service/src/test/java/integration/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationPostgresIntegrationTest.java @@ -0,0 +1,1396 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Base64; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.accountservice.authordraft.AccountControlUiAuthority; +import net.firedevops.firemud.accountservice.authordraft.DraftAuthorizationFenceRepository; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.world.RoomTemplateRef; +import net.firedevops.firemud.common.world.WorldDraftStartLocationEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.test.IsolatedWorldPublicationInventoryFixtures; +import net.firedevops.firemud.test.TestContainerImages; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.Network; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Real Account signer/issuance/Redis/current-actor and PostgreSQL ordering. World APPLIED and + * synchronized selection bytes below are explicitly test-only upstream stipulations. This does not + * prove authenticated World transport, publication terminalization or runtime activation. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AccountPublicationAuthorizationPostgresIntegrationTest { + private static final Network NETWORK = Network.newNetwork(); + + @Container + static final PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final GenericContainer redis = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .withNetworkAliases("publication-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final GenericContainer replica = + new GenericContainer<>(TestContainerImages.redis()) + .withNetwork(NETWORK) + .dependsOn(redis) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "publication-primary", + "6379"); + + @TempDir Path temporary; + + /** + * Both owner readbacks here are upstream authenticated-owner stipulations, not transport proof. + */ + @Test + void exactTwoOwnerSettlementRollsBackAtomicallyThenReplaysAfterLostAcknowledgement() + throws Exception { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = terminal(operation, outcome); + String phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.settle(operation, terminal, phase, terminal.canonicalBytes()); + throw new IllegalStateException("rollback before owner commit"); + })) + .isInstanceOf(IllegalStateException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy(() -> f.tx(f::changeRoleToAdmin)) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + + byte[] originalBinding = order.canonicalBytes(); + byte[] receipt = + f.tx(() -> repository.settle(operation, terminal, phase, terminal.canonicalBytes())); + // A committed response may be lost. Fresh outside transport correlations never enter + // settlement identity; historical replay does not authenticate a new creator credential. + UUID firstTransportRead = UUID.randomUUID(), retryTransportRead = UUID.randomUUID(); + assertThat(firstTransportRead).isNotEqualTo(retryTransportRead); + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT binding FROM account_selected_publication_authorizations WHERE operation_id = ?", + order.operationId()) + .get("binding", byte[].class)) + .isEqualTo(originalBinding); + assertThatThrownBy( + () -> + f.tx( + () -> { + repository.readHeld(order); + return null; + })) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("already settled"); + var readOwner = + new AccountPublicationAuthorizationReadService(repository, f.manager, "test"); + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", order)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(((io.grpc.StatusRuntimeException) failure).getStatus().getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); + // Even after the source changes, the original committed issuance and receipt replay. + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .isEqualTo(receipt); + for (String mutation : + List.of( + "UPDATE account_selected_publication_settlements SET world_outcome = 'ABORTED'", + "DELETE FROM account_selected_publication_settlements", + "TRUNCATE account_selected_publication_settlements")) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(mutation))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + } + } + + @Test + void missingAmbiguousSubstitutedAndDisagreeingOwnersKeepOriginalSourcesHeld() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var order = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var noPublication = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var published = terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + var wrongFence = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + order.operationId(), UUID.randomUUID(), order.input(), order.sources()); + var wrongOperation = operation(wrongFence, proof.world()); + for (Runnable rejected : + List.of( + () -> + repository.settle( + operation, noPublication, "PUBLISHED", noPublication.canonicalBytes()), + () -> + repository.settle( + operation, noPublication, "ABORTED", published.canonicalBytes()), + () -> + repository.settle( + operation, + noPublication, + "RECONCILIATION_REQUIRED", + noPublication.canonicalBytes()), + () -> repository.settle(operation, noPublication, "ABORTED", new byte[0]), + () -> repository.settle(operation, noPublication, "ABORTED", null), + () -> + repository.settle( + wrongOperation, + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION), + "ABORTED", + terminal( + wrongOperation, + GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) + .canonicalBytes()))) { + assertThatThrownBy( + () -> + f.tx( + () -> { + rejected.run(); + return null; + })) + .isInstanceOf(RuntimeException.class); + } + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + + byte[] receipt = + f.tx( + () -> + repository.settle( + operation, noPublication, "ABORTED", noPublication.canonicalBytes())); + assertThatThrownBy( + () -> + f.tx( + () -> + repository.settle( + operation, published, "PUBLISHED", published.canonicalBytes()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Changed original"); + assertThat( + f.dsl + .fetchSingle( + "SELECT receipt FROM account_selected_publication_settlements WHERE operation_id = ?", + order.operationId()) + .get("receipt", byte[].class)) + .isEqualTo(receipt); + } + } + + @Test + void settlingOneOrderLeavesEveryOtherOriginalSourceParticipationPending() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var service = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository); + var first = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var secondSelection = + selection(proof.selection().selectedCommit(), "other order", "another-publication"); + var second = service.authorize(issued.compact(), secondSelection, issued.environment()); + var operation = operation(first, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + f.tx(() -> repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes())); + f.tx( + () -> { + repository.readHeld(second); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + var captured = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), captured.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + } + } + + static GameDesignPublicationTerminalEvidence terminal( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence.Outcome outcome) { + if (outcome == GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION) { + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), outcome, null, null); + } + var request = operation.world().request(); + var participants = + AuthoredWorldReleaseAttestationEvidence.requiredParticipantOrder().stream() + .map( + owner -> + new GameDesignPublicationTerminalEvidence.Participant( + owner, + Long.toString( + operation + .account() + .input() + .selection() + .target() + .gameDesignVersionRowId()), + null, + request.appliedCommitId(), + request.contentDigest(), + AuthoredWorldReleaseAttestationEvidence.supportedParticipantDigestSchema( + owner, AuthoredWorldReleaseAttestationEvidence.SELECTOR_SCHEMA_VERSION), + "GAME_LOGIC".equals(owner) ? "sha256:" + "a".repeat(64) : null, + null, + null)) + .toList(); + var release = + new GameDesignPublicationTerminalEvidence.ReleaseContent( + operation.account().tenantId(), + request.canonicalVersionId(), + "release-exact", + 1, + "v2", + request.publishWorkflowId(), + "sha256:" + "c".repeat(64), + 1, + List.of(), + List.of(), + participants, + List.of("look"), + "generation-1", + operation.world()); + return new GameDesignPublicationTerminalEvidence( + operation.canonicalBytes(), + outcome, + release, + Math.addExact(request.versionStateEpoch(), 1)); + } + + static GameDesignPublicationOperationBinding operation( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding account, + WorldPublishedStartLocationEvidence world) { + return new GameDesignPublicationOperationBinding( + account, world, IsolatedWorldPublicationInventoryFixtures.stipulated(account, world)); + } + + private static byte[] rawOperation( + String schema, byte[] accountBytes, byte[] worldBytes, byte[] inventoryBytes, String digest) { + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, schema); + DraftAuthorizationFenceBinding.frame(out, accountBytes); + DraftAuthorizationFenceBinding.frame(out, worldBytes); + if (schema.equals(GameDesignPublicationOperationBinding.SCHEMA)) { + DraftAuthorizationFenceBinding.frame(out, inventoryBytes); + DraftAuthorizationFenceBinding.frame(out, digest); + } + return out.toByteArray(); + } + + private static void assertSqlState(Throwable failure, String expectedState) { + String sqlState = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) { + sqlState = sqlException.getSQLState(); + } + } + assertThat(sqlState).isEqualTo(expectedState); + } + + @Test + void directMalformedOrSubstitutedReceiptRowsDoNotRemovePendingProtection() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + Integer selectedSourceKeyWidth = + f.dsl + .fetchSingle( + "SELECT character_maximum_length FROM information_schema.columns" + + " WHERE table_schema = current_schema()" + + " AND table_name = 'account_selected_publication_sources'" + + " AND column_name = 'source_key'") + .get(0, Integer.class); + assertThat(selectedSourceKeyWidth).isEqualTo(2048); + String inventoryGuard = + f.dsl + .fetchSingle( + "SELECT pg_get_functiondef('require_selected_inventory_operation_v2(bytea)'::regprocedure)") + .get(0, String.class); + assertThat(inventoryGuard) + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'regionTemplateId'), '[]'::JSONB)") + .contains("coalesce(jsonb_agg(entry ORDER BY entry->>'bindingTemplateId'), '[]'::JSONB)") + .contains( + "OR selector->'request'->'worldAffectedTuples' IS DISTINCT FROM expected_tuples") + .contains( + "OR model->'appliedEpochs' IS DISTINCT FROM expected_epochs OR expected_epochs = '[]'::JSONB") + .contains( + "Inventory differs from exact original selected Account, APPLIED graph or freeze"); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var out = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, order.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, "ABORTED"); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + byte[] receipt = out.toByteArray(); + String insert = + "INSERT INTO account_selected_publication_settlements" + + " (operation_id, fence_id, account_binding, publication_operation, game_design_outcome," + + " game_design_terminal, world_outcome, world_terminal, receipt) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"; + List malformed = + List.of( + new Object[] { + order.operationId(), + UUID.randomUUID(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + new byte[] {0}, + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + new byte[] {0}, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + new byte[] {0}, + "ABORTED", + new byte[] {0}, + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "PUBLISHED", + terminal.canonicalBytes(), + receipt + }, + new Object[] { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + operation.canonicalBytes(), + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + new byte[] {0} + }); + for (Object[] values : malformed) { + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, values))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + String publicInventoryJson = + new String( + operation.inventory().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + String graphDigest = operation.inventory().publicEvidence().sourceModel().graphDigest(); + byte[] substitutedInventory = + publicInventoryJson + .replace( + "\"graphDigest\":\"" + graphDigest + "\"", + "\"graphDigest\":\"sha256:" + "0".repeat(64) + "\"") + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] validOperation = operation.canonicalBytes(); + String tenantId = proof.world().request().canonicalTenantId().toString(); + String versionId = proof.world().request().canonicalVersionId().toString(); + String originalRegionTemplateId = + operation + .inventory() + .publicEvidence() + .sourceModel() + .regionGeneratorInputs() + .get(0) + .regionTemplateId() + .toString(); + String originalRegionInputs = + "\"regionGeneratorInputs\":[" + + inventoryRegionGeneratorInput(originalRegionTemplateId) + + "]"; + String unsortedRegionInputs = + "[" + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000002") + + "," + + inventoryRegionGeneratorInput("00000000-0000-0000-0000-000000000001") + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"REGION\",\"rowCount\":1") + .contains(originalRegionInputs); + byte[] unsortedRegionInventory = + publicInventoryJson + .replace( + "\"family\":\"REGION\",\"rowCount\":1", "\"family\":\"REGION\",\"rowCount\":2") + .replace(originalRegionInputs, "\"regionGeneratorInputs\":" + unsortedRegionInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedRegionOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedRegionInventory, + DraftAuthorizationFenceBinding.digest(unsortedRegionInventory)); + Object[] unsortedRegionSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedRegionOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedRegionSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered region generator input")); + String unsortedSpawnInputs = + "[" + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000002", + "00000000-0000-0000-0000-000000000003", + "00000000-0000-0000-0000-000000000004", + tenantId, + versionId) + + "," + + inventorySpawnBindingInput( + "00000000-0000-0000-0000-000000000001", + "00000000-0000-0000-0000-000000000005", + "00000000-0000-0000-0000-000000000006", + tenantId, + versionId) + + "]"; + assertThat(publicInventoryJson) + .contains("\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0") + .contains("\"spawnBindingCount\":0") + .contains("\"spawnBindingInputs\":[]"); + byte[] unsortedSpawnInventory = + publicInventoryJson + .replace( + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":0", + "\"family\":\"WORLD_ENTITY_SPAWN_BINDING\",\"rowCount\":2") + .replace("\"spawnBindingCount\":0", "\"spawnBindingCount\":2") + .replace("\"spawnBindingInputs\":[]", "\"spawnBindingInputs\":" + unsortedSpawnInputs) + .getBytes(java.nio.charset.StandardCharsets.UTF_8); + byte[] unsortedSpawnOperation = + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + unsortedSpawnInventory, + DraftAuthorizationFenceBinding.digest(unsortedSpawnInventory)); + Object[] unsortedSpawnSettlement = { + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + unsortedSpawnOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt + }; + assertThatThrownBy(() -> f.tx(() -> f.dsl.execute(insert, unsortedSpawnSettlement))) + .satisfies( + failure -> + assertSqlFailure( + failure, "23514", "Unsupported or unordered scoped spawn input")); + List invalidOperations = + List.of( + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + new byte[0], + DraftAuthorizationFenceBinding.digest(new byte[0])), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + operation.inventory().canonicalBytes(), + "sha256:" + "0".repeat(64)), + rawOperation( + GameDesignPublicationOperationBinding.SCHEMA, + order.canonicalBytes(), + proof.world().canonicalBytes(), + substitutedInventory, + DraftAuthorizationFenceBinding.digest(substitutedInventory)), + rawOperation( + "game-design-publication-operation/v1", + order.canonicalBytes(), + proof.world().canonicalBytes(), + null, + null), + java.util.Arrays.copyOf(validOperation, validOperation.length + 1)); + for (byte[] invalidOperation : invalidOperations) { + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + insert, + order.operationId(), + order.fenceId(), + order.canonicalBytes(), + invalidOperation, + "NO_PUBLICATION", + terminal.canonicalBytes(), + "ABORTED", + terminal.canonicalBytes(), + receipt))) + .satisfies(failure -> assertSqlState(failure, "23514")); + } + assertThat( + f.dsl.fetchCount(org.jooq.impl.DSL.table("account_selected_publication_settlements"))) + .isZero(); + f.tx( + () -> { + repository.readHeld(order); + return null; + }); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void sourceWriterCannotPassUncommittedSettlementAndCanRetryAfterItsCommit() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = + terminal(operation, GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + try { + f.tx( + () -> { + repository.settle(operation, terminal, "ABORTED", terminal.canonicalBytes()); + int settlementPid = + f.dsl.fetchSingle("SELECT pg_backend_pid() AS pid").get("pid", Integer.class); + var writer = + executor.submit( + () -> + f.tx( + () -> { + int writerPid = + f.dsl + .fetchSingle("SELECT pg_backend_pid() AS pid") + .get("pid", Integer.class); + assertThat(writerPid).isNotEqualTo(settlementPid); + // The actual source trigger takes the same source locks NOWAIT. A + // pending + // transaction cannot release its protection to a different writer + // connection. + return f.changeRoleToAdmin(); + })); + assertThatThrownBy(() -> writer.get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(org.jooq.exception.DataAccessException.class); + return null; + }); + assertThat(f.tx(f::changeRoleToAdmin).getRole()).isEqualTo("admin"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void authenticatesPreFreezeDistinctOrderReplaysExactlyAndBlocksSourceWritersAndDisclosure() + throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var original = service.authorize(issued.compact(), proof.selection(), issued.environment()); + var replay = service.authorize(issued.compact(), proof.selection(), issued.environment()); + assertThat(replay.canonicalBytes()).isEqualTo(original.canonicalBytes()); + assertThat(original.operationId()).isNotEqualTo(proof.original().operationId()); + assertThat(original.fenceId()).isNotEqualTo(proof.original().fenceId()); + assertThat(f.dsl.fetchCount(org.jooq.impl.DSL.table("account_draft_authorization_fences"))) + .isZero(); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isEqualTo(1); + assertThat( + java.util.Objects.requireNonNull( + f.dsl.fetchOne( + "SELECT world_evidence FROM account_selected_publication_authorizations" + + " WHERE operation_id = ?", + original.operationId()), + "Expected exact pre-freeze Account order") + .get("world_evidence", byte[].class)) + .isNull(); + // The immutable Account order is available before the separate World capture is correlated. + operation(original, proof.world()); + assertThat(original.sources()).hasSize(8); + var readOwner = + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(f.dsl), f.manager, "test"); + var readRequest = + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence + .Request.create("test", original); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + var mismatched = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + original.operationId(), UUID.randomUUID(), original.input(), original.sources()); + var unknown = + new net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding( + UUID.randomUUID(), original.fenceId(), original.input(), original.sources()); + for (var rejected : List.of(mismatched, unknown)) { + assertThatThrownBy( + () -> + asGameDesign( + () -> + readOwner.requireHeld( + net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadEvidence.Request.create( + "test", rejected)))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(io.grpc.Status.fromThrowable(failure).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + } + assertThatThrownBy( + () -> + f.tx( + () -> { + f.fences.requireDisclosurePreparation(original.sources()); + return null; + })) + .hasMessageContaining("selected-publication"); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), original.sources(), new byte[] {1}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isFalse(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isFalse(); + // An exact retained replay remains possible while a later source change waits. + assertThat( + service + .authorize(issued.compact(), proof.selection(), issued.environment()) + .canonicalBytes()) + .isEqualTo(original.canonicalBytes()); + asGameDesign(() -> readOwner.requireHeld(readRequest)); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE accounts SET role = 'admin' WHERE id = ?", + f.account.getId()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("selected-publication"); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET fence_id = ?", + UUID.randomUUID()))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> f.tx(() -> f.dsl.execute("DELETE FROM account_selected_publication_sources"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + var changed = selection(proof.selection().selectedCommit(), "changed notes"); + assertThatThrownBy(() -> service.authorize(issued.compact(), changed, issued.environment())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + service.authorize( + issued.compact() + "changed", proof.selection(), issued.environment())) + .isInstanceOf(RuntimeException.class); + // Original source/issuance identity is immutable even if a privileged SQL caller tries it. + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_authorizations SET issuance_fence = issuance_fence + 1"))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + assertThatThrownBy( + () -> + f.tx( + () -> + f.dsl.execute( + "UPDATE account_selected_publication_sources SET source_evidence = ?", + new byte[] {9}))) + .isInstanceOf(org.jooq.exception.DataAccessException.class); + } + } + + @Test + void earlierWaitingSourceChangeWinsAndDeniedAuthenticationCreatesNoOperation() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var source = + f.tx( + () -> + f.authority.capture(f.account.getAccountUuid(), f.tenant, issued.environment())); + var change = + new DraftAuthorizationFenceRepository.SourceChange( + UUID.randomUUID(), source.sources(), new byte[] {2}); + assertThat(f.tx(() -> f.fences.requestSourceChange(change))).isTrue(); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + assertThatThrownBy( + () -> service.authorize(issued.compact(), proof.selection(), issued.environment())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("source change is waiting"); + assertThatThrownBy( + () -> + service.authorize( + "unsigned-caller-claim", proof.selection(), issued.environment())) + .isInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(f.tx(() -> f.fences.sourceMutationPermitted(change))).isTrue(); + } + } + + @Test + void actualSourceWriterBlocksCreatorCaptureThenWinsBeforePublication() throws Exception { + try (var fixture = fixture()) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var service = + new AccountPublicationAuthorizationService( + issued.actors(), f.fences, new AccountPublicationAuthorizationRepository(f.dsl)); + var accounts = new net.firedevops.firemud.accountservice.repository.AccountRepository(f.dsl); + var executor = java.util.concurrent.Executors.newSingleThreadExecutor(); + var attempt = + new java.util.concurrent.atomic.AtomicReference>(); + try { + f.tx( + () -> { + int blockerPid = + java.util.Objects.requireNonNull( + f.dsl.fetchOne("SELECT pg_backend_pid() AS pid"), + "Expected PostgreSQL source-writer connection") + .get("pid", Integer.class); + var account = + java.util.Objects.requireNonNull( + accounts.findByIdForUpdate(f.account.getId()).orElseThrow(), + "Expected locked Account source before canonical role mutation"); + assertThat(account.getRole()).isNotEqualTo("player"); + attempt.set( + executor.submit( + () -> + service.authorize( + issued.compact(), proof.selection(), issued.environment()))); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(10); + Integer blockedPid = null; + while (System.nanoTime() < deadline && blockedPid == null) { + if (attempt.get().isDone()) { + try { + attempt.get().get(); + } catch (java.util.concurrent.ExecutionException failure) { + throw new AssertionError( + "Creator authorization failed before the Account-row wait was observed", + failure.getCause()); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw new AssertionError( + "Interrupted while diagnosing completed creator authorization", + interrupted); + } + throw new AssertionError( + "Creator authorization succeeded before the source writer committed"); + } + // Activity snapshots are otherwise frozen for this blocker transaction. + f.dsl.fetch("SELECT pg_stat_clear_snapshot()"); + var blocked = + f.dsl.fetchOne( + "SELECT pid FROM pg_stat_activity WHERE datname = current_database()" + + " AND ? = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' LIMIT 1", + blockerPid); + if (blocked != null) blockedPid = blocked.get("pid", Integer.class); + else Thread.onSpinWait(); + } + assertThat(blockedPid) + .as("Distinct creator connection physically waits on source-writer Account row") + .isNotNull(); + assertThat(blockedPid).isNotEqualTo(blockerPid); + assertThat(attempt.get().isDone()).isFalse(); + // Actual guarded source write, held until this transaction commits. The old signed + // credential cannot authorize a publication from the newly changed Account state. + account.setRole("player"); + assertThat(accounts.save(account).getRole()).isEqualTo("player"); + return null; + }); + assertThatThrownBy(() -> attempt.get().get(10, java.util.concurrent.TimeUnit.SECONDS)) + .isInstanceOf(java.util.concurrent.ExecutionException.class) + .hasCauseInstanceOf(RuntimeException.class); + assertThat( + f.dsl.fetchCount( + org.jooq.impl.DSL.table("account_selected_publication_authorizations"))) + .isZero(); + assertThat(accounts.findById(f.account.getId()).orElseThrow().getRole()) + .isEqualTo("player"); + } finally { + executor.shutdownNow(); + assertThat(executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)).isTrue(); + } + } + } + + @Test + void closureInventoryUpgradePreservesOriginalLegacySettlementsAndExactReplay() throws Exception { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = + new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary, + UUID.randomUUID(), + java.time.Clock.systemUTC(), + "1010")) { + var issued = fixture.issueCreator(); + var f = issued.sources(); + var proof = proof(f, issued.environment()); + var repository = new AccountPublicationAuthorizationRepository(f.dsl); + var order = + new AccountPublicationAuthorizationService(issued.actors(), f.fences, repository) + .authorize(issued.compact(), proof.selection(), issued.environment()); + var operation = operation(order, proof.world()); + var terminal = terminal(operation, outcome); + String phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + byte[] receipt = + f.tx(() -> repository.settle(operation, terminal, phase, terminal.canonicalBytes())); + var before = publicationRetentionRows(f.dsl); + f.upgradeToCurrent(); + assertThat(publicationRetentionRows(f.dsl)).isEqualTo(before); + f.dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", operation.canonicalBytes()); + assertThat( + f.tx( + () -> repository.settle(operation, terminal, phase, terminal.canonicalBytes()))) + .containsExactly(receipt); + assertThat(publicationRetentionRows(f.dsl)).isEqualTo(before); + } + } + } + + private static java.util.Map> publicationRetentionRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + java.util.List.of( + "account_selected_publication_authorizations", + "account_selected_publication_sources", + "account_selected_publication_settlements", + "account_control_ui_issuance_operations", + "flyway_schema_history")) { + String filter = + table.equals("flyway_schema_history") ? " WHERE version IS DISTINCT FROM '1011'" : ""; + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + + table + + " r" + + filter + + " ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + + private AccountControlUiOriginalOrderFixture fixture() throws Exception { + return new AccountControlUiOriginalOrderFixture( + postgres.getJdbcUrl(), + postgres.getUsername(), + postgres.getPassword(), + redis.getHost(), + redis.getMappedPort(6379), + temporary); + } + + private static void asGameDesign(Runnable action) { + io.grpc.Context.current() + .withValue( + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.CONTEXT_KEY, + net.firedevops.firemud.common.grpc.GrpcPeerIdentity.parseUri( + "spiffe://firemud/ns/test/sa/game-design-service") + .orElseThrow()) + .run(action); + } + + record Proof( + AuthoredDraftPublishSelectionBinding selection, + WorldPublishedStartLocationEvidence world, + DraftAuthorizationFenceBinding original) {} + + /** Closed World codec bytes copied in spirit from the existing isolated selector fixtures. */ + static Proof proof( + AccountControlUiOwnerSourcesFixture f, + net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService + .CapturedEnvironmentBoundary + environment) + throws Exception { + UUID version = UUID.randomUUID(), request = UUID.randomUUID(), commit = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + f.tenant, + version, + 17, + "test-private-tenant", + 11, + "test-private-tenant", + "NEW_GAME_ROW"); + List families = List.of("REGION", "ZONE", "ROOM"); + List templates = List.of(UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID()); + List revisions = new ArrayList<>(); + List affected = new ArrayList<>(); + for (int i = 0; i < families.size(); i++) { + UUID revision = UUID.randomUUID(); + var mutation = new LinkedHashMap(); + mutation.put("logicalRevisionId", revision.toString()); + mutation.put("commitId", commit.toString()); + mutation.put("aggregateType", "WORLD_DESIGN_AGGREGATE_TYPE_" + families.get(i)); + mutation.put("aggregateId", templates.get(i).toString()); + if (i == 0) + mutation.put( + "freshGraphDeclaration", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "startLocation", + Map.of( + "tenantId", + f.tenant.toString(), + "versionId", + version.toString(), + "roomTemplateId", + templates.get(2).toString()), + "familyCounts", + List.of( + "REGION", + "ZONE", + "ROOM", + "ROOM_EXIT", + "GENERATION_RULE", + "WORLD_ENTITY_SPAWN_BINDING") + .stream() + .map( + family -> + Map.of( + "family", + "WORLD_DESIGN_AGGREGATE_TYPE_" + family, + "count", + families.contains(family) ? 1 : 0)) + .toList())); + revisions.add( + new DraftCommitBinding.RevisionPayload( + Integer.toString(i), + revision, + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + new tools.jackson.databind.ObjectMapper().writeValueAsString(mutation))); + affected.add( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + families.get(i), + templates.get(i).toString(), + "AGGREGATE", + templates.get(i).toString(), + "0")); + } + var draft = DraftCommitBinding.create(target, request, commit, "base-1", revisions, affected); + var selection = selection(draft, "selected publication proof"); + var original = + new DraftAuthorizationFenceBinding( + UUID.randomUUID(), + request, + commit, + UUID.randomUUID(), + f.account.getAccountUuid(), + f.tenant, + version, + "base-1", + "0", + draft.canonicalBytes(), + draft.canonicalBytes(), + draft.digest(), + f.tx(() -> f.authority.capture(f.account.getAccountUuid(), f.tenant, environment)) + .sources()); + UUID intake = UUID.randomUUID(); + var operation = new java.io.ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(operation, "world-draft-terminal-operation/v1"); + for (UUID id : + List.of(original.operationId(), request, commit, original.fenceId(), f.tenant, version)) + DraftAuthorizationFenceBinding.frame(operation, id.toString()); + DraftAuthorizationFenceBinding.frame(operation, draft.canonicalBytes()); + for (String value : + List.of( + "test", + f.tenant.toString(), + version.toString(), + original.operationId().toString(), + "17", + intake.toString(), + UUID.randomUUID().toString(), + "a".repeat(64), + UUID.randomUUID().toString(), + "b".repeat(64), + "c".repeat(64), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()))) + DraftAuthorizationFenceBinding.frame(operation, value); + DraftAuthorizationFenceBinding.frame(operation, original.canonicalBytes()); + List> rows = new ArrayList<>(); + for (int i = 0; i < revisions.size(); i++) { + var mapping = new LinkedHashMap(); + mapping.put("id", i + 1); + mapping.put("target_namespace", "test"); + mapping.put("canonical_tenant_id", f.tenant.toString()); + mapping.put("canonical_version_id", version.toString()); + mapping.put("family", families.get(i)); + mapping.put("template_id", templates.get(i).toString()); + mapping.put("private_row_key", 101 + i); + mapping.put("tenant_id", 11); + mapping.put("version_id", 19); + mapping.put("version_identity_operation_id", original.operationId().toString()); + mapping.put("request_id", request.toString()); + mapping.put("commit_id", commit.toString()); + mapping.put("revision_id", revisions.get(i).revisionId().toString()); + mapping.put("revision_order", Integer.toString(i)); + rows.add(Map.of("mapping", mapping, "content", Map.of())); + } + byte[] graph = + AccountControlUiAuthority.canonical( + Map.of( + "schemaVersion", + "2", + "canonicalTenantId", + f.tenant.toString(), + "canonicalVersionId", + version.toString(), + "rows", + rows)); + String graphDigest = DraftAuthorizationFenceBinding.digest(graph); + var receipt = + WorldDraftStartLocationEvidence.create( + "test", + original.operationId(), + request, + commit, + original.fenceId(), + DraftAuthorizationFenceBinding.digest(original.canonicalBytes()), + draft.digest(), + new RoomTemplateRef(f.tenant, version, templates.get(2)), + graphDigest); + var applied = new LinkedHashMap(); + applied.put("schema", "world-draft-graph-applied/v2"); + applied.put("status", "APPLIED"); + applied.put("operationBytesBase64", b64(operation.toByteArray())); + applied.put("graphBytesBase64", b64(graph)); + applied.put("graphDigest", graphDigest); + applied.put("startLocationReceiptBase64", b64(receipt.canonicalBytes())); + applied.put("startLocationReceiptDigest", receipt.receiptDigest()); + applied.put( + "appliedEpochs", + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + Map.of( + "aggregateType", + u.aggregateType(), + "aggregateId", + u.aggregateId(), + "scopeType", + u.scopeType(), + "scopeId", + u.scopeId(), + "expectedEpoch", + "0", + "resultingEpoch", + "1")) + .toList()); + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + "test", + f.tenant, + version, + intake, + UUID.randomUUID(), + selection.intent().publishRequestId(), + selection.digest().substring(7), + 5, + PublicationDigestRequestBinding.full( + f.tenant.toString(), "17", selection.intent().publishRequestId()) + .derivedWorkflowIdentity(), + commit.toString(), + "b".repeat(64), + 3, + draft.affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT).stream() + .map( + u -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + u.owner().name(), + u.aggregateType(), + u.aggregateId(), + u.scopeType(), + u.scopeId(), + u.expectedEpoch())) + .toList()); + return new Proof( + selection, + new WorldPublishedStartLocationEvidence( + worldRequest, + receipt.canonicalBytes(), + original.canonicalBytes(), + AccountControlUiAuthority.canonical(applied)), + original); + } + + private static String b64(byte[] value) { + return Base64.getEncoder().encodeToString(value); + } + + private static String inventorySpawnBindingInput( + String bindingTemplateId, + String roomTemplateId, + String entityTemplateId, + String tenantId, + String versionId) { + return "{\"bindingTemplateId\":\"" + + bindingTemplateId + + "\",\"entityReferenceKind\":\"ENTITY_TEMPLATE_REFERENCE_TYPE_CANONICAL_UUID\",\"entityTemplateId\":\"" + + entityTemplateId + + "\",\"entityTemplateType\":\"ITEM\",\"entityTenantId\":\"" + + tenantId + + "\",\"entityVersionId\":\"" + + versionId + + "\",\"respawnDelaySeconds\":0,\"roomTemplateId\":\"" + + roomTemplateId + + "\",\"spawnCount\":1}"; + } + + private static String inventoryRegionGeneratorInput(String regionTemplateId) { + return "{\"generatorParams\":\"\",\"generatorType\":\"\",\"regionTemplateId\":\"" + + regionTemplateId + + "\"}"; + } + + private static void assertSqlFailure( + Throwable failure, String expectedState, String expectedMessage) { + java.sql.SQLException sqlFailure = null; + for (Throwable cause = failure; cause != null; cause = cause.getCause()) { + if (cause instanceof java.sql.SQLException sqlException) sqlFailure = sqlException; + } + assertThat((Throwable) sqlFailure).isNotNull(); + var exactSqlFailure = + java.util.Objects.requireNonNull(sqlFailure, "Expected SQL failure from direct insert"); + assertThat(exactSqlFailure.getSQLState()).isEqualTo(expectedState); + assertThat(exactSqlFailure.getMessage()).contains(expectedMessage); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes) { + return selection(draft, notes, "publication-request"); + } + + private static AuthoredDraftPublishSelectionBinding selection( + DraftCommitBinding draft, String notes, String publishRequestId) { + return AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + draft.target().canonicalTenantId(), + draft.target().canonicalVersionId(), + publishRequestId, + "5", + notes, + draft.requestId(), + draft.commitId(), + draft.digest()), + draft.target(), + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + draft.target(), + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java index 110290b1c5..53396c39fb 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/authordraft/DraftAuthorizationFenceWorldParticipationTest.java @@ -148,19 +148,30 @@ void pendingWorldParticipationBlocksSourceMutationAndAbortWhileSettledKeepsPrior } @Test - void disclosureSourceLockPreservesTheExisting512ByteBoundWithoutAliasing() throws Exception { + void disclosureSourceLocksRetainCompleteCanonicalKeysThrough2048Utf8Bytes() throws Exception { Fixture fixture = new Fixture(false); fixture.begin(); - SourceEvidence boundary = source("x".repeat(499)); - assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + SourceEvidence legacy = source("x".repeat(499)); + SourceEvidence longer = source("x".repeat(500)); + SourceEvidence boundary = source("x".repeat(2035)); + SourceEvidence unicodeBoundary = source("😀".repeat(508) + "xxx"); + assertThat(legacy.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(512); + assertThat(longer.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(513); + assertThat(boundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)).hasSize(2048); + assertThat(unicodeBoundary.key().getBytes(java.nio.charset.StandardCharsets.UTF_8)) + .hasSize(2048); - fixture.repository.lockDisclosureSources(List.of(boundary)); + // V76 and the shared SourceEvidence already own this exact byte bound; retain the whole key. + for (var source : List.of(legacy, longer, boundary, unicodeBoundary)) { + fixture.repository.lockDisclosureSources(List.of(source)); + } - assertThat(fixture.lockedKeys).containsExactly(boundary.key()); - assertThatThrownBy( - () -> fixture.repository.lockDisclosureSources(List.of(source("x".repeat(500))))) + assertThat(fixture.lockedKeys) + .containsExactly(legacy.key(), longer.key(), boundary.key(), unicodeBoundary.key()); + assertThat(longer.key()).startsWith(legacy.key()).isNotEqualTo(legacy.key()); + assertThatThrownBy(() -> source("x".repeat(2036))) .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("existing Account source-lock bound"); + .hasMessageContaining("2048 UTF-8 bytes"); } private static SourceChange sourceChange(SourceEvidence source) { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java index b674202308..e9f6ee1030 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/client/StartSessionReservationEvidenceClientTest.java @@ -10,14 +10,17 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; -import io.grpc.ManagedChannel; import io.grpc.Server; +import io.grpc.ServerInterceptors; import io.grpc.Status; import io.grpc.StatusRuntimeException; -import io.grpc.inprocess.InProcessChannelBuilder; -import io.grpc.inprocess.InProcessServerBuilder; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; import io.grpc.stub.StreamObserver; import java.io.InputStream; +import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; @@ -26,23 +29,29 @@ import java.time.ZoneOffset; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; 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.GrpcPeerIdentityInterceptor; import net.firedevops.firemud.common.operator.StartSessionOperatorAction; import net.firedevops.firemud.common.operator.StartSessionPreAuthorizationReservationTuple; +import net.firedevops.firemud.common.security.SessionContext; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceRequest; import net.firedevops.firemud.loggingadmin.v1.ReadCurrentClaimEvidenceResponse; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidencePurpose; import net.firedevops.firemud.loggingadmin.v1.StartSessionReservationEvidenceServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; class StartSessionReservationEvidenceClientTest { private static final long NOW_EPOCH_MILLIS = 1_800_000_000_000L; @@ -59,18 +68,34 @@ class StartSessionReservationEvidenceClientTest { Clock.fixed(Instant.ofEpochMilli(NOW_EPOCH_MILLIS), ZoneOffset.UTC); private static final String LOGGING_ADMIN_TARGET = "logging-admin.internal:6565"; + @TempDir static Path pkiDirectory; + private static AccountStartSessionReservationProofPki pki; + private static CommonGrpcClientProperties accountTls; + + @BeforeAll + static void createControlledPki() throws Exception { + pki = AccountStartSessionReservationProofPki.create(pkiDirectory, "world-runtime"); + accountTls = pki.clientProperties(); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + @Test - void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { + void repeatedMtlsReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); List requests = new ArrayList<>(); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { requests.add(request); assertThat(io.grpc.Context.current().getDeadline()).isNotNull(); return validResponse(request, tuple.mutationDigest()); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse issueFirst = client.readCurrentClaimEvidence( @@ -137,8 +162,8 @@ void repeatedInProcessReadsBindTheExactTupleClaimPurposeAndDeadline() throws Exc void rejectsEveryResponseIdentityFieldUnknownFieldsAndStaleTimes() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference response = new AtomicReference<>(); - try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + try (MtlsFixture fixture = mtlsFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse valid = validResponse( request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), @@ -193,8 +218,8 @@ void acceptsProducerObservationAfterLocalNowWhenClaimRemainsOrderedAndUnexpired( throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference response = new AtomicReference<>(); - try (InProcessFixture fixture = inProcessFixture(request -> response.get())) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + try (MtlsFixture fixture = mtlsFixture(request -> response.get())) { + StartSessionReservationEvidenceClient client = fixture.client(); ReadCurrentClaimEvidenceResponse futureObservation = validResponse( request(tuple, StartSessionReservationEvidenceClient.Purpose.ISSUE), @@ -221,13 +246,13 @@ void acceptsProducerObservationAfterLocalNowWhenClaimRemainsOrderedAndUnexpired( void invalidInputIsRejectedBeforeAnyRpc() throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicInteger calls = new AtomicInteger(); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { calls.incrementAndGet(); return validResponse(request, tuple.mutationDigest()); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); assertThatThrownBy( () -> @@ -278,12 +303,12 @@ void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence throws Exception { StartSessionPreAuthorizationReservationTuple tuple = tuple(); AtomicReference status = new AtomicReference<>(Status.UNAVAILABLE); - try (InProcessFixture fixture = - inProcessFixture( + try (MtlsFixture fixture = + mtlsFixture( request -> { throw status.get().asRuntimeException(); })) { - StartSessionReservationEvidenceClient client = client(fixture.stub()); + StartSessionReservationEvidenceClient client = fixture.client(); assertThatThrownBy( () -> @@ -315,24 +340,14 @@ void propagatesUnavailableAndStaleOwnerStatusesWithoutInterpretingThemAsEvidence } @Test - void usesConfiguredLoggingEndpointTlsChannelAndStubCustomizer(@TempDir Path directory) - throws Exception { + void usesConfiguredLoggingEndpointAndTlsChannel(@TempDir Path directory) throws Exception { ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); endpoints.setLoggingAdminService(LOGGING_ADMIN_TARGET); CommonGrpcClientProperties tls = tlsProperties(directory); GrpcChannelFactory channelFactory = spy(new GrpcChannelFactory()); - AtomicInteger customizerCalls = new AtomicInteger(); - BlockingGrpcStubCustomizer customizer = - new BlockingGrpcStubCustomizer() { - @Override - public > T customize(T stub) { - customizerCalls.incrementAndGet(); - return stub; - } - }; StartSessionReservationEvidenceClient client = new StartSessionReservationEvidenceClient( - endpoints, tls, channelFactory, customizer, CLOCK); + endpoints, tls, channelFactory, "world-runtime", CLOCK); try { client.init(); @@ -340,59 +355,182 @@ public > T customize(T stub) { verify(channelFactory) .buildChannel( eq(LOGGING_ADMIN_TARGET), eq(6565), any(CommonGrpcClientProperties.class), eq(true)); - assertThat(customizerCalls).hasValue(1); } finally { client.close(); } } - private static StartSessionReservationEvidenceClient client( - StartSessionReservationEvidenceServiceGrpc.StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - StartSessionReservationClientTestAccess client = newClient(); - client.installStub(stub); - return client.client(); + @Test + void pinsConfiguredLoggingServerIndependentlyOfMutationTargetNamespace() throws Exception { + var targetTuple = tuple("other-target-runtime"); + try (var fixture = + mtlsFixture(request -> validResponse(request, targetTuple.mutationDigest()))) { + var evidence = + fixture + .client() + .readCurrentClaimEvidence( + targetTuple, + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + assertThat(evidence.getPreAuthorizationTupleJson().toByteArray()) + .containsExactly(targetTuple.canonicalJson().getBytes(StandardCharsets.UTF_8)); + } } - private static StartSessionReservationClientTestAccess newClient() { - ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); - CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); - tls.setPlaintext(true); - StartSessionReservationEvidenceClient client = - new StartSessionReservationEvidenceClient( - endpoints, - tls, - mock(GrpcChannelFactory.class), - BlockingGrpcStubCustomizer.noop(), - CLOCK); - return new StartSessionReservationClientTestAccess(client); + @Test + void rejectsWrongAndMissingAuthenticatedServerIdentityBeforeRequestDelivery() throws Exception { + var calls = new AtomicInteger(); + for (String identity : List.of("wrong-workload", "wrong-namespace", "missing-identity")) { + try (var fixture = + mtlsFixture( + identity, + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple().mutationDigest()); + })) { + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)) + .hasMessageContaining("exact authenticated server workload identity"); + } + } + assertThat(calls).hasValue(0); + } + + @Test + void rejectsAmbientTransactionAndSynchronizationBeforeAnyRpc() throws Exception { + var calls = new AtomicInteger(); + try (var fixture = + mtlsFixture( + request -> { + calls.incrementAndGet(); + return validResponse(request, tuple().mutationDigest()); + })) { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + SessionContext.setContext("caller", List.of(), Map.of()); + assertThatThrownBy(() -> readIssue(fixture.client())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only caller"); + SessionContext.clear(); + assertThat(calls).hasValue(0); + assertThat(readIssue(fixture.client()).getControlPlaneRequestId()).isEqualTo(REQUEST_ID); + assertThat(calls).hasValue(1); + } + } + + @Test + void requiresUsableMutualTlsBeforeAnyTransportUse() throws Exception { + var plaintext = accountTls.copy(); + plaintext.setPlaintext(true); + var missing = accountTls.copy(); + missing.setCertChain(pkiDirectory.resolve("missing-certificate.pem").toString()); + var absentClientKey = accountTls.copy(); + absentClientKey.setPrivateKey(null); + var absentClientCertificate = accountTls.copy(); + absentClientCertificate.setCertChain(null); + for (var tls : List.of(plaintext, missing, absentClientKey, absentClientCertificate)) { + var factory = mock(GrpcChannelFactory.class); + try (var client = + new StartSessionReservationEvidenceClient( + new ServiceEndpointsProperties(), tls, factory, "world-runtime", CLOCK)) { + assertThatThrownBy(() -> readIssue(client)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("mTLS"); + org.mockito.Mockito.verifyNoInteractions(factory); + } + } } - private static InProcessFixture inProcessFixture(EvidenceHandler handler) throws Exception { - String serverName = InProcessServerBuilder.generateName(); + private static ReadCurrentClaimEvidenceResponse readIssue( + StartSessionReservationEvidenceClient client) { + return client.readCurrentClaimEvidence( + tuple(), + RESERVATION_OWNER_ID, + 1L, + RESERVATION_OWNER_ID, + 1L, + StartSessionReservationEvidenceClient.Purpose.ISSUE); + } + + private static MtlsFixture mtlsFixture(EvidenceHandler handler) throws Exception { + return mtlsFixture("logging", handler); + } + + private static MtlsFixture mtlsFixture(String identity, EvidenceHandler handler) + throws Exception { + var serverIdentity = pki.server(identity); Server server = - InProcessServerBuilder.forName(serverName) - .directExecutor() + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) .addService( - new StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceImplBase() { - @Override - public void readCurrentClaimEvidence( - ReadCurrentClaimEvidenceRequest request, - StreamObserver responseObserver) { - try { - responseObserver.onNext(handler.read(request)); - responseObserver.onCompleted(); - } catch (StatusRuntimeException exception) { - responseObserver.onError(exception); - } - } - }) + ServerInterceptors.intercept( + new StartSessionReservationEvidenceServiceGrpc + .StartSessionReservationEvidenceServiceImplBase() { + @Override + public void readCurrentClaimEvidence( + ReadCurrentClaimEvidenceRequest request, + StreamObserver responseObserver) { + assertThat(GrpcPeerIdentity.current().uri()) + .isEqualTo("spiffe://firemud/ns/world-runtime/sa/account-service"); + try { + responseObserver.onNext(handler.read(request)); + responseObserver.onCompleted(); + } catch (StatusRuntimeException exception) { + responseObserver.onError(exception); + } + } + }, + new GrpcPeerIdentityInterceptor(), + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + assertThat( + headers.get( + io.grpc.Metadata.Key.of( + "authorization", io.grpc.Metadata.ASCII_STRING_MARSHALLER))) + .isNull(); + return next.startCall(call, headers); + } + })) .build() .start(); - ManagedChannel channel = InProcessChannelBuilder.forName(serverName).directExecutor().build(); - return new InProcessFixture(server, channel); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setLoggingAdminService("localhost:" + server.getPort()); + var client = + new StartSessionReservationEvidenceClient( + endpoints, accountTls, new GrpcChannelFactory(), "world-runtime", CLOCK); + try { + client.init(); + return new MtlsFixture(server, client); + } catch (Exception failure) { + client.close(); + server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + throw failure; + } } private static ReadCurrentClaimEvidenceRequest request( @@ -440,11 +578,15 @@ private static StartSessionReservationEvidencePurpose toWirePurpose( } private static StartSessionPreAuthorizationReservationTuple tuple() { + return tuple("world-runtime"); + } + + private static StartSessionPreAuthorizationReservationTuple tuple(String targetNamespace) { StartSessionOperatorAction action = new StartSessionOperatorAction( StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_ID, StartSessionOperatorAction.ACTION_FAMILY_SCHEMA_VERSION, - new StartSessionOperatorAction.Scope(TENANT_ID, "world-runtime"), + new StartSessionOperatorAction.Scope(TENANT_ID, targetNamespace), new StartSessionOperatorAction.Target(17L, TARGET_ACCOUNT_ID), StartSessionOperatorAction.ExpectedVersion.ABSENT, new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), @@ -477,30 +619,12 @@ private interface EvidenceHandler { ReadCurrentClaimEvidenceResponse read(ReadCurrentClaimEvidenceRequest request); } - private record InProcessFixture(Server server, ManagedChannel channel) implements AutoCloseable { - private StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub() { - return StartSessionReservationEvidenceServiceGrpc.newBlockingStub(channel); - } - + private record MtlsFixture(Server server, StartSessionReservationEvidenceClient client) + implements AutoCloseable { @Override public void close() throws Exception { - channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); + client.close(); server.shutdownNow().awaitTermination(5, TimeUnit.SECONDS); } } - - private record StartSessionReservationClientTestAccess( - StartSessionReservationEvidenceClient client) { - private void installStub( - StartSessionReservationEvidenceServiceGrpc - .StartSessionReservationEvidenceServiceBlockingStub - stub) - throws Exception { - var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); - field.setAccessible(true); - field.set(client, stub); - } - } } diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java index 196f0f5945..19826e2a31 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountControlUiSigningAndActorTest.java @@ -421,6 +421,13 @@ void owner(String compact) { AccountControlUiAuthority.canonical( Map.ofEntries( Map.entry("kid", "test-only-control"), + Map.entry( + "publicKeyFingerprint", + AccountJwtJwksTrustedSource.publicKeyFingerprint( + new AccountPublicJwksCache.PublicJwksSnapshot(pin, jwks), + pin, + "test-only-control") + .orElseThrow()), Map.entry("environmentId", pin.environmentId()), Map.entry("clusterId", pin.clusterId()), Map.entry("clusterIncarnationUid", pin.clusterIncarnationUid()), diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java new file mode 100644 index 0000000000..0b04160423 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationReadServiceTest.java @@ -0,0 +1,267 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationRequest; +import net.firedevops.firemud.account.v1.ReadHeldPublicationAuthorizationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level owner tests; supplied peer contexts are not actual TLS-positive proof. */ +class AccountPublicationAuthorizationReadServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final PlatformTransactionManager transactions = mock(PlatformTransactionManager.class); + private final TransactionStatus status = mock(TransactionStatus.class); + private final AccountPublicationAuthorizationReadService service = + new AccountPublicationAuthorizationReadService(repository, transactions, "test"); + + @AfterEach + void clear() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void commitsAnIndependentOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "game-design-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + + @Test + void commitsAnIndependentWorldOwnerReadBeforeReturningHeld() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + asPeer("test", "world-management-service", () -> service.requireHeld(request)); + verify(repository).readHeld(any()); + var definition = ArgumentCaptor.forClass(TransactionDefinition.class); + verify(transactions).getTransaction(definition.capture()); + assertThat(definition.getValue().getPropagationBehavior()) + .isEqualTo(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + assertThat(definition.getValue().getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.getValue().isReadOnly()).isFalse(); + verify(transactions).commit(status); + } + + @Test + void rejectsUnverifiedWrongWorkloadCrossNamespaceAndAmbientTransactionBeforeLookup() { + var request = request("test"); + assertCode(Status.Code.UNAUTHENTICATED, () -> service.requireHeld(request)); + for (String workload : + List.of("account-service", "game-session-service", "spring-cloud-gateway")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.requireHeld(request))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.requireHeld(request))); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "world-management-service", () -> service.requireHeld(request))); + SessionContext.setContext("authenticated-player", List.of(), java.util.Map.of()); + for (String workload : List.of("game-design-service", "world-management-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.requireHeld(request))); + } + SessionContext.clear(); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request("other")))); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + verifyNoInteractions(repository, transactions); + } + + @Test + void absentOrChangedOwnerStateCannotProduceHeldAndStorageFailureFailsClosed() { + var request = request("test"); + when(transactions.getTransaction(any())).thenReturn(status); + doThrow(new IllegalArgumentException("absent or changed")).when(repository).readHeld(any()); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + doThrow(new org.jooq.exception.DataAccessException("offline")).when(repository).readHeld(any()); + assertCode( + Status.Code.UNAVAILABLE, + () -> asPeer("test", "game-design-service", () -> service.requireHeld(request))); + } + + @Test + void grpcAuthenticatesBeforeDecodingMalformedCallerCarriers() { + var endpoint = new AccountPublicationAuthorizationReadGrpcService(service, "test"); + var error = new AtomicReference(); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(ReadHeldPublicationAuthorizationResponse value) { + throw new AssertionError("Malformed request cannot return HELD"); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() { + throw new AssertionError("Malformed request cannot complete"); + } + }; + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.UNAUTHENTICATED); + asPeer( + "test", + "account-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "other", + "world-management-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + asPeer( + "test", + "world-management-service", + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()).isEqualTo(Status.Code.INVALID_ARGUMENT); + SessionContext.setContext("authenticated-player", List.of(), java.util.Map.of()); + for (String workload : List.of("game-design-service", "world-management-service")) { + asPeer( + "test", + workload, + () -> + endpoint.readHeldPublicationAuthorization( + ReadHeldPublicationAuthorizationRequest.getDefaultInstance(), observer)); + assertThat(Status.fromThrowable(error.get()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + SessionContext.clear(); + verifyNoInteractions(repository, transactions); + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static void asPeer(String namespace, String workload, Runnable action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer).run(action); + } + + private static AccountPublicationAuthorizationReadEvidence.Request request(String namespace) { + UUID actor = UUID.randomUUID(), + tenant = UUID.randomUUID(), + version = UUID.randomUUID(), + revision = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 17, "test-tenant", 11, "test-tenant", "NEW_GAME_ROW"); + var draft = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", revision, DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "ROOM", + "room", + "ROOM_SCOPE", + "room", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "proof", + draft.requestId(), + draft.commitId(), + draft.digest()), + target, + draft, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + draft.requestId(), + draft.commitId(), + draft.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + return AccountPublicationAuthorizationReadEvidence.Request.create(namespace, binding); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java new file mode 100644 index 0000000000..b272b7e034 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountPublicationAuthorizationServiceTest.java @@ -0,0 +1,43 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AccountPublicationAuthorizationServiceTest { + @Test + void persistenceCannotBeCalledWithoutTheWritableAccountOwnerTransaction() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("Writable READ_COMMITTED"); + verifyNoInteractions(dsl); + } + + @Test + void readOnlyOrDifferentIsolationCannotMintPublicationPermission() { + var dsl = mock(DSLContext.class); + var repository = new AccountPublicationAuthorizationRepository(dsl); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + TransactionSynchronizationManager.setCurrentTransactionReadOnly(true); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setCurrentTransactionReadOnly(false); + TransactionSynchronizationManager.setCurrentTransactionIsolationLevel( + java.sql.Connection.TRANSACTION_REPEATABLE_READ); + assertThatThrownBy(() -> repository.authorize(null, null, () -> {})) + .isInstanceOf(IllegalStateException.class); + verifyNoInteractions(dsl); + } finally { + TransactionSynchronizationManager.clear(); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java new file mode 100644 index 0000000000..937b78fad5 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcMtlsTest.java @@ -0,0 +1,456 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import io.grpc.Server; +import io.grpc.ServerInterceptor; +import io.grpc.ServerInterceptors; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.PrivateKey; +import java.security.cert.X509Certificate; +import java.time.OffsetDateTime; +import java.util.Base64; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderGrpcService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationOrderService; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +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.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.test.TlsTestSupport; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Native loopback mTLS transport proof for the unregistered selected-publication producer. */ +class AccountSelectedDraftPublicationOrderGrpcMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String WRONG_ACCOUNT_URI = + "spiffe://firemud/ns/other-test/sa/account-service"; + private static final String WRONG_SERVER_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String WRONG_CLIENT_URI = + "spiffe://firemud/ns/test/sa/world-management-service"; + private static final String OTHER_NAMESPACE_CLIENT_URI = + "spiffe://firemud/ns/other-test/sa/game-design-service"; + + @TempDir static Path temporaryDirectory; + private static TestPki pki; + + @BeforeAll + static void createTrustedWorkloadCertificates() throws Exception { + pki = TestPki.create(temporaryDirectory); + } + + @Test + void authenticatedGameDesignClientReachesEnvironmentCaptureThenUnresolvedOwner() + throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(server.handlerCalls()).hasValue(1); + var calls = inOrder(terms, owner); + calls.verify(terms).captureCurrentEnvironmentBoundary(); + calls.verify(owner).authorize(eq(CREDENTIAL), any(), same(captured)); + } + } + + @Test + void maximumCreatorCredentialMetadataReachesAuthenticatedOwnerUnchanged() throws Exception { + String credential = "A".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES); + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(credential), any(), same(captured))) + .thenThrow(Status.FAILED_PRECONDITION.asRuntimeException()); + + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request(credential))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + + assertThat(server.handlerCalls()).hasValue(1); + var calls = inOrder(terms, owner); + calls.verify(terms).captureCurrentEnvironmentBoundary(); + calls.verify(owner).authorize(eq(credential), any(), same(captured)); + } + } + + @Test + void trustedWrongServiceAndNamespaceGameDesignCallersAreDeniedBeforeCapture() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceClient(), pki.otherNamespaceClient())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + var client = newClient(server.port(), identity)) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + } + + @Test + void missingClientCertificateFailsTlsBeforeReceiverOrOwner() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithoutIdentity(server.port())) { + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request()); + + assertThatThrownBy(() -> client.authorize(wire)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(TlsTestSupport.isTlsHandshakeRejection(failure)) + .as( + "missing client certificate must fail during TLS negotiation: %s", + failure) + .isTrue()); + + assertThat(server.handlerCalls()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + + @Test + void creatorCredentialMetadataIsRequiredBeforeEnvironmentCapture() throws Exception { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(pki.accountServer(), owner, terms); + ClientTransport client = newClientWithIdentity(server.port(), pki.gameDesignClient())) { + assertThatThrownBy( + () -> client.authorize(AccountSelectedPublicationOrderGrpcCodec.toRequest(request()))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).hasValue(1); + verifyNoInteractions(terms, owner); + } + } + + @Test + void clientRejectsTrustedWrongServiceAndNamespaceAccountServerIdentities() throws Exception { + for (TestIdentity identity : List.of(pki.wrongServiceServer(), pki.otherNamespaceServer())) { + var owner = mock(AccountSelectedDraftPublicationOrderService.class); + var terms = mock(AccountHostedTermsService.class); + try (TransportServer server = startServer(identity, owner, terms); + var client = newClient(server.port(), pki.gameDesignClient())) { + client.init(); + + assertThatThrownBy(() -> client.authorize(request())) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .as(identity.alias()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + assertThat(server.handlerCalls()).as(identity.alias()).hasValue(0); + verifyNoInteractions(terms, owner); + } + } + } + + private static TransportServer startServer( + TestIdentity serverIdentity, + AccountSelectedDraftPublicationOrderService owner, + AccountHostedTermsService terms) + throws Exception { + AtomicInteger handlerCalls = new AtomicInteger(); + ServerInterceptor countHandlerCalls = + new ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + handlerCalls.incrementAndGet(); + return next.startCall(call, headers); + } + }; + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMetadataSize(AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, NAMESPACE), + countHandlerCalls, + new GrpcPeerIdentityInterceptor())) + .build() + .start(); + return new TransportServer(server, handlerCalls); + } + + private static AccountSelectedPublicationOrderClient newClient(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new AccountSelectedPublicationOrderClient( + endpoints, + pki.clientProperties(temporaryDirectory, identity), + new GrpcChannelFactory(), + NAMESPACE); + } + + private static ClientTransport newClientWithoutIdentity(int port) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCaCert(pki.caCertificatePem().toString()); + ManagedChannel channel = + new GrpcChannelFactory().buildChannel("127.0.0.1:" + port, 6565, tls, false); + return new ClientTransport(channel); + } + + private static ClientTransport newClientWithIdentity(int port, TestIdentity identity) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + var channel = + new GrpcChannelFactory() + .buildChannel( + endpoints.getAccountService(), + 6565, + pki.clientProperties(temporaryDirectory, identity), + false); + return new ClientTransport(channel); + } + + private static AccountSelectedPublicationOrderGrpcCodec.Request request() { + return request(CREDENTIAL); + } + + private static AccountSelectedPublicationOrderGrpcCodec.Request request(String credential) { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.Request.create( + NAMESPACE, selection, credential); + } + + private static final String CREDENTIAL = "original.secret.credential"; + + private record TransportServer(Server server, AtomicInteger handlerCalls) + implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback Account gRPC server did not terminate"); + } + } + } + + private record ClientTransport(ManagedChannel channel) implements AutoCloseable { + private void authorize( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest request) { + AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withDeadlineAfter(3, TimeUnit.SECONDS) + .authorizeSelectedPublication(request); + } + + @Override + public void close() throws InterruptedException { + if (!channel.shutdownNow().awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Loopback gRPC client did not terminate"); + } + } + } + + private record TestIdentity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, + Path caCertificatePem, + TestIdentity accountServer, + TestIdentity wrongServiceServer, + TestIdentity otherNamespaceServer, + TestIdentity gameDesignClient, + TestIdentity wrongServiceClient, + TestIdentity otherNamespaceClient) { + private static final String STORE_PASSWORD = "test-only-store-password"; + + private static TestPki create(Path directory) throws Exception { + var authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + directory, + "selected-publication-test-ca.p12", + "selected-publication-test-ca.crt", + "test-ca", + "CN=FireMUD selected publication test CA", + STORE_PASSWORD); + return new TestPki( + authority.certificate(), + authority.certificateFile(), + issueIdentity(directory, authority, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, authority, "wrong-service-server", WRONG_SERVER_URI, true), + issueIdentity(directory, authority, "other-namespace-server", WRONG_ACCOUNT_URI, true), + issueIdentity(directory, authority, "game-design-client", GAME_DESIGN_URI, false), + issueIdentity(directory, authority, "wrong-service-client", WRONG_CLIENT_URI, false), + issueIdentity( + directory, authority, "other-namespace-client", OTHER_NAMESPACE_CLIENT_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory, TestIdentity identity) + throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setCertChain( + writePem( + directory.resolve(identity.alias() + ".client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve(identity.alias() + ".client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()) + .toString()); + tls.setCaCert(caCertificatePem.toString()); + tls.setPlaintext(false); + return tls; + } + + private static TestIdentity issueIdentity( + Path directory, + AccountStartSessionReservationProofPki.TestCertificateAuthority authority, + String alias, + String workloadUri, + boolean server) + throws Exception { + var identity = + AccountStartSessionReservationProofPki.issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + ".crt", + workloadUri, + server, + true, + true) + .identity(); + return new TestIdentity(identity.alias(), identity.privateKey(), identity.certificate()); + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n"); + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java new file mode 100644 index 0000000000..7e8aba8be6 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderGrpcServiceTest.java @@ -0,0 +1,349 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Status; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderCredentials; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Context-level receiver units, not mounted-certificate or real Account currentness proof. */ +class AccountSelectedDraftPublicationOrderGrpcServiceTest { + private static final String CREDENTIAL = "original.secret.credential"; + private final AccountSelectedDraftPublicationOrderService owner = + mock(AccountSelectedDraftPublicationOrderService.class); + private final AccountHostedTermsService terms = mock(AccountHostedTermsService.class); + private final AccountSelectedDraftPublicationOrderGrpcService receiver = + new AccountSelectedDraftPublicationOrderGrpcService(owner, terms, "test"); + + @AfterEach + void clear() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeAndCaptureAndDeniesWorld() { + assertThat(invoke(null).code()).isEqualTo(Status.Code.UNAUTHENTICATED); + for (String workload : + List.of("world-management-service", "account-service", "game-session-service")) { + assertThat(peer("test", workload, () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } + assertThat(peer("other", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized(() -> invoke(AuthorizeSelectedPublicationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void boundInterceptorAuthenticatesBeforeTouchingMalformedCredentialMetadata() { + var headers = mock(io.grpc.Metadata.class); + assertThat(boundCode(headers)).isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "world-management-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(peer("other", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + var malformed = new io.grpc.Metadata(); + malformed.put( + io.grpc.Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + io.grpc.Metadata.BINARY_BYTE_MARSHALLER), + new byte[] {(byte) 128}); + assertThat(peer("test", "game-design-service", () -> boundCode(malformed))) + .isEqualTo(Status.Code.UNAUTHENTICATED); + assertThat(peer("test", "game-design-service", () -> invoke(null)).code()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner, terms); + } + + @Test + void authenticatedCallerContextDeniesBoundCallBeforeReadingCredentialMetadata() { + SessionContext.setContext("test-user", List.of(), java.util.Map.of()); + var headers = mock(io.grpc.Metadata.class); + + assertThat(peer("test", "game-design-service", () -> boundCode(headers))) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(headers, owner, terms); + } + + @Test + void authenticatedCallerContextDeniesDirectCallBeforeMalformedPayloadDecode() { + SessionContext.setContext("test-user", List.of(), java.util.Map.of()); + + assertThat( + peer( + "test", + "game-design-service", + () -> invoke(AuthorizeSelectedPublicationRequest.getDefaultInstance())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner, terms); + } + + @SuppressWarnings("unchecked") + private Status.Code boundCode(io.grpc.Metadata headers) { + var method = + (io.grpc.ServerMethodDefinition< + AuthorizeSelectedPublicationRequest, AuthorizeSelectedPublicationResponse>) + receiver.bindService().getMethods().iterator().next(); + io.grpc.ServerCall + call = mock(io.grpc.ServerCall.class); + method.getServerCallHandler().startCall(call, headers); + var status = org.mockito.ArgumentCaptor.forClass(Status.class); + org.mockito.Mockito.verify(call).close(status.capture(), org.mockito.ArgumentMatchers.any()); + return status.getValue().getCode(); + } + + @Test + void deniesAmbientSqlNamespaceAndUnknownFieldsBeforeCapture() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThat(authorized(() -> invoke(null)).code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + var request = request(); + assertThat( + authorized(() -> invoke(request.toBuilder().setTargetNamespace("other").build())) + .code()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat( + authorized( + () -> + invoke( + request.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, + UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .code()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + verifyNoInteractions(owner, terms); + } + + @Test + void + automaticallyCapturesAccountEnvironmentAndHandsOffOriginalCredentialAndSelectionOutsideSql() { + var request = request(); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(request, CREDENTIAL); + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + UUID actor = UUID.randomUUID(); + var binding = + new AccountPublicationAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + actor, decoded.selection()), + List.of( + new DraftAuthorizationFenceBinding.SourceEvidence( + DraftAuthorizationFenceBinding.SourceKind.ACCOUNT, + actor.toString(), + "1", + "1", + null, + null, + new byte[] {1}))); + when(terms.captureCurrentEnvironmentBoundary()) + .thenAnswer( + call -> { + outsideSql(); + return captured; + }); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenAnswer( + call -> { + outsideSql(); + assertThat( + call.getArgument(1, AuthoredDraftPublishSelectionBinding.class) + .canonicalBytes()) + .isEqualTo(decoded.originalSelection()); + return binding; + }); + var result = authorized(() -> invoke(request)); + assertThat(result.error()).isNull(); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(decoded, result.response()) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + assertThat(result.response().toString()).doesNotContain(CREDENTIAL); + } + + @Test + void unavailableCaptureReturnsSanitizedFailure() { + when(terms.captureCurrentEnvironmentBoundary()) + .thenThrow(new IllegalStateException(CREDENTIAL)); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + verifyNoInteractions(owner); + } + + @Test + void immutableOwnerConflictIsPermanentWhilePendingSourceChangeRemainsRetryable() { + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(new IllegalArgumentException(CREDENTIAL)) + .thenThrow(new IllegalStateException(CREDENTIAL)); + var conflict = authorized(() -> invoke(request())); + assertThat(conflict.code()).isEqualTo(Status.Code.FAILED_PRECONDITION); + assertThat(conflict.error().toString()).doesNotContain(CREDENTIAL); + assertThat(conflict.error().getCause()).isNull(); + + var waiting = authorized(() -> invoke(request())); + assertThat(waiting.code()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(waiting.error().toString()).doesNotContain(CREDENTIAL); + assertThat(waiting.error().getCause()).isNull(); + } + + @Test + void secretBearingOwnerStatusReturnsOnlyItsCodeAndSanitizedDescription() { + var captured = mock(AccountHostedTermsService.CapturedEnvironmentBoundary.class); + when(terms.captureCurrentEnvironmentBoundary()).thenReturn(captured); + when(owner.authorize(eq(CREDENTIAL), any(), same(captured))) + .thenThrow(Status.PERMISSION_DENIED.withDescription(CREDENTIAL).asRuntimeException()); + var denied = authorized(() -> invoke(request())); + assertThat(denied.code()).isEqualTo(Status.Code.PERMISSION_DENIED); + assertThat(denied.error().toString()).doesNotContain(CREDENTIAL); + assertThat(denied.error().getCause()).isNull(); + } + + private record Result(AuthorizeSelectedPublicationResponse response, Throwable error) { + Status.Code code() { + return Status.fromThrowable(error).getCode(); + } + } + + private Result invoke(AuthorizeSelectedPublicationRequest request) { + var response = new AtomicReference(); + var error = new AtomicReference(); + receiver.authorizeSelectedPublication( + request, + new io.grpc.stub.StreamObserver<>() { + @Override + public void onNext(AuthorizeSelectedPublicationResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }); + return new Result(response.get(), error.get()); + } + + private static void outsideSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + AccountSelectedPublicationOrderCredentials.CONTEXT_KEY, + AccountSelectedPublicationOrderCredentials.Credential.of(CREDENTIAL)); + var prior = context.attach(); + try { + return peer("test", "game-design-service", action); + } finally { + context.detach(prior); + } + } + + private static T peer( + String namespace, String workload, java.util.function.Supplier action) { + var context = + io.grpc.Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static AuthorizeSelectedPublicationRequest request() { + UUID tenant = UUID.randomUUID(), version = UUID.randomUUID(); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19, "tenant-key", 42, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-1", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", UUID.randomUUID(), DraftCommitBinding.Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new AuthoredDraftPublishSelectionBinding.PublishIntent( + tenant, + version, + "publication-request", + "5", + "fixture", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new AuthoredDraftPublishSelectionBinding.VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return AccountSelectedPublicationOrderGrpcCodec.toRequest( + AccountSelectedPublicationOrderGrpcCodec.Request.create("test", selected, CREDENTIAL)); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java new file mode 100644 index 0000000000..375ee54ec9 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationOrderServiceTest.java @@ -0,0 +1,292 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.accountservice.hostedterms.AccountHostedTermsService.CapturedEnvironmentBoundary; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition ordering units with stipulated peer context and mocked owner evidence/producer. These + * fixture values are not genuine cross-owner mTLS, creator or PostgreSQL proof. + */ +class AccountSelectedDraftPublicationOrderServiceTest { + private static final String COMPACT_JWT = "original-compact-creator-jwt"; + private final AuthoredDraftPublishSelectionReadClient client = + mock(AuthoredDraftPublishSelectionReadClient.class); + private final AccountPublicationAuthorizationService owner = + mock(AccountPublicationAuthorizationService.class); + private final CapturedEnvironmentBoundary environment = mock(CapturedEnvironmentBoundary.class); + private final AccountSelectedDraftPublicationOrderService service = + new AccountSelectedDraftPublicationOrderService(client, owner, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void deniesMissingWrongServiceAndCrossNamespacePeerBeforeTransportOrOwner() { + // Null lookup also proves authentication precedes carrier inspection. + assertCode(Status.Code.UNAUTHENTICATED, () -> service.authorize(null, null, null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("test", workload, () -> service.authorize(null, null, null))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> asPeer("other", "game-design-service", () -> service.authorize(null, null, null))); + verifyNoInteractions(client, owner); + } + + @Test + void rejectsActualTransactionAndSynchronizationBeforeRemoteRead() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode( + Status.Code.FAILED_PRECONDITION, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + verifyNoInteractions(client, owner); + } + + @Test + void exactReadCompletesBeforeOwnerReceivesUnchangedCreatorJwtEnvironmentAndSelection() { + var lookup = selection(); + var result = mock(AccountPublicationAuthorizationBinding.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + assertThat(request.targetNamespace()).isEqualTo("test"); + assertThat(request.originalSelection()).containsExactly(lookup.canonicalBytes()); + assertThat(request.selectionDigest()).isEqualTo(lookup.digest()); + return fixtureEvidence(request); + }); + when(owner.authorize(eq(COMPACT_JWT), eq(lookup), same(environment))) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return result; + }); + assertThat(authorized(() -> service.authorize(COMPACT_JWT, lookup, environment))) + .isSameAs(result); + var request = ArgumentCaptor.forClass(AuthoredDraftPublishSelectionReadEvidence.Request.class); + var order = inOrder(client, owner); + order.verify(client).read(request.capture()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(lookup), same(environment)); + order.verifyNoMoreInteractions(); + assertThat(request.getValue().binding()).isEqualTo(lookup); + } + + @Test + void missingOrSubstitutedReadbackNeverInvokesAccountOwner() { + when(client.read(any())).thenReturn(null); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class); + for (String changed : List.of("namespace", "readIdentity", "selection")) { + doAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, AuthoredDraftPublishSelectionReadEvidence.Request.class); + if ("selection".equals(changed)) { + var original = request.binding(); + var intent = original.intent(); + var replaced = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + "changed notes", + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + original.target(), + original.selectedCommit(), + new VisibilityFence( + original.target(), + original.fenceRequestId(), + original.fenceCommitId(), + original.fenceInputDigest(), + original.fenceResultVectorJson(), + OffsetDateTime.parse(original.fenceCreatedAt()))); + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + request.readRequestId(), + replaced.canonicalBytes(), + replaced.digest())); + } + return fixtureEvidence( + new AuthoredDraftPublishSelectionReadEvidence.Request( + request.schemaVersion(), + "namespace".equals(changed) ? "other" : request.targetNamespace(), + "readIdentity".equals(changed) + ? UUID.randomUUID() + : request.readRequestId(), + request.originalSelection(), + request.selectionDigest())); + }) + .when(client) + .read(any()); + assertThatThrownBy( + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("differs from the exact publication order request"); + } + verifyNoInteractions(owner); + } + + @Test + void unavailableOrDeniedSelectionReadNeverInvokesOwner() { + for (Status failure : List.of(Status.UNAVAILABLE, Status.NOT_FOUND, Status.PERMISSION_DENIED)) { + doThrow(failure.asRuntimeException()).when(client).read(any()); + assertCode( + failure.getCode(), + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + } + verifyNoInteractions(owner); + } + + @Test + void lowerLevelCreatorDenialPropagatesAfterExactOwnerRead() { + when(client.read(any())).thenAnswer(invocation -> fixtureEvidence(invocation.getArgument(0))); + when(owner.authorize(any(), any(), any())) + .thenThrow(Status.PERMISSION_DENIED.asRuntimeException()); + assertCode( + Status.Code.PERMISSION_DENIED, + () -> authorized(() -> service.authorize(COMPACT_JWT, selection(), environment))); + var order = inOrder(client, owner); + order.verify(client).read(any()); + order.verify(owner).authorize(eq(COMPACT_JWT), eq(selection()), same(environment)); + } + + private static AuthoredDraftPublishSelectionReadEvidence fixtureEvidence( + AuthoredDraftPublishSelectionReadEvidence.Request request) { + var evidence = mock(AuthoredDraftPublishSelectionReadEvidence.class); + when(evidence.request()).thenReturn(request); + return evidence; + } + + private static T authorized(Supplier action) { + return asPeer("test", "game-design-service", action); + } + + private static T asPeer(String namespace, String workload, Supplier action) { + var peer = + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow(); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code expected, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static AuthoredDraftPublishSelectionBinding selection() { + UUID tenant = uuid("22222222-2222-4222-8222-222222222222"); + UUID version = uuid("33333333-3333-4333-8333-333333333333"); + var target = + new DraftCommitBinding.TargetProof( + tenant, version, 19L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + var commit = + DraftCommitBinding.create( + target, + uuid("44444444-4444-4444-8444-444444444444"), + uuid("55555555-5555-4555-8555-555555555555"), + "base-1", + List.of( + new RevisionPayload( + "0", + uuid("66666666-6666-4666-8666-666666666666"), + Owner.WORLD_MANAGEMENT, + "{}")), + List.of( + new AffectedUnit( + Owner.WORLD_MANAGEMENT, + "WORLD_TEMPLATE", + "world-1", + "ROOM_SCOPE", + "room-1", + "0"))); + var selected = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + tenant, + version, + "publication-request", + "5", + "test selection", + commit.requestId(), + commit.commitId(), + commit.digest()), + target, + commit, + new VisibilityFence( + target, + commit.requestId(), + commit.commitId(), + commit.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + return selected; + } + + private static UUID uuid(String value) { + return UUID.fromString(value); + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java new file mode 100644 index 0000000000..bb106f9ad1 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedDraftPublicationSettlementServiceTest.java @@ -0,0 +1,403 @@ +package net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.AbstractPlatformTransactionManager; +import org.springframework.transaction.support.DefaultTransactionStatus; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Composition seams only: canonical codec outputs, owner results and peer identity are stipulated + * here. Actual PostgreSQL, codec integrity and mounted-certificate mTLS are separate proof. + */ +class AccountSelectedDraftPublicationSettlementServiceTest { + private final AccountPublicationAuthorizationRepository repository = + mock(AccountPublicationAuthorizationRepository.class); + private final GameDesignPublicationTerminalClient gameDesign = + mock(GameDesignPublicationTerminalClient.class); + private final WorldPublicationTerminalReadClient world = + mock(WorldPublicationTerminalReadClient.class); + private final OwnerTransactions transactions = new OwnerTransactions(); + private final AccountSelectedDraftPublicationSettlementService service = + new AccountSelectedDraftPublicationSettlementService( + repository, gameDesign, world, transactions, "test"); + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesBeforeMalformedDecodeOrOwnerReads() { + assertCode(Status.Code.UNAUTHENTICATED, () -> service.settle(null)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("test", workload, () -> service.settle(new byte[] {0}))); + } + assertCode( + Status.Code.PERMISSION_DENIED, + () -> peer("other", "game-design-service", () -> service.settle(null))); + assertThatThrownBy(() -> authorized(() -> service.settle(new byte[] {0}))) + .isInstanceOf(RuntimeException.class); + verifyNoInteractions(repository, gameDesign, world); + assertThat(transactions.begins).isZero(); + } + + @Test + void deniesAmbientTransactionAndSynchronizationBeforeDecode() { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, () -> authorized(() -> service.settle(null))); + verifyNoInteractions(repository, gameDesign, world); + } + + @Test + void agreeingOwnersCommitThenSeparatelyReadBackAndRetriesUseFreshReadCorrelations() { + for (var outcome : GameDesignPublicationTerminalEvidence.Outcome.values()) { + try (var fixture = new CodecOutputs(outcome)) { + var gameDesignReads = new ArrayList(); + var worldReads = new ArrayList(); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + gameDesignReads.add(request.readRequestId()); + return gameDesignEvidence(request, fixture.terminal); + }) + .when(gameDesign) + .read(any()); + doAnswer( + call -> { + assertNoSql(); + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + worldReads.add(request.readRequestId()); + return worldEvidence(request, fixture.terminal, request.expectedWorldOutcome()); + }) + .when(world) + .read(any()); + var calls = new AtomicInteger(); + int priorCommits = transactions.commits; + byte[] receipt = new byte[] {9, 8}; + doAnswer( + call -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()) + .isTrue(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isTrue(); + assertThat(TransactionSynchronizationManager.isCurrentTransactionReadOnly()) + .isFalse(); + assertThat( + TransactionSynchronizationManager.getCurrentTransactionIsolationLevel()) + .isEqualTo(java.sql.Connection.TRANSACTION_READ_COMMITTED); + assertThat(transactions.commits - priorCommits) + .isEqualTo(calls.getAndIncrement()); + assertThat(call.getArgument(0, GameDesignPublicationOperationBinding.class)) + .isSameAs(fixture.operation); + assertThat(call.getArgument(1, GameDesignPublicationTerminalEvidence.class)) + .isSameAs(fixture.terminal); + assertThat(call.getArgument(2, String.class)).isEqualTo(fixture.phase.name()); + assertThat(call.getArgument(3, byte[].class)) + .containsExactly(fixture.terminalBytes); + return receipt.clone(); + }) + .when(repository) + .settle(any(), any(), anyString(), any()); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(authorized(() -> service.settle(fixture.operationBytes))) + .containsExactly(receipt); + assertThat(calls).hasValue(4); + assertThat(transactions.commits - priorCommits).isEqualTo(4); + assertThat(gameDesignReads).hasSize(2).doesNotHaveDuplicates(); + assertThat(worldReads).hasSize(2).doesNotHaveDuplicates(); + assertNoSql(); + } + } + } + + @Test + void missingSubstitutedOrUnavailableGameDesignResultNeverReadsWorldOrWritesAccount() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())).thenReturn(null); + assertFailure(fixture); + doAnswer( + call -> { + var request = + call.getArgument( + 0, GameDesignPublicationTerminalReadEvidence.ReadRequest.class); + return gameDesignEvidence( + new GameDesignPublicationTerminalReadEvidence.ReadRequest( + 1, "test", UUID.randomUUID(), request.operationBytes()), + fixture.terminal); + }) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + var substituted = mock(GameDesignPublicationTerminalEvidence.class); + when(substituted.canonicalBytes()).thenReturn(new byte[] {99}); + doAnswer(call -> gameDesignEvidence(call.getArgument(0), substituted)) + .when(gameDesign) + .read(any()); + assertFailure(fixture); + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(gameDesign).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(world, repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void + worldNamespaceMismatchMissingChangedRequestTerminalPhaseAndUnavailableKeepAccountUntouched() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(fixture.worldRequest.targetNamespace()).thenReturn("other"); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(gameDesign, world, repository); + when(fixture.worldRequest.targetNamespace()).thenReturn("test"); + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + for (String changed : + List.of("missing", "correlation", "namespace", "phase", "terminal", "operation")) { + doAnswer( + call -> { + var request = + call.getArgument(0, WorldPublicationTerminalReadEvidence.Request.class); + if (changed.equals("missing")) return null; + var response = worldEvidence(request, fixture.terminal, fixture.phase); + if (changed.equals("correlation") || changed.equals("namespace")) { + // Mock the returned request itself to exercise a substituted owner echo without + // treating a structurally invalid carrier as a genuine codec result. + when(response.request()) + .thenReturn(mock(WorldPublicationTerminalReadEvidence.Request.class)); + } + if (changed.equals("phase")) + when(response.worldOutcome()) + .thenReturn(WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED); + if (changed.equals("terminal")) + when(response.worldTerminalEvidence()).thenReturn(new byte[] {99}); + if (changed.equals("operation")) { + var other = mock(GameDesignPublicationTerminalEvidence.class); + when(other.operationBytes()).thenReturn(new byte[] {99}); + when(response.terminalEvidence()).thenReturn(other); + } + return response; + }) + .when(world) + .read(any()); + assertFailure(fixture); + } + doThrow(Status.UNAVAILABLE.asRuntimeException()).when(world).read(any()); + assertCode( + Status.Code.UNAVAILABLE, () -> authorized(() -> service.settle(fixture.operationBytes))); + verifyNoInteractions(repository); + assertThat(transactions.begins).isZero(); + } + } + + @Test + void changedPostCommitReadbackCannotReturnSuccess() { + try (var fixture = + new CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome.NO_PUBLICATION)) { + when(gameDesign.read(any())) + .thenAnswer(call -> gameDesignEvidence(call.getArgument(0), fixture.terminal)); + when(world.read(any())) + .thenAnswer(call -> worldEvidence(call.getArgument(0), fixture.terminal, fixture.phase)); + when(repository.settle(any(), any(), anyString(), any())) + .thenReturn(new byte[] {1}, new byte[] {2}); + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("readback differs"); + assertThat(transactions.commits).isEqualTo(2); + assertNoSql(); + } + } + + private void assertFailure(CodecOutputs fixture) { + assertThatThrownBy(() -> authorized(() -> service.settle(fixture.operationBytes))) + .isInstanceOf(RuntimeException.class); + } + + private static GameDesignPublicationTerminalReadEvidence.ReadResult gameDesignEvidence( + GameDesignPublicationTerminalReadEvidence.ReadRequest request, + GameDesignPublicationTerminalEvidence terminal) { + var result = mock(GameDesignPublicationTerminalReadEvidence.ReadResult.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(java.util.Optional.ofNullable(terminal)); + return result; + } + + private static WorldPublicationTerminalReadEvidence worldEvidence( + WorldPublicationTerminalReadEvidence.Request request, + GameDesignPublicationTerminalEvidence terminal, + WorldPublicationTerminalReadEvidence.WorldOutcome phase) { + byte[] terminalBytes = terminal.canonicalBytes(); + var result = mock(WorldPublicationTerminalReadEvidence.class); + when(result.request()).thenReturn(request); + when(result.terminalEvidence()).thenReturn(terminal); + when(result.worldTerminalEvidence()).thenReturn(terminalBytes); + when(result.worldOutcome()).thenReturn(phase); + return result; + } + + private static void assertNoSql() { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + } + + private static T authorized(Supplier action) { + return peer("test", "game-design-service", action); + } + + private static T peer(String namespace, String workload, Supplier action) { + var context = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + GrpcPeerIdentity.parseUri("spiffe://firemud/ns/" + namespace + "/sa/" + workload) + .orElseThrow()); + var prior = context.attach(); + try { + return action.get(); + } finally { + context.detach(prior); + } + } + + private static void assertCode(Status.Code code, Runnable action) { + assertThatThrownBy(action::run) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies(failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(code)); + } + + private static final class CodecOutputs implements AutoCloseable { + final byte[] operationBytes = new byte[] {11}; + final byte[] terminalBytes = new byte[] {22}; + final GameDesignPublicationOperationBinding operation = + mock(GameDesignPublicationOperationBinding.class); + final GameDesignPublicationTerminalEvidence terminal = + mock(GameDesignPublicationTerminalEvidence.class); + final WorldPublishedStartLocationEvidence.Request worldRequest = + mock(WorldPublishedStartLocationEvidence.Request.class); + final WorldPublicationTerminalReadEvidence.WorldOutcome phase; + final org.mockito.MockedStatic operations = + mockStatic(GameDesignPublicationOperationBinding.class); + final org.mockito.MockedStatic terminals = + mockStatic(GameDesignPublicationTerminalEvidence.class); + + CodecOutputs(GameDesignPublicationTerminalEvidence.Outcome outcome) { + var world = mock(WorldPublishedStartLocationEvidence.class); + // Stipulated codec outputs include identities required by the current read correlation. + var account = + mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + .class); + var input = + mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + .PreallocationInput.class); + var selection = + mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.class); + var intent = + mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding + .PublishIntent.class); + when(operation.account()).thenReturn(account); + when(account.operationId()).thenReturn(UUID.randomUUID()); + when(account.fenceId()).thenReturn(UUID.randomUUID()); + when(account.input()).thenReturn(input); + when(input.selection()).thenReturn(selection); + when(selection.intent()).thenReturn(intent); + when(intent.selectedCommitRequestId()).thenReturn(UUID.randomUUID()); + when(intent.selectedCommitId()).thenReturn(UUID.randomUUID()); + when(operation.canonicalBytes()).thenReturn(operationBytes); + when(operation.world()).thenReturn(world); + when(world.request()).thenReturn(worldRequest); + when(worldRequest.targetNamespace()).thenReturn("test"); + when(terminal.canonicalBytes()).thenReturn(terminalBytes); + when(terminal.operationBytes()).thenReturn(operationBytes); + when(terminal.worldEvidence()).thenReturn(world); + when(terminal.outcome()).thenReturn(outcome); + operations + .when(() -> GameDesignPublicationOperationBinding.fromStored(operationBytes)) + .thenReturn(operation); + terminals + .when(() -> GameDesignPublicationTerminalEvidence.fromStored(terminalBytes)) + .thenReturn(terminal); + phase = + outcome == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? WorldPublicationTerminalReadEvidence.WorldOutcome.PUBLISHED + : WorldPublicationTerminalReadEvidence.WorldOutcome.ABORTED; + } + + @Override + public void close() { + terminals.close(); + operations.close(); + } + } + + private static final class OwnerTransactions extends AbstractPlatformTransactionManager { + private static final long serialVersionUID = 1L; + int begins; + int commits; + + @Override + protected Object doGetTransaction() { + return new Object(); + } + + @Override + protected void doBegin(Object transaction, TransactionDefinition definition) { + assertThat(definition.getIsolationLevel()) + .isEqualTo(TransactionDefinition.ISOLATION_READ_COMMITTED); + assertThat(definition.isReadOnly()).isFalse(); + begins++; + } + + @Override + protected void doCommit(DefaultTransactionStatus status) { + commits++; + } + + @Override + protected void doRollback(DefaultTransactionStatus status) {} + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java new file mode 100644 index 0000000000..285cca35ad --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountSelectedPublicationSettlementGrpcServiceTest.java @@ -0,0 +1,142 @@ +package unit.net.firedevops.firemud.accountservice.service.session; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import com.google.protobuf.UnknownFieldSet; +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedDraftPublicationSettlementService; +import net.firedevops.firemud.accountservice.service.session.AccountSelectedPublicationSettlementGrpcService; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Receiver identity/ordering units; synthetic peer context is not authenticated TLS proof. */ +class AccountSelectedPublicationSettlementGrpcServiceTest { + private static final String NAMESPACE = "publication-runtime"; + private static final String GAME_DESIGN_URI = + "spiffe://firemud/ns/publication-runtime/sa/game-design-service"; + + @AfterEach + void clearThreadState() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatesExactGameDesignBeforeMalformedRequestOrOwnerAccess() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var malformed = SettleSelectedPublicationRequest.getDefaultInstance(); + + assertCode(Status.Code.UNAUTHENTICATED, invoke(receiver, null, malformed)); + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/other-runtime/sa/game-design-service"), + malformed)); + for (String workload : + List.of("account-service", "world-management-service", "game-session-service")) { + assertCode( + Status.Code.PERMISSION_DENIED, + invoke( + receiver, + identity("spiffe://firemud/ns/publication-runtime/sa/" + workload), + malformed)); + } + SessionContext.setContext("test-user", List.of(), Map.of()); + assertCode( + Status.Code.PERMISSION_DENIED, invoke(receiver, identity(GAME_DESIGN_URI), malformed)); + verifyNoInteractions(owner); + } + + @Test + void deniesAmbientSqlAndClosedEnvelopeErrorsBeforeOwnerCall() { + var owner = mock(AccountSelectedDraftPublicationSettlementService.class); + var receiver = new AccountSelectedPublicationSettlementGrpcService(owner, NAMESPACE); + var peer = identity(GAME_DESIGN_URI); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertCode(Status.Code.FAILED_PRECONDITION, invoke(receiver, peer, null)); + TransactionSynchronizationManager.clearSynchronization(); + + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, null)); + var unknown = + SettleSelectedPublicationRequest.newBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1L).build()) + .build()) + .build(); + assertCode(Status.Code.INVALID_ARGUMENT, invoke(receiver, peer, unknown)); + verifyNoInteractions(owner); + } + + private static Invocation invoke( + AccountSelectedPublicationSettlementGrpcService receiver, + GrpcPeerIdentity peer, + SettleSelectedPublicationRequest request) { + var result = new Invocation(); + Context context = Context.current(); + if (peer != null) context = context.withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + receiver.settleSelectedPublication(request, result); + } finally { + context.detach(previous); + } + return result; + } + + private static GrpcPeerIdentity identity(String uri) { + return GrpcPeerIdentity.parseUri(uri).orElseThrow(); + } + + private static void assertCode(Status.Code expected, Invocation invocation) { + assertThat(invocation.error).isNotNull(); + assertThat(invocation.error.statusRuntimeException()).isTrue(); + assertThat(invocation.error.code()).isEqualTo(expected); + assertThat(invocation.response).isNull(); + assertThat(invocation.completed).isFalse(); + } + + private record ObservedError(boolean statusRuntimeException, Status.Code code) {} + + private static final class Invocation + implements StreamObserver { + private SettleSelectedPublicationResponse response; + private ObservedError error; + private boolean completed; + + @Override + public void onNext(SettleSelectedPublicationResponse value) { + response = value; + } + + @Override + public void onError(Throwable failure) { + error = + new ObservedError( + failure instanceof StatusRuntimeException, Status.fromThrowable(failure).getCode()); + } + + @Override + public void onCompleted() { + completed = true; + } + } +} diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java index a1cca68f6d..f721291564 100644 --- a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/service/session/AccountStartSessionWorldParticipationSettlementGrpcMtlsTest.java @@ -25,11 +25,8 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; -import java.security.KeyStore; import java.security.PrivateKey; -import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; -import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; @@ -40,6 +37,7 @@ import net.firedevops.firemud.account.v1.SettleOriginalStartSessionWorldParticipationRequest; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementGrpcService; import net.firedevops.firemud.accountservice.service.session.AccountStartSessionWorldParticipationSettlementService; +import net.firedevops.firemud.accountservice.testsupport.AccountStartSessionReservationProofPki; import net.firedevops.firemud.common.account.startsession.AccountStartSessionWorldParticipationSettlementInput; import net.firedevops.firemud.common.account.startsession.GrpcAccountStartSessionWorldParticipationSettlementClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; @@ -292,67 +290,32 @@ private record TestPki( "spiffe://firemud/ns/world-runtime/sa/world-management-service"; private static TestPki create(Path directory) throws Exception { - Path caStore = directory.resolve("world-participation-settlement-test-ca.p12"); - runKeytool( - "-genkeypair", - "-alias", - "world-participation-settlement-ca", - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=FireMUD controlled World participation settlement test CA", - "-validity", - "30", - "-ext", - "BC=ca:true", - "-ext", - "KU=keyCertSign,cRLSign", - "-storetype", - "PKCS12", - "-keystore", - caStore.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - Path caFile = directory.resolve("world-participation-settlement-test-ca.crt"); - runKeytool( - "-exportcert", - "-alias", - "world-participation-settlement-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-rfc"); - X509Certificate ca = readCertificate(caFile); + var authority = + AccountStartSessionReservationProofPki.createCertificateAuthority( + directory, + "world-participation-settlement-test-ca.p12", + "world-participation-settlement-test-ca.crt", + "world-participation-settlement-ca", + "CN=FireMUD controlled World participation settlement test CA", + STORE_PASSWORD); return new TestPki( - ca, + authority.certificate(), issueIdentity( directory, - caStore, - caFile, + authority, "account-server", "spiffe://firemud/ns/world-runtime/sa/account-service", true), - issueIdentity(directory, caStore, caFile, "world-client", WORLD_URI, false), + issueIdentity(directory, authority, "world-client", WORLD_URI, false), issueIdentity( directory, - caStore, - caFile, + authority, "wrong-service-client", "spiffe://firemud/ns/world-runtime/sa/game-session-service", false), issueIdentity( directory, - caStore, - caFile, + authority, "other-namespace-client", "spiffe://firemud/ns/other-runtime/sa/world-management-service", false)); @@ -386,140 +349,26 @@ private Path caCertificatePem(Path directory) throws Exception { } private static TestIdentity issueIdentity( - Path directory, Path caStore, Path caFile, String alias, String workloadUri, boolean server) + Path directory, + AccountStartSessionReservationProofPki.TestCertificateAuthority authority, + String alias, + String workloadUri, + boolean server) throws Exception { - Path store = directory.resolve(alias + ".p12"); - Path request = directory.resolve(alias + ".csr"); - Path certificate = directory.resolve(alias + "-signed.crt"); - String san = "URI:" + workloadUri + (server ? ",DNS:localhost,IP:127.0.0.1" : ""); - String usage = server ? "serverAuth" : "clientAuth"; - runKeytool( - "-genkeypair", - "-alias", - alias, - "-keyalg", - "RSA", - "-keysize", - "2048", - "-dname", - "CN=" + alias, - "-validity", - "30", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + usage, - "-ext", - "SAN=" + san, - "-storetype", - "PKCS12", - "-keystore", - store.toString(), - "-storepass", - STORE_PASSWORD, - "-keypass", - STORE_PASSWORD); - runKeytool( - "-certreq", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - request.toString(), - "-ext", - "SAN=" + san); - runKeytool( - "-gencert", - "-alias", - "world-participation-settlement-ca", - "-keystore", - caStore.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-infile", - request.toString(), - "-outfile", - certificate.toString(), - "-validity", - "30", - "-rfc", - "-ext", - "BC=ca:false", - "-ext", - "KU=digitalSignature,keyEncipherment", - "-ext", - "EKU=" + usage, - "-ext", - "SAN=" + san); - runKeytool( - "-importcert", - "-alias", - "world-participation-settlement-ca", - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - caFile.toString(), - "-noprompt"); - runKeytool( - "-importcert", - "-alias", - alias, - "-keystore", - store.toString(), - "-storetype", - "PKCS12", - "-storepass", - STORE_PASSWORD, - "-file", - certificate.toString(), - "-noprompt"); - KeyStore keyStore = KeyStore.getInstance("PKCS12"); - try (var input = Files.newInputStream(store)) { - keyStore.load(input, STORE_PASSWORD.toCharArray()); - } - return new TestIdentity( - alias, - (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), - (X509Certificate) keyStore.getCertificate(alias)); - } - - private static void runKeytool(String... arguments) throws Exception { - Path keytool = - Path.of( - System.getProperty("java.home"), - "bin", - System.getProperty("os.name").toLowerCase().contains("windows") - ? "keytool.exe" - : "keytool"); - var command = new ArrayList(); - command.add(keytool.toString()); - command.addAll(List.of(arguments)); - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - String output; - try (var stream = process.getInputStream()) { - output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); - } - if (!process.waitFor(30, TimeUnit.SECONDS) || process.exitValue() != 0) { - process.destroyForcibly(); - throw new IllegalStateException("test keytool failed: " + output); - } - } - - private static X509Certificate readCertificate(Path path) throws Exception { - try (var input = Files.newInputStream(path)) { - return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); - } + var identity = + AccountStartSessionReservationProofPki.issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + "-signed.crt", + workloadUri, + server, + false, + true) + .identity(); + return new TestIdentity(identity.alias(), identity.privateKey(), identity.certificate()); } private static Path writePem(Path path, String label, byte[] bytes) throws IOException { diff --git a/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java new file mode 100644 index 0000000000..e738bd42f4 --- /dev/null +++ b/services/account-service/src/test/java/unit/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPkiTest.java @@ -0,0 +1,85 @@ +package net.firedevops.firemud.accountservice.testsupport; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; + +/** Actual stalled JDK children exercise only this fixture's process deadline and cleanup. */ +class AccountStartSessionReservationProofPkiTest { + @TempDir Path directory; + + @Test + @Timeout(15) + void timeoutTerminatesAndReapsTheStalledChild() throws Exception { + Process process = awaitingPassword(); + try { + assertThatThrownBy( + () -> + AccountStartSessionReservationProofPki.awaitKeytoolExit( + process, 1, TimeUnit.SECONDS)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("execution deadline"); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + cleanup(process); + } + } + + @Test + @Timeout(15) + void interruptionTerminatesAndReapsTheChildAndRestoresTheInterruptFlag() throws Exception { + Process process = awaitingPassword(); + try { + Thread.currentThread().interrupt(); + assertThatThrownBy( + () -> + AccountStartSessionReservationProofPki.awaitKeytoolExit( + process, 30, TimeUnit.SECONDS)) + .isInstanceOf(InterruptedException.class); + assertThat(Thread.currentThread().isInterrupted()).isTrue(); + Thread.interrupted(); + assertThat(process.isAlive()).isFalse(); + assertThat(process.exitValue()).isNotZero(); + } finally { + Thread.interrupted(); + cleanup(process); + } + } + + private Process awaitingPassword() throws Exception { + var keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(java.util.Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + return new ProcessBuilder( + keytool.toString(), + "-genkeypair", + "-alias", + "controlled-timeout", + "-keyalg", + "RSA", + "-keystore", + directory.resolve("pending-password.p12").toString(), + "-storetype", + "PKCS12") + .redirectErrorStream(true) + .start(); + } + + private static void cleanup(Process process) throws Exception { + if (process.isAlive()) process.destroyForcibly(); + assertThat(process.waitFor(5, TimeUnit.SECONDS)).isTrue(); + process.getOutputStream().close(); + process.getInputStream().close(); + process.getErrorStream().close(); + } +} diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java index d7f60deb97..4fab00ca13 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOriginalOrderFixture.java @@ -36,6 +36,8 @@ public final class AccountControlUiOriginalOrderFixture implements AutoCloseable { private final AccountControlUiOwnerSourcesFixture f; private final AccountControlUiActorService actors; + final AccountJwtJwksTrustedSource publicSource; + final AccountControlUiSignerFixture signerFixture; private final AccountControlUiIssuanceService issuance; private final AccountControlUiCoordination coordination; private final RedisClient accountClient; @@ -145,7 +147,8 @@ public AccountControlUiOriginalOrderFixture( f = new AccountControlUiOwnerSourcesFixture( jdbcUrl, username, password, temporary, false, gameDesignTenant, migrationTarget); - var lifecycle = new AccountControlUiSignerFixture(f, temporary, serviceClock); + signerFixture = new AccountControlUiSignerFixture(f, temporary, serviceClock); + var lifecycle = signerFixture; lifecycle.commit(); var originalSigner = f.tx(lifecycle.signer::captureCurrent); assertThat(f.tx(() -> lifecycle.signer.requireOriginal(originalSigner.receipt())).receipt()) @@ -206,9 +209,14 @@ public AccountControlUiOriginalOrderFixture( new AcknowledgementRequirements(1, 1, 5000), testCatalog()); var operations = new AccountControlUiIssuanceRepository(f.dsl); - var publicSource = - new AccountJwtJwksTrustedSource( - lifecycle.client, lifecycle.trust, lifecycle.desired, lifecycle.publication, f.manager); + publicSource = + org.mockito.Mockito.spy( + new AccountJwtJwksTrustedSource( + lifecycle.client, + lifecycle.trust, + lifecycle.desired, + lifecycle.publication, + f.manager)); actors = new AccountControlUiActorService( operations, diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java index 94bcb6acc7..0e668aa749 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiOwnerSourcesFixture.java @@ -138,9 +138,10 @@ final class AccountControlUiOwnerSourcesFixture { && !"160.1".equals(migrationTarget) && !"1006".equals(migrationTarget) && !"1007".equals(migrationTarget) - && !"1009".equals(migrationTarget)) { + && !"1009".equals(migrationTarget) + && !"1010".equals(migrationTarget)) { throw new IllegalArgumentException( - "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, or 1009 selected-owner predecessor is supported"); + "Only the preserved 160.1 source-retention, 1006 parent, 1007 preliminary source-read, 1009 selected-owner predecessor, or 1010 selected-publication closure predecessor is supported"); } this.tenant = Objects.requireNonNull(tenant); String schema = "control_ui_owner_" + UUID.randomUUID().toString().replace("-", ""); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java index b0961a0ca1..a7b4c0613d 100644 --- a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/service/session/AccountControlUiSignerFixture.java @@ -486,7 +486,7 @@ public void onCompleted() { return java.util.Objects.requireNonNull(result.get()); } - private record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} + record PublicJwk(String json, String jsonWithoutKeyOps, String fingerprint) {} private Instant now() { return Instant.ofEpochSecond(clock.instant().getEpochSecond()); @@ -527,7 +527,7 @@ private static String privateBundleJson( return JSON.writeValueAsString(bundle); } - private static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { + static PublicJwk publicJwk(String kid, RSAPublicKey key) throws Exception { String modulus = encodeUnsigned(key.getModulus()); String exponent = encodeUnsigned(key.getPublicExponent()); Map jwk = new LinkedHashMap<>(); diff --git a/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java new file mode 100644 index 0000000000..4a82b6ae81 --- /dev/null +++ b/services/account-service/src/testFixtures/java/net/firedevops/firemud/accountservice/testsupport/AccountStartSessionReservationProofPki.java @@ -0,0 +1,408 @@ +package net.firedevops.firemud.accountservice.testsupport; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; + +/** Controlled loopback PKI for the original Logging claim-read client; no production authority. */ +public final class AccountStartSessionReservationProofPki { + private static final String PASSWORD = "test-only-reservation-pki-password"; + private final Path directory; + private final X509Certificate ca; + private final Map servers; + private final Identity account; + + private AccountStartSessionReservationProofPki( + Path directory, X509Certificate ca, Map servers, Identity account) { + this.directory = directory; + this.ca = ca; + this.servers = servers; + this.account = account; + } + + /** Creates one controlled CA using the caller's established fixture names and password. */ + public static TestCertificateAuthority createCertificateAuthority( + Path directory, + String storeFileName, + String certificateFileName, + String alias, + String distinguishedName, + String password) + throws Exception { + Files.createDirectories(directory); + Path caStore = directory.resolve(storeFileName); + Path caFile = directory.resolve(certificateFileName); + runKeytool( + directory, + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + distinguishedName, + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + password, + "-keypass", + password); + runKeytool( + directory, + "-exportcert", + "-alias", + alias, + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + caFile.toString(), + "-rfc"); + return new TestCertificateAuthority(alias, caStore, caFile, readCertificate(caFile), password); + } + + /** Issues one controlled workload identity while retaining caller-specific SAN and store form. */ + public static IssuedIdentity issueIdentity( + Path directory, + TestCertificateAuthority authority, + String alias, + String storeFileName, + String requestFileName, + String certificateFileName, + String workloadUri, + boolean server, + boolean addLoopbackSansForClients, + boolean importCertificateChainIntoStore) + throws Exception { + String password = authority.storePassword(); + Path store = directory.resolve(storeFileName); + Path request = directory.resolve(requestFileName); + Path certificateFile = directory.resolve(certificateFileName); + String san = + "URI:" + + workloadUri + + (server || addLoopbackSansForClients ? ",DNS:localhost,IP:127.0.0.1" : ""); + String usage = server ? "serverAuth" : "clientAuth"; + runKeytool( + directory, + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + password, + "-keypass", + password); + runKeytool( + directory, + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + directory, + "-gencert", + "-alias", + authority.alias(), + "-keystore", + authority.keyStore().toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-infile", + request.toString(), + "-outfile", + certificateFile.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san); + if (importCertificateChainIntoStore) { + runKeytool( + directory, + "-importcert", + "-alias", + authority.alias(), + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + authority.certificateFile().toString(), + "-noprompt"); + runKeytool( + directory, + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + password, + "-file", + certificateFile.toString(), + "-noprompt"); + } + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, password.toCharArray()); + } + X509Certificate certificate = + importCertificateChainIntoStore + ? (X509Certificate) keyStore.getCertificate(alias) + : readCertificate(certificateFile); + Identity identity = + new Identity( + alias, (PrivateKey) keyStore.getKey(alias, password.toCharArray()), certificate); + return new IssuedIdentity(identity, certificateFile); + } + + public static AccountStartSessionReservationProofPki create(Path directory, String namespace) + throws Exception { + TestCertificateAuthority authority = + createCertificateAuthority( + directory, + "reservation-test-ca.p12", + "reservation-test-ca.crt", + "reservation-test-ca", + "CN=Controlled Logging claim-read test CA", + PASSWORD); + Map servers = + Map.of( + "logging", + issue( + directory, + authority, + "logging-server", + "spiffe://firemud/ns/" + namespace + "/sa/logging-admin-service", + true), + "wrong-workload", + issue( + directory, + authority, + "wrong-workload-server", + "spiffe://firemud/ns/" + namespace + "/sa/game-session-service", + true), + "missing-identity", + issue( + directory, + authority, + "missing-identity-server", + "https://localhost/controlled-test", + true), + "wrong-namespace", + issue( + directory, + authority, + "wrong-namespace-server", + "spiffe://firemud/ns/other-runtime/sa/logging-admin-service", + true)); + Identity account = + issue( + directory, + authority, + "account-client", + "spiffe://firemud/ns/" + namespace + "/sa/account-service", + false); + return new AccountStartSessionReservationProofPki( + directory, authority.certificate(), servers, account); + } + + public Identity accountIdentity() { + return account; + } + + public X509Certificate caCertificate() { + return ca; + } + + public Identity server(String name) { + return java.util.Objects.requireNonNull(servers.get(name)); + } + + public CommonGrpcClientProperties clientProperties() throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + writePem( + directory.resolve("account-client.crt"), + "CERTIFICATE", + account.certificate().getEncoded()) + .toString()); + tls.setPrivateKey( + writePem( + directory.resolve("account-client.key"), + "PRIVATE KEY", + account.privateKey().getEncoded()) + .toString()); + tls.setCaCert( + writePem(directory.resolve("account-client-trust.crt"), "CERTIFICATE", ca.getEncoded()) + .toString()); + return tls; + } + + private static Identity issue( + Path directory, TestCertificateAuthority authority, String alias, String uri, boolean server) + throws Exception { + return issueIdentity( + directory, + authority, + alias, + alias + ".p12", + alias + ".csr", + alias + "-signed.crt", + uri, + server, + false, + true) + .identity(); + } + + public static void runKeytool(Path directory, String... args) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows") + ? "keytool.exe" + : "keytool"); + ArrayList command = new ArrayList<>(); + command.add(keytool.toString()); + command.addAll(List.of(args)); + Path output = Files.createTempFile(directory, "keytool-output-", ".log"); + try { + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(output.toFile()) + .start(); + awaitKeytoolExit(process, 30, TimeUnit.SECONDS); + if (process.exitValue() != 0) { + throw new IllegalStateException("test keytool failed: " + Files.readString(output)); + } + } finally { + Files.deleteIfExists(output); + } + } + + /** Waits before reading child output, then terminates and reaps on timeout or interruption. */ + static void awaitKeytoolExit(Process process, long timeout, TimeUnit unit) + throws InterruptedException { + try { + if (!process.waitFor(timeout, unit)) { + throw new IllegalStateException("test keytool exceeded its execution deadline"); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + throw interrupted; + } finally { + boolean restoreInterrupt = Thread.interrupted(); + try { + if (process.isAlive()) process.destroyForcibly(); + long cleanupDeadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + boolean reaped = false; + while (!reaped) { + long remaining = cleanupDeadline - System.nanoTime(); + if (remaining <= 0) { + throw new IllegalStateException("test keytool could not be reaped after termination"); + } + try { + reaped = process.waitFor(remaining, TimeUnit.NANOSECONDS); + } catch (InterruptedException interrupted) { + restoreInterrupt = true; + } + } + } finally { + if (restoreInterrupt) Thread.currentThread().interrupt(); + } + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + + public record Identity(String alias, PrivateKey privateKey, X509Certificate certificate) {} + + public record TestCertificateAuthority( + String alias, + Path keyStore, + Path certificateFile, + X509Certificate certificate, + String storePassword) {} + + public record IssuedIdentity(Identity identity, Path certificateFile) {} +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java index a562ded108..5dcd5122b9 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/gamedesign/GameDesignPublicationTerminalClient.java @@ -2,8 +2,6 @@ import io.grpc.ManagedChannel; import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Objects; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLException; @@ -24,8 +22,6 @@ public final class GameDesignPublicationTerminalClient private static final long CALL_DEADLINE_SECONDS = 5L; private final String workloadNamespace; - private volatile boolean initialized; - private volatile boolean closed; public GameDesignPublicationTerminalClient( ServiceEndpointsProperties endpoints, @@ -34,7 +30,7 @@ public GameDesignPublicationTerminalClient( String workloadNamespace) { super( endpoints, - requireFileBackedMtls(tlsProperties), + requireFileBackedMtls(tlsProperties, "Game Design publication terminal read"), channelFactory, GameDesignPublicationTerminalClient.class); if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { @@ -44,18 +40,10 @@ public GameDesignPublicationTerminalClient( } /** Initializes only when the owning Account or World service explicitly starts this client. */ - public synchronized void init() throws SSLException, IOException { - if (closed) { - throw new IllegalStateException("Game Design publication terminal client is closed"); - } - if (initialized) { - return; - } - initReloadingClient(); - if (stub() == null) { - throw new IllegalStateException("Game Design publication terminal client has no gRPC stub"); - } - initialized = true; + public void init() throws SSLException, IOException { + initOnce( + "Game Design publication terminal client is closed", + "Game Design publication terminal client has no gRPC stub"); } /** @@ -64,13 +52,15 @@ public synchronized void init() throws SSLException, IOException { */ public GameDesignPublicationTerminalReadEvidence.ReadResult read( GameDesignPublicationTerminalReadEvidence.ReadRequest request) { + requireNoAmbientSql("Game Design publication terminal read requires no owner transaction"); Objects.requireNonNull(request, "request"); if (!workloadNamespace.equals(request.targetNamespace())) { throw new IllegalArgumentException( "Game Design publication terminal request must use the configured workload namespace"); } var response = - requireStub() + requireInitializedStub( + "Game Design publication terminal client is not initialized and available") .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) .readGameDesignPublicationTerminal( GameDesignPublicationTerminalReadGrpcCodec.toRequest(request)); @@ -102,58 +92,4 @@ protected String defaultTarget() { .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) .withCompression("gzip"); } - - @Override - public synchronized void close() throws IOException { - closed = true; - initialized = false; - super.close(); - } - - private GameDesignPublicationTerminalReadServiceGrpc - .GameDesignPublicationTerminalReadServiceBlockingStub - requireStub() { - var currentStub = stub(); - if (closed || !initialized || currentStub == null) { - throw new IllegalStateException( - "Game Design publication terminal client is not initialized and available"); - } - return currentStub; - } - - private static CommonGrpcClientProperties requireFileBackedMtls( - CommonGrpcClientProperties tlsProperties) { - if (tlsProperties == null || tlsProperties.isPlaintext()) { - throw new IllegalArgumentException( - "Game Design publication terminal read requires workload mTLS"); - } - requireReadableFile(tlsProperties.getCertChain(), "certificate chain"); - requireReadableFile(tlsProperties.getPrivateKey(), "private key"); - requireReadableFile(tlsProperties.getCaCert(), "CA certificate"); - return tlsProperties; - } - - private static void requireReadableFile(String configuredPath, String label) { - if (configuredPath == null || configuredPath.isBlank()) { - throw new IllegalArgumentException( - "Game Design publication terminal read requires file-backed certificate, key, and CA material"); - } - String pathText = configuredPath.trim(); - if (pathText.startsWith("classpath:")) { - throw new IllegalArgumentException( - "Game Design publication terminal read requires file-backed certificate, key, and CA material"); - } - Path path; - try { - path = Path.of(pathText); - } catch (RuntimeException invalid) { - throw new IllegalArgumentException( - "Game Design publication terminal read " + label + " must be a readable file-backed path", - invalid); - } - if (!Files.isRegularFile(path) || !Files.isReadable(path)) { - throw new IllegalArgumentException( - "Game Design publication terminal read " + label + " must be an existing readable file"); - } - } } diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java index 4e2f8cd6a6..8840f13cee 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/grpc/AbstractReloadingBlockingGrpcClient.java @@ -3,6 +3,7 @@ import io.grpc.ManagedChannel; import io.grpc.stub.AbstractStub; import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import javax.net.ssl.SSLException; @@ -53,6 +54,46 @@ protected static final void requireNoAmbientSql(String message) { } } + protected static final CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties, String errorContext) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException(errorContext + " requires workload mTLS"); + } + for (String configuredPath : + new String[] { + tlsProperties.getCertChain(), tlsProperties.getPrivateKey(), tlsProperties.getCaCert() + }) { + if (configuredPath == null || configuredPath.isBlank()) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + String pathText = configuredPath; + if (pathText.startsWith("classpath:")) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + Path path; + try { + path = Path.of(pathText); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + boolean readable; + try { + readable = Files.isRegularFile(path) && Files.isReadable(path); + } catch (RuntimeException inaccessible) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + if (!readable) { + throw new IllegalArgumentException( + errorContext + " requires readable file-backed TLS material"); + } + } + return tlsProperties; + } + protected final void initReloadingClient() throws SSLException, IOException { if (tlsProps.isPlaintext() || !GrpcTlsReloadPolicy.isEnabled()) { reloadChannel(); diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java new file mode 100644 index 0000000000..31707e6059 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClient.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CompositeCallCredentials; +import io.grpc.ManagedChannel; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Strict explicit mTLS client; never registers or enables the Account producer. */ +public final class AccountSelectedPublicationOrderClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub> { + // Covers the nested Game Design selection read plus Account authorization and persistence. + private static final long CALL_DEADLINE_SECONDS = 30L; + + private final String namespace; + + public AccountSelectedPublicationOrderClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory, + String namespace) { + super( + endpoints, + requireFileBackedMtls(tls, "Account selected-publication"), + factory, + AccountSelectedPublicationOrderClient.class); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) + throw new IllegalArgumentException("Canonical Account namespace required"); + this.namespace = namespace; + } + + public void init() throws SSLException, IOException { + initOnce( + "Account selected-publication client is closed", + "Account selected-publication stub unavailable"); + } + + public AccountPublicationAuthorizationBinding authorize( + AccountSelectedPublicationOrderGrpcCodec.Request request) { + requireNoAmbientSql("Account selected-publication transport requires no owner transaction"); + Objects.requireNonNull(request); + if (!namespace.equals(request.targetNamespace())) + throw new IllegalArgumentException("Account selected-publication namespace mismatch"); + var current = requireInitializedStub("Account selected-publication client unavailable"); + try { + var response = + current + .withCallCredentials( + new CompositeCallCredentials( + new GrpcServerPeerIdentityCallCredentials( + "spiffe://firemud/ns/" + namespace + "/sa/account-service"), + AccountSelectedPublicationOrderCredentials.forCall( + request.originalCreatorCredential()))) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .authorizeSelectedPublication( + AccountSelectedPublicationOrderGrpcCodec.toRequest(request)); + return AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException unavailable) { + // Remote diagnostics are not trusted to exclude credential-bearing request data. + throw Status.fromCode(unavailable.getStatus().getCode()) + .withDescription("Account selected-publication order denied or unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Account returned invalid selected-publication order evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub + buildStub(ManagedChannel channel) { + String peer = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return AccountSelectedPublicationOrderServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(peer)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(peer)) + .withCompression("gzip") + .withMaxInboundMessageSize( + AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java new file mode 100644 index 0000000000..a62175efec --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentials.java @@ -0,0 +1,113 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.CallCredentials; +import io.grpc.Context; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import io.grpc.Status; +import java.nio.charset.StandardCharsets; +import java.util.concurrent.Executor; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; + +/** + * Purpose-specific protected metadata for the original creator credential. Never log metadata: + * metadata's wire serialization necessarily contains the secret, unlike this redacted wrapper. The + * receiver must authenticate its workload peer before reading or decoding this header. + */ +public final class AccountSelectedPublicationOrderCredentials { + public static final Context.Key CONTEXT_KEY = + Context.key("account-selected-publication-original-creator"); + public static final Metadata.Key HEADER = + Metadata.Key.of( + "firemud-selected-publication-creator-bin", + new Metadata.BinaryMarshaller<>() { + @Override + public byte[] toBytes(Credential value) { + return value.bytes.clone(); + } + + // Parsing deliberately defers all credential validation until after workload + // authentication. + @Override + public Credential parseBytes(byte[] serialized) { + return new Credential(serialized); + } + }); + + private AccountSelectedPublicationOrderCredentials() {} + + public static final class Credential { + private final byte[] bytes; + + private Credential(byte[] bytes) { + this.bytes = bytes.clone(); + } + + public static Credential of(String value) { + if (value == null + || value.isEmpty() + || value.length() > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES + || value.chars().anyMatch(c -> c <= 32 || c >= 127)) throw invalid(); + return new Credential(value.getBytes(StandardCharsets.US_ASCII)); + } + + public String value() { + if (bytes.length == 0 + || bytes.length > AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES) + throw invalid(); + for (byte value : bytes) if (value <= 32 || value >= 127) throw invalid(); + return new String(bytes, StandardCharsets.US_ASCII); + } + + @Override + public String toString() { + return "SelectedPublicationCredential[redacted]"; + } + } + + /** Only after authenticating the exact same-namespace Game Design peer. */ + public static Credential readAuthenticated(Metadata headers) { + var values = headers.getAll(HEADER); + if (values == null) throw invalid(); + var iterator = values.iterator(); + if (!iterator.hasNext()) throw invalid(); + Credential credential = iterator.next(); + if (iterator.hasNext()) throw invalid(); + credential.value(); + return credential; + } + + public static CallCredentials forCall(String value) { + var credential = Credential.of(value); + return new CallCredentials() { + @Override + public void applyRequestMetadata( + RequestInfo info, Executor executor, MetadataApplier applier) { + if (info.getSecurityLevel() != SecurityLevel.PRIVACY_AND_INTEGRITY + || !AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .getFullMethodName() + .equals(info.getMethodDescriptor().getFullMethodName())) { + applier.fail( + Status.UNAUTHENTICATED.withDescription( + "Protected selected-publication transport required")); + return; + } + var headers = new Metadata(); + headers.put(HEADER, credential); + applier.apply(headers); + } + + @Override + public void thisUsesUnstableApi() {} + + @Override + public String toString() { + return "SelectedPublicationCallCredentials[redacted]"; + } + }; + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication credential metadata"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java new file mode 100644 index 0000000000..ceeb056bb0 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodec.java @@ -0,0 +1,161 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed producer transport. Credential data never appears in responses or diagnostics. */ +public final class AccountSelectedPublicationOrderGrpcCodec { + public static final int MAX_CREDENTIAL_BYTES = 16384; + // Protected binary metadata uses base64 on the gRPC wire plus bounded metadata overhead. + public static final int MAX_METADATA_BYTES = ((MAX_CREDENTIAL_BYTES + 2) / 3) * 4 + 1024; + public static final int MAX_SELECTION_BYTES = 1048576; + public static final int MAX_BINDING_BYTES = + AccountPublicationAuthorizationReadEvidence.MAX_BINDING_BYTES; + public static final int MAX_RESPONSE_MESSAGE_BYTES = + MAX_SELECTION_BYTES + MAX_BINDING_BYTES + 1024; + + private AccountSelectedPublicationOrderGrpcCodec() {} + + public record Request( + int schemaVersion, + String targetNamespace, + UUID requestId, + byte[] originalSelection, + String originalCreatorCredential) { + public Request { + if (schemaVersion != 1 + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || requestId == null + || requestId.equals(new UUID(0, 0))) { + throw invalid(); + } + if (originalSelection == null + || originalSelection.length == 0 + || originalSelection.length > MAX_SELECTION_BYTES + || originalCreatorCredential == null + || originalCreatorCredential.isEmpty() + || originalCreatorCredential.length() > MAX_CREDENTIAL_BYTES + || originalCreatorCredential.chars().anyMatch(c -> c <= 32 || c >= 127)) { + throw invalid(); + } + originalSelection = originalSelection.clone(); + var selection = decodeSelection(originalSelection); + if (!Arrays.equals(originalSelection, selection.canonicalBytes())) throw invalid(); + } + + public static Request create( + String namespace, AuthoredDraftPublishSelectionBinding selection, String credential) { + return new Request(1, namespace, UUID.randomUUID(), selection.canonicalBytes(), credential); + } + + @Override + public byte[] originalSelection() { + return originalSelection.clone(); + } + + public AuthoredDraftPublishSelectionBinding selection() { + return decodeSelection(originalSelection); + } + + @Override + public String toString() { + return "AccountSelectedPublicationOrder.Request[redacted]"; + } + } + + public static AuthorizeSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request); + return AuthorizeSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .build(); + } + + /** Invoke only after authenticating the exact same-namespace Game Design workload. */ + public static Request fromRequest(AuthorizeSelectedPublicationRequest wire, String credential) { + try { + noUnknown(wire); + UUID id = UUID.fromString(wire.getRequestId()); + if (!id.toString().equals(wire.getRequestId())) throw invalid(); + return new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + id, + wire.getOriginalSelection().toByteArray(), + credential); + } catch (RuntimeException malformed) { + // Do not retain a parsing cause that could contain credential-bearing request data. + throw invalid(); + } + } + + public static AuthorizeSelectedPublicationResponse toResponse( + Request request, AccountPublicationAuthorizationBinding binding) { + if (binding == null) throw invalid(); + byte[] bindingBytes = binding.canonicalBytes(); + if (bindingBytes.length == 0 || bindingBytes.length > MAX_BINDING_BYTES) throw invalid(); + requireSelection(request, binding); + return AuthorizeSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setPublicationAuthorizationBinding(ByteString.copyFrom(bindingBytes)) + .build(); + } + + public static AccountPublicationAuthorizationBinding fromResponse( + Request request, AuthorizeSelectedPublicationResponse wire) { + try { + noUnknown(wire); + if (wire.getSerializedSize() > MAX_RESPONSE_MESSAGE_BYTES) throw invalid(); + var bindingBytes = wire.getPublicationAuthorizationBinding(); + if (bindingBytes.isEmpty() || bindingBytes.size() > MAX_BINDING_BYTES) throw invalid(); + if (wire.getSchemaVersion() != request.schemaVersion() + || !wire.getTargetNamespace().equals(request.targetNamespace()) + || !wire.getRequestId().equals(request.requestId().toString()) + || !Arrays.equals(wire.getOriginalSelection().toByteArray(), request.originalSelection())) + throw invalid(); + var binding = AccountPublicationAuthorizationBinding.fromStored(bindingBytes.toByteArray()); + requireSelection(request, binding); + return binding; + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void requireSelection( + Request request, AccountPublicationAuthorizationBinding binding) { + if (binding == null + || !Arrays.equals( + request.originalSelection(), binding.input().selection().canonicalBytes())) + throw invalid(); + } + + private static AuthoredDraftPublishSelectionBinding decodeSelection(byte[] bytes) { + try { + return AuthoredDraftPublishSelectionBinding.fromStored( + new String(bytes, StandardCharsets.UTF_8), DraftAuthorizationFenceBinding.digest(bytes)); + } catch (RuntimeException malformed) { + throw invalid(); + } + } + + private static void noUnknown(Message wire) { + if (wire == null || !wire.getUnknownFields().asMap().isEmpty()) throw invalid(); + } + + private static IllegalArgumentException invalid() { + return new IllegalArgumentException("Invalid selected-publication order transport evidence"); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java new file mode 100644 index 0000000000..bc3ce66fd5 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClient.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.common.publication; + +import io.grpc.ManagedChannel; +import java.io.IOException; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLException; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; + +/** Explicit file-backed mTLS client for Account-owned selected-publication settlement. */ +public final class AccountSelectedPublicationSettlementClient + extends AbstractReloadingBlockingGrpcClient< + AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub> { + // Covers both bounded owner reads plus Account persistence, receipt construction, and readback. + private static final long CALL_DEADLINE_SECONDS = 30L; + + private final String workloadNamespace; + + public AccountSelectedPublicationSettlementClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + requireFileBackedMtls(tlsProperties, "Account publication settlement"), + channelFactory, + AccountSelectedPublicationSettlementClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + } + + public void init() throws SSLException, IOException { + initOnce( + "Account publication settlement client is closed", + "Account publication settlement stub unavailable"); + } + + /** Returns the exact original six-frame receipt after Account peer and receipt validation. */ + public byte[] settle(AccountSelectedPublicationSettlementGrpcCodec.Request request) { + requireNoAmbientSql("Account publication settlement requires no owner transaction"); + Objects.requireNonNull(request, "request"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Account publication settlement must use the configured workload namespace"); + } + var response = + requireInitializedStub( + "Account publication settlement client is not initialized and available") + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .settleSelectedPublication( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + try { + return AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response); + } catch (IllegalArgumentException invalid) { + throw new IllegalStateException( + "Account returned an invalid publication settlement receipt", invalid); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAccountService(); + } + + @Override + protected String defaultTarget() { + return "account-service:6565"; + } + + @Override + protected AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = "spiffe://firemud/ns/" + workloadNamespace + "/sa/account-service"; + return AccountSelectedPublicationSettlementServiceGrpc.newBlockingStub(channel) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip") + .withMaxInboundMessageSize(AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java new file mode 100644 index 0000000000..22085d2767 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodec.java @@ -0,0 +1,246 @@ +package net.firedevops.firemud.common.publication; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.io.ByteArrayOutputStream; +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; + +/** Closed Account-owned selected-publication settlement transport and receipt validation. */ +public final class AccountSelectedPublicationSettlementGrpcCodec { + /** Shared per-message protobuf budget; oversized complete six-frame receipts fail closed. */ + public static final int MAX_MESSAGE_BYTES = 32 * 1024 * 1024; + + private static final int MESSAGE_ENVELOPE_OVERHEAD_RESERVE = 256; + private static final String RECEIPT_SCHEMA = "account-selected-publication-settlement/v1"; + + private AccountSelectedPublicationSettlementGrpcCodec() {} + + public static SettleSelectedPublicationRequest toRequest(Request request) { + Objects.requireNonNull(request, "request"); + var wire = + SettleSelectedPublicationRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .build(); + requireWireBudget(wire); + return wire; + } + + /** Receiver authenticates the exact Game Design peer before decoding this request. */ + public static Request fromRequest(SettleSelectedPublicationRequest request) { + Objects.requireNonNull(request, "request"); + requireWireBudget(request); + noUnknownFields(request); + try { + return new Request( + request.getSchemaVersion(), + request.getTargetNamespace(), + canonicalUuid(request.getRequestId()), + request.getOriginalOperation().toByteArray()); + } catch (IllegalArgumentException malformed) { + throw new IllegalArgumentException( + "Account publication settlement request is invalid", malformed); + } + } + + /** Emits only an exact original receipt whose six canonical frames agree with the request. */ + public static SettleSelectedPublicationResponse toResponse(Request request, byte[] receipt) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(receipt, "receipt"); + if ((long) receipt.length + request.originalOperation().length + > MAX_MESSAGE_BYTES - MESSAGE_ENVELOPE_OVERHEAD_RESERVE) { + throw new IllegalArgumentException( + "Account publication settlement response exceeds the 32 MiB wire budget"); + } + var response = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(receipt)) + .build(); + requireWireBudget(response); + validateReceipt(request, receipt); + return response; + } + + /** Verifies the full echo and returns the exact canonical Account settlement receipt. */ + public static byte[] fromResponse(Request request, SettleSelectedPublicationResponse response) { + Objects.requireNonNull(request, "request"); + Objects.requireNonNull(response, "response"); + requireWireBudget(response); + noUnknownFields(response); + if (response.getSchemaVersion() != request.schemaVersion() + || !request.targetNamespace().equals(response.getTargetNamespace()) + || !request.requestId().toString().equals(response.getRequestId()) + || !Arrays.equals( + request.originalOperation(), response.getOriginalOperation().toByteArray())) { + throw new IllegalArgumentException( + "Account changed the exact publication settlement request"); + } + byte[] receipt = response.getSettlementReceipt().toByteArray(); + validateReceipt(request, receipt); + return receipt.clone(); + } + + private static void validateReceipt(Request request, byte[] receipt) { + if (receipt == null || receipt.length == 0 || receipt.length > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Complete bounded Account publication settlement receipt required"); + } + final byte[] accountBinding; + final byte[] originalOperation; + final byte[] gameDesignTerminalBytes; + final String worldOutcome; + final byte[] worldTerminalBytes; + try { + var reader = new DraftAuthorizationFenceBinding.FrameReader(receipt); + reader.expect(RECEIPT_SCHEMA); + accountBinding = reader.bytes(); + originalOperation = reader.bytes(); + gameDesignTerminalBytes = reader.bytes(); + worldOutcome = reader.text(); + worldTerminalBytes = reader.bytes(); + reader.requireEnd(); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Canonical six-frame Account publication settlement receipt required", malformed); + } + + GameDesignPublicationOperationBinding operation; + GameDesignPublicationTerminalEvidence terminal; + try { + operation = GameDesignPublicationOperationBinding.fromStored(request.originalOperation()); + terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalBytes); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Account receipt lacks complete canonical publication evidence", malformed); + } + String expectedWorldOutcome = + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"; + if (!Arrays.equals(accountBinding, operation.account().canonicalBytes()) + || !Arrays.equals(originalOperation, request.originalOperation()) + || !Arrays.equals(terminal.operationBytes(), originalOperation) + || !Arrays.equals(gameDesignTerminalBytes, terminal.canonicalBytes()) + || !Arrays.equals(worldTerminalBytes, gameDesignTerminalBytes) + || !expectedWorldOutcome.equals(worldOutcome)) { + throw new IllegalArgumentException( + "Account settlement receipt differs from the exact operation, terminal, or World outcome"); + } + + var canonical = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(canonical, RECEIPT_SCHEMA); + DraftAuthorizationFenceBinding.frame(canonical, accountBinding); + DraftAuthorizationFenceBinding.frame(canonical, originalOperation); + DraftAuthorizationFenceBinding.frame(canonical, gameDesignTerminalBytes); + DraftAuthorizationFenceBinding.frame(canonical, worldOutcome); + DraftAuthorizationFenceBinding.frame(canonical, worldTerminalBytes); + if (!Arrays.equals(receipt, canonical.toByteArray())) { + throw new IllegalArgumentException("Noncanonical Account publication settlement receipt"); + } + } + + private static void requireWireBudget(Message message) { + if (message.getSerializedSize() > MAX_MESSAGE_BYTES) { + throw new IllegalArgumentException( + "Account publication settlement exceeds the 32 MiB wire budget"); + } + } + + private static void noUnknownFields(Message message) { + if (!message.getUnknownFields().asMap().isEmpty()) { + throw new IllegalArgumentException("Account publication settlement has unsupported fields"); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Canonical non-nil request UUID required"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException("Canonical non-nil request UUID required", malformed); + } + } + + /** Request correlation is fresh per transport call and is not the retained settlement key. */ + public record Request( + int schemaVersion, String targetNamespace, UUID requestId, byte[] originalOperation) { + public static final int SCHEMA_VERSION = 1; + + public Request { + if (schemaVersion != SCHEMA_VERSION) { + throw new IllegalArgumentException("Unsupported Account publication settlement schema"); + } + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace)) { + throw new IllegalArgumentException("Canonical Account workload namespace required"); + } + if (requestId == null || requestId.equals(new UUID(0L, 0L))) { + throw new IllegalArgumentException("Non-nil canonical request identity required"); + } + if (originalOperation == null || originalOperation.length == 0) { + throw new IllegalArgumentException("Complete original publication operation required"); + } + if (originalOperation.length > GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES) { + throw new IllegalArgumentException("Original publication operation exceeds 4 MiB"); + } + originalOperation = originalOperation.clone(); + GameDesignPublicationOperationBinding operation; + try { + // Shared decoding preserves historical v1; this current wire requires complete v2 input. + new DraftAuthorizationFenceBinding.FrameReader(originalOperation) + .expect(GameDesignPublicationOperationBinding.SCHEMA); + operation = GameDesignPublicationOperationBinding.fromStored(originalOperation); + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + "Complete canonical original publication operation required", malformed); + } + if (!Arrays.equals(originalOperation, operation.canonicalBytes())) { + throw new IllegalArgumentException( + "Exact canonical original publication operation required"); + } + if (!targetNamespace.equals(operation.world().request().targetNamespace())) { + throw new IllegalArgumentException( + "Original publication operation differs from the Account workload namespace"); + } + } + + public static Request create(String targetNamespace, byte[] originalOperation) { + return new Request(SCHEMA_VERSION, targetNamespace, UUID.randomUUID(), originalOperation); + } + + @Override + public byte[] originalOperation() { + return originalOperation.clone(); + } + + @Override + public boolean equals(Object other) { + return other instanceof Request that + && schemaVersion == that.schemaVersion + && targetNamespace.equals(that.targetNamespace) + && requestId.equals(that.requestId) + && Arrays.equals(originalOperation, that.originalOperation); + } + + @Override + public int hashCode() { + return 31 * Objects.hash(schemaVersion, targetNamespace, requestId) + + Arrays.hashCode(originalOperation); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java index 8e799ce14c..71872ef675 100644 --- a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodec.java @@ -5,6 +5,7 @@ import java.util.Arrays; import java.util.Objects; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; @@ -184,6 +185,9 @@ public record Request( gameDesignTerminalEvidence = gameDesignTerminalEvidence.clone(); GameDesignPublicationTerminalEvidence terminal; try { + // Historical decoding must not widen this complete-v2 completion transport. + new DraftAuthorizationFenceBinding.FrameReader(originalOperation) + .expect(GameDesignPublicationOperationBinding.SCHEMA); terminal = GameDesignPublicationTerminalEvidence.fromStored(gameDesignTerminalEvidence); } catch (RuntimeException malformed) { throw new IllegalArgumentException( diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java index c90ecfe7f7..05e70d8051 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeClientLifecycleTest.java @@ -26,11 +26,17 @@ import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; import net.firedevops.firemud.common.config.ServiceEndpointsProperties; import net.firedevops.firemud.common.entity.sourceintake.GrpcEntitySelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; import net.firedevops.firemud.common.gamedesign.GrpcSelectedOwnerIntakeSourceClient; import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; import net.firedevops.firemud.common.grpc.GrpcChannelFactory; import net.firedevops.firemud.common.grpc.TlsCertificateWatcher; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationSettlementClient; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient; +import net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient; import net.firedevops.firemud.common.publication.WorldSelectedOwnerInventoryGrpcClient; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; @@ -181,7 +187,13 @@ private enum ClientKind { ENTITY_TERMINAL, AUTOMATION_TERMINAL, GAME_DESIGN_SOURCE, - WORLD_INVENTORY; + WORLD_INVENTORY, + GAME_DESIGN_PUBLICATION_TERMINAL, + ACCOUNT_PUBLICATION_SETTLEMENT, + ACCOUNT_PUBLICATION_HELD_READ, + ACCOUNT_PUBLICATION_ORDER, + GAME_DESIGN_PUBLICATION_SELECTION, + WORLD_PUBLICATION_TERMINAL; ClientHandle create( ServiceEndpointsProperties endpoints, @@ -222,6 +234,32 @@ ClientHandle create( var client = new WorldSelectedOwnerInventoryGrpcClient(endpoints, tls, factory, "test"); yield new ClientHandle(client, client::init); } + case GAME_DESIGN_PUBLICATION_TERMINAL -> { + var client = new GameDesignPublicationTerminalClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_SETTLEMENT -> { + var client = + new AccountSelectedPublicationSettlementClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_HELD_READ -> { + var client = + new AccountPublicationAuthorizationReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case ACCOUNT_PUBLICATION_ORDER -> { + var client = new AccountSelectedPublicationOrderClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case GAME_DESIGN_PUBLICATION_SELECTION -> { + var client = new AuthoredDraftPublishSelectionReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case WORLD_PUBLICATION_TERMINAL -> { + var client = new WorldPublicationTerminalReadClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } }; } } diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java new file mode 100644 index 0000000000..eb8beecde7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/AssetSourceTest.java @@ -0,0 +1,270 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +class AssetSourceTest { + private static final UUID TENANT = UUID.randomUUID(); + private static final UUID VERSION = UUID.randomUUID(); + + @Test + void extractionPreservesExactBindingOrderAndExplicitRequiredness() { + var binding = + binding( + AssetSource.upsertPayload( + "9223372036854775807", " Logo.png ", AssetSource.Requiredness.REQUIRED), + "{\"revisionKind\":\"COMMAND_DEFINITION\"}", + "{\"revisionKind\":\"REALM_ENTRY_POLICY\"}", + AssetSource.upsertPayload("2", "required.png", AssetSource.Requiredness.REQUIRED)); + var mutations = AssetSource.mutations(binding); + + assertThat(mutations).hasSize(2); + assertThat(mutations).extracting(AssetSource.Mutation::revisionOrder).containsExactly("0", "3"); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThat(mutations.getFirst().revisionId()) + .isEqualTo(binding.revisions().getFirst().revisionId()); + assertThat(mutations.getFirst().usageKey()).isEqualTo(" Logo.png "); + assertThat(mutations.getFirst().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getLast().requiredness()).isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(mutations.getFirst().binding()).isSameAs(binding); + assertThatThrownBy(() -> mutations.clear()).isInstanceOf(UnsupportedOperationException.class); + } + + @Test + void replayReplacesOnlyExplicitKeysAndRetainsExactSourceProvenance() { + var original = + binding( + AssetSource.upsertPayload("1", "one.png", AssetSource.Requiredness.REQUIRED), + AssetSource.upsertPayload("2", "two.png", AssetSource.Requiredness.REQUIRED)); + var baseline = AssetSource.replay(List.of(), original); + var changed = + binding( + AssetSource.deletePayload("one.png"), + AssetSource.upsertPayload("3", "one.png", AssetSource.Requiredness.REQUIRED)); + var result = AssetSource.replay(baseline.references(), changed); + + assertThat(result.binding()).isSameAs(changed); + assertThat(result.references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png", "two.png"); + assertThat(result.references().getFirst().assetRowId()).isEqualTo("3"); + assertThat(result.references().getFirst().requiredness()) + .isEqualTo(AssetSource.Requiredness.REQUIRED); + assertThat(result.references().getFirst().family()).isEqualTo("ORDINARY"); + assertThat(result.references().getFirst().role()).isEqualTo("RESOURCE"); + assertThat(result.references().getFirst().sourceBinding()).isSameAs(changed); + assertThat(result.references().getLast().sourceBinding()).isSameAs(original); + assertThat(AssetSource.replay(result.references(), changed)).isEqualTo(result); + assertThat( + AssetSource.replay(result.references(), binding(AssetSource.deletePayload("two.png"))) + .references()) + .extracting(AssetSource.Reference::usageKey) + .containsExactly("one.png"); + } + + @Test + void referenceCannotRewriteItsBoundRequirednessOrRevisionIdentity() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var revision = binding.revisions().getFirst(); + + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.OPTIONAL, + binding, + "0", + revision.revisionId())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Reference( + "logo.png", + "1", + AssetSource.Requiredness.REQUIRED, + binding, + "0", + UUID.randomUUID())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotRejectsForeignTargetDuplicateKeysAndSourceAliases() { + var original = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var references = AssetSource.replay(List.of(), original).references(); + var foreign = binding(UUID.randomUUID(), AssetSource.deletePayload("logo.png")); + + assertThatThrownBy(() -> AssetSource.replay(references, foreign)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new AssetSource.Snapshot( + original, List.of(references.getFirst(), references.getFirst()))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AssetSource.replay( + references, + binding( + AssetSource.upsertPayload( + "1", "alias.png", AssetSource.Requiredness.REQUIRED)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void snapshotDefensivelyRetainsItsReferenceList() { + var binding = + binding(AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.REQUIRED)); + var mutable = new ArrayList<>(AssetSource.replay(List.of(), binding).references()); + var snapshot = new AssetSource.Snapshot(binding, mutable); + mutable.clear(); + + assertThat(snapshot.references()).hasSize(1); + assertThatThrownBy(() -> snapshot.references().clear()) + .isInstanceOf(UnsupportedOperationException.class); + } + + @ParameterizedTest + @ValueSource( + strings = { + "0", + "01", + "-1", + "+1", + "1.0", + "1e2", + " 1", + "9223372036854775808", + "999999999999999999999999" + }) + void deniesNoncanonicalOrOverflowingOwnerRowId(String value) { + assertThatThrownBy( + () -> AssetSource.mutations(binding(upsert("\"" + value + "\"", "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"1", "1.0", "1e0", "null", "true", "{}", "[]"}) + void ownerRowIdMustBeTextNotCoercedJson(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert(value, "\"REQUIRED\"")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @ParameterizedTest + @ValueSource(strings = {"\"UNKNOWN\"", "\"required\"", "null", "true", "1", "{}"}) + void deniesUnknownOrUntypedRequiredness(String value) { + assertThatThrownBy(() -> AssetSource.mutations(binding(upsert("\"1\"", value)))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void deniesMissingRequirednessUnknownMembersDuplicateFieldsAndTrailingJson() { + String valid = upsert("\"1\"", "\"REQUIRED\""); + List invalid = + List.of( + valid.replace(",\"requiredness\":\"REQUIRED\"", ""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1.0"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":\"1\""), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":2"), + valid.replace("\"schemaVersion\":1", "\"schemaVersion\":1,\"schemaVersion\":1"), + valid.replace("\"usageKey\":\"logo.png\"", "\"usageKey\":\"logo.png\",\"extra\":true"), + valid + " {}", + "{\"revisionKind\":\"UNSUPPORTED\"}", + "{}", + AssetSource.deletePayload("logo.png") + .replace( + "\"operation\":\"DELETE\"", + "\"operation\":\"DELETE\",\"requiredness\":\"OPTIONAL\"")); + for (String payload : invalid) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .as(payload) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void usageKeyIsExactBoundedAndCannotReserveManifestName() { + for (String key : List.of("", " ", "manifest.json", "x".repeat(256))) { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", key, AssetSource.Requiredness.REQUIRED)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThat( + AssetSource.mutations( + binding( + AssetSource.upsertPayload( + "1", "x".repeat(255), AssetSource.Requiredness.REQUIRED)))) + .hasSize(1); + } + + @Test + void ordinaryResourceCannotClaimOptionalPresentationOrAnUnknownFamilyOrRole() { + assertThatThrownBy( + () -> AssetSource.upsertPayload("1", "logo.png", AssetSource.Requiredness.OPTIONAL)) + .isInstanceOf(IllegalArgumentException.class); + String required = upsert("\"1\"", "\"REQUIRED\""); + for (String payload : + List.of( + required.replace("REQUIRED", "OPTIONAL"), + required.replace("ORDINARY", "BRANDING"), + required.replace("RESOURCE", "PRESENTATION"), + required.replace(",\"role\":\"RESOURCE\"", ""), + required.replace(",\"family\":\"ORDINARY\"", ""))) { + assertThatThrownBy(() -> AssetSource.mutations(binding(payload))) + .isInstanceOf(IllegalArgumentException.class); + } + } + + private static String upsert(String rowIdJson, String requirednessJson) { + return "{\"schemaVersion\":1,\"revisionKind\":\"ASSET_REFERENCE\",\"family\":\"ORDINARY\",\"role\":\"RESOURCE\",\"operation\":\"UPSERT\",\"assetRowId\":" + + rowIdJson + + ",\"usageKey\":\"logo.png\",\"requiredness\":" + + requirednessJson + + "}"; + } + + private static DraftCommitBinding binding(String... payloads) { + return binding(VERSION, payloads); + } + + private static DraftCommitBinding binding(UUID versionId, String... payloads) { + List revisions = new ArrayList<>(); + for (int index = 0; index < payloads.length; index++) { + revisions.add( + new RevisionPayload( + Integer.toString(index), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads[index])); + } + return DraftCommitBinding.create( + new TargetProof(TENANT, versionId, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"), + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + versionId.toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java new file mode 100644 index 0000000000..5166f916ff --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/gamedesign/CommandDefinitionClosedFieldsTest.java @@ -0,0 +1,97 @@ +package net.firedevops.firemud.common.gamedesign; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +class CommandDefinitionClosedFieldsTest { + private static final String VALID_DEFINITION = + """ + { + "schemaVersion": 1, + "commandId": "salute", + "semanticOwner": "GAME_LOGIC", + "executionDiscipline": "DURABLE_GAMEPLAY", + "stageRequirement": "GAMEPLAY", + "promptPolicy": "WHEN_GAMEPLAY", + "actionCategory": "SOCIAL", + "historyRecordable": true, + "aliases": ["salute"], + "actionTags": ["COMMUNICATION"], + "effects": [ + { + "effectKind": "APPLY_ACTION_STATE", + "schemaVersion": 1, + "targeting": "SELF", + "replayPolicy": "EFFECT_IDEMPOTENT", + "payload": { + "conditionKey": "SALUTING", + "durationSeconds": 30, + "effectPayload": { + "modifiers": [ + { + "operation": "ADD", + "target_key": "salute_count", + "value": 1, + "scope_kind": "ACTION_FAMILY", + "scope_key": "social", + "priority": 2 + } + ] + } + } + } + ] + } + """; + + @Test + void acceptsCanonicalDefinitionAndDefinedOptionalModifierFields() { + assertThat(CommandSource.upsertPayload(VALID_DEFINITION)).isNotBlank(); + } + + @Test + void acceptsCanonicalDefinitionWhenAllOptionalModifierFieldsAreAbsent() { + String definitionWithoutOptionalModifierFields = + VALID_DEFINITION.replace( + ",\n \"scope_kind\": \"ACTION_FAMILY\",\n \"scope_key\": \"social\",\n \"priority\": 2", + ""); + + assertThat(definitionWithoutOptionalModifierFields) + .doesNotContain("scope_kind", "scope_key", "priority"); + assertThat(CommandSource.upsertPayload(definitionWithoutOptionalModifierFields)).isNotBlank(); + } + + @Test + void rejectsUnknownDefinitionFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"commandId\": \"salute\",", "\"targetSelectionPolicyKey\": \"self\","); + } + + @Test + void rejectsUnknownEffectFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectKind\": \"APPLY_ACTION_STATE\",", "\"targetSetKey\": \"SOURCE\","); + } + + @Test + void rejectsUnknownPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"conditionKey\": \"SALUTING\",", "\"sourceRuleId\": \"rule-1\","); + } + + @Test + void rejectsUnknownEffectPayloadFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"effectPayload\": {", "\"targetRefs\": [],"); + } + + @Test + void rejectsUnknownModifierFieldThatCouldCarryAnUnsupportedReference() { + assertRejected("\"operation\": \"ADD\",", "\"targetTemplateId\": \"item-1\","); + } + + private static void assertRejected(String marker, String insertion) { + String unsupported = VALID_DEFINITION.replace(marker, marker + insertion); + assertThat(unsupported).isNotEqualTo(VALID_DEFINITION); + assertThatThrownBy(() -> CommandSource.upsertPayload(unsupported)) + .isInstanceOf(IllegalArgumentException.class); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java new file mode 100644 index 0000000000..5affea2688 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderClientTest.java @@ -0,0 +1,251 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Stub configuration/codec units; mocked channels do not prove an mTLS handshake. */ +class AccountSelectedPublicationOrderClientTest { + @AfterEach + void clear() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresReadableFileBackedMutualTlsAndNamespace(@TempDir Path directory) throws Exception { + var factory = mock(GrpcChannelFactory.class); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), null, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasNoCause(); + var tls = tls(directory); + tls.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication"); + tls.setPlaintext(false); + for (String bad : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + tls.setCertChain(bad); + Throwable failure = + catchThrowable( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, factory, "test")); + assertThat(failure) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasNoCause(); + if (bad != null && !bad.isEmpty()) { + assertThat(failure).hasMessageNotContaining(bad); + } + } + var valid = tls(directory); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), valid, factory, "Test")) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(factory); + } + + @Test + void validatesExactConfiguredTlsPathsBeforeCreatingAChannel(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + + var certChainTls = tls(directory); + certChainTls.setCertChain(certChainTls.getCertChain() + " "); + assertThat(Files.exists(Path.of(certChainTls.getCertChain()))).isFalse(); + assertThat(Files.isReadable(Path.of(certChainTls.getCertChain().trim()))).isTrue(); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), certChainTls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasMessageNotContaining(certChainTls.getCertChain()) + .hasNoCause(); + + var privateKeyTls = tls(directory); + privateKeyTls.setPrivateKey(privateKeyTls.getPrivateKey() + " "); + assertThat(Files.exists(Path.of(privateKeyTls.getPrivateKey()))).isFalse(); + assertThat(Files.isReadable(Path.of(privateKeyTls.getPrivateKey().trim()))).isTrue(); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), privateKeyTls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasMessageNotContaining(privateKeyTls.getPrivateKey()) + .hasNoCause(); + + var caCertTls = tls(directory); + caCertTls.setCaCert(caCertTls.getCaCert() + " "); + assertThat(Files.exists(Path.of(caCertTls.getCaCert()))).isFalse(); + assertThat(Files.isReadable(Path.of(caCertTls.getCaCert().trim()))).isTrue(); + assertThatThrownBy( + () -> + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), caCertTls, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account selected-publication") + .hasMessageNotContaining(caCertTls.getCaCert()) + .hasNoCause(); + + verifyNoInteractions(factory); + } + + @Test + void acceptsAndPreservesTrailingSpacesInExistingTlsPaths(@TempDir Path directory) + throws Exception { + var certChain = Files.writeString(directory.resolve("client.crt "), "certificate"); + var privateKey = Files.writeString(directory.resolve("client.key "), "private-key"); + var caCert = Files.writeString(directory.resolve("ca.crt "), "ca"); + assertThat(Files.exists(directory.resolve("client.crt"))).isFalse(); + assertThat(Files.exists(directory.resolve("client.key"))).isFalse(); + assertThat(Files.exists(directory.resolve("ca.crt"))).isFalse(); + + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(certChain.toString()); + tls.setPrivateKey(privateKey.toString()); + tls.setCaCert(caCert.toString()); + var client = + new AccountSelectedPublicationOrderClient( + new ServiceEndpointsProperties(), tls, mock(GrpcChannelFactory.class), "test"); + + var tlsPropsField = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("tlsProps"); + tlsPropsField.setAccessible(true); + var copiedTls = (CommonGrpcClientProperties) tlsPropsField.get(client); + assertThat(copiedTls.getCertChain()).isEqualTo(certChain.toString()); + assertThat(copiedTls.getPrivateKey()).isEqualTo(privateKey.toString()); + assertThat(copiedTls.getCaCert()).isEqualTo(caCert.toString()); + client.close(); + } + + @Test + void configuresExactAccountPeerDeadlineAndValidatesEchoOutsideSql(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var channel = mock(ManagedChannel.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("account.internal:6565"); + when(factory.buildChannel( + eq("account.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(channel); + var client = + new AccountSelectedPublicationOrderClient(endpoints, tls(directory), factory, "test"); + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), "original.secret.credential"); + try { + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + var initialized = (io.grpc.stub.AbstractStub) field.get(client); + assertThat(initialized.getCallOptions().getMaxInboundMessageSize()) + .isEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); + var credentials = initialized.getCallOptions().getCredentials(); + assertThat(credentials).isInstanceOf(GrpcServerPeerIdentityCallCredentials.class); + var peerField = + GrpcServerPeerIdentityCallCredentials.class.getDeclaredField("expectedPeerUri"); + peerField.setAccessible(true); + assertThat(peerField.get(credentials)) + .isEqualTo("spiffe://firemud/ns/test/sa/account-service"); + var stub = + mock( + AccountSelectedPublicationOrderServiceGrpc + .AccountSelectedPublicationOrderServiceBlockingStub.class); + when(stub.withDeadlineAfter(30, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.withCallCredentials(any())).thenReturn(stub); + field.set(client, stub); + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.setActualTransactionActive(false); + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + TransactionSynchronizationManager.clearSynchronization(); + var wrongNamespace = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "other", binding.input().selection(), "original.secret.credential"); + assertThatThrownBy(() -> client.authorize(wrongNamespace)) + .isInstanceOf(IllegalArgumentException.class); + verifyNoInteractions(stub); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + when(stub.authorizeSelectedPublication(any())).thenReturn(response); + assertThat(client.authorize(request).canonicalBytes()).isEqualTo(binding.canonicalBytes()); + verify(stub).withDeadlineAfter(30, TimeUnit.SECONDS); + var wire = + org.mockito.ArgumentCaptor.forClass( + net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest.class); + verify(stub).authorizeSelectedPublication(wire.capture()); + assertThat(wire.getValue().toString()).doesNotContain(request.originalCreatorCredential()); + var perCall = org.mockito.ArgumentCaptor.forClass(io.grpc.CallCredentials.class); + verify(stub).withCallCredentials(perCall.capture()); + assertThat(perCall.getValue()).isInstanceOf(io.grpc.CompositeCallCredentials.class); + when(stub.authorizeSelectedPublication(any())) + .thenReturn(response.toBuilder().setTargetNamespace("other").build()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageNotContaining(request.originalCreatorCredential()); + when(stub.authorizeSelectedPublication(any())) + .thenThrow( + io.grpc.Status.UNAVAILABLE + .withDescription(request.originalCreatorCredential()) + .asRuntimeException()); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .hasMessageNotContaining(request.originalCreatorCredential()) + .hasNoCause(); + } finally { + client.close(); + } + assertThatThrownBy(client::init).isInstanceOf(IllegalStateException.class); + assertThatThrownBy(() -> client.authorize(request)).isInstanceOf(IllegalStateException.class); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + return tls; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java new file mode 100644 index 0000000000..aed92c82e7 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderCredentialsTest.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.common.publication; + +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.when; + +import io.grpc.CallCredentials; +import io.grpc.Metadata; +import io.grpc.SecurityLevel; +import java.nio.charset.StandardCharsets; +import java.util.List; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationOrderServiceGrpc; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderCredentialsTest { + private static final String SECRET = "original.secret.credential"; + private static final Metadata.Key RAW = + Metadata.Key.of( + AccountSelectedPublicationOrderCredentials.HEADER.name(), + Metadata.BINARY_BYTE_MARSHALLER); + + @Test + void carrierAndWrapperAreRedactedAndApplyOnlyToProtectedExactMethod() { + var credentials = AccountSelectedPublicationOrderCredentials.forCall(SECRET); + assertThat(credentials.toString()).doesNotContain(SECRET); + assertThat(AccountSelectedPublicationOrderCredentials.Credential.of(SECRET).toString()) + .doesNotContain(SECRET); + var info = mock(CallCredentials.RequestInfo.class); + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod()) + .when(info) + .getMethodDescriptor(); + var applier = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, applier); + var captured = org.mockito.ArgumentCaptor.forClass(Metadata.class); + verify(applier).apply(captured.capture()); + assertThat( + AccountSelectedPublicationOrderCredentials.readAuthenticated(captured.getValue()) + .value()) + .isEqualTo(SECRET); + for (var level : List.of(SecurityLevel.NONE, SecurityLevel.INTEGRITY)) { + when(info.getSecurityLevel()).thenReturn(level); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied) + .fail( + org.mockito.ArgumentMatchers.argThat( + status -> status.getCode() == io.grpc.Status.Code.UNAUTHENTICATED)); + } + when(info.getSecurityLevel()).thenReturn(SecurityLevel.PRIVACY_AND_INTEGRITY); + org.mockito.Mockito.doReturn( + AccountSelectedPublicationOrderServiceGrpc.getAuthorizeSelectedPublicationMethod() + .toBuilder() + .setFullMethodName("different/Method") + .build()) + .when(info) + .getMethodDescriptor(); + var denied = mock(CallCredentials.MetadataApplier.class); + credentials.applyRequestMetadata(info, Runnable::run, denied); + verify(denied).fail(org.mockito.ArgumentMatchers.any()); + } + + @Test + void + authenticatedReadRejectsMissingDuplicateOversizedAndMalformedHeadersWithoutSecretDiagnostics() { + String maxCredential = + "A".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES); + var missing = new Metadata(); + var duplicate = new Metadata(); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + duplicate.put(RAW, SECRET.getBytes(StandardCharsets.US_ASCII)); + for (var headers : + List.of( + missing, + duplicate, + raw(new byte[0]), + raw(new byte[] {(byte) 128}), + raw((SECRET + "\n").getBytes(StandardCharsets.US_ASCII)), + raw(new byte[AccountSelectedPublicationOrderGrpcCodec.MAX_CREDENTIAL_BYTES + 1]))) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderCredentials.readAuthenticated(headers)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(SECRET) + .hasNoCause(); + } + var exact = + AccountSelectedPublicationOrderCredentials.readAuthenticated( + raw(SECRET.getBytes(StandardCharsets.US_ASCII))); + assertThat(exact.value()).isEqualTo(SECRET); + assertThat(exact.toString()).doesNotContain(SECRET); + assertThat( + AccountSelectedPublicationOrderCredentials.readAuthenticated( + raw(maxCredential.getBytes(StandardCharsets.US_ASCII))) + .value()) + .isEqualTo(maxCredential); + } + + private static Metadata raw(byte[] bytes) { + var headers = new Metadata(); + headers.put(RAW, bytes); + return headers; + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java new file mode 100644 index 0000000000..df0baf31a5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationOrderGrpcCodecTest.java @@ -0,0 +1,235 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.AuthorizeSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.SourceEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.VisibilityFence; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationOrderGrpcCodecTest { + private static final String CREDENTIAL = "original.secret.credential"; + + @Test + void preservesOriginalCredentialAndCanonicalSelectionWithoutEchoingSecret() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + var decoded = AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, CREDENTIAL); + assertThat(decoded.originalCreatorCredential()).isEqualTo(CREDENTIAL); + assertThat(decoded.originalSelection()).isEqualTo(request.originalSelection()); + assertThat(decoded.requestId()).isEqualTo(request.requestId()); + assertThat(decoded.toString()).doesNotContain(CREDENTIAL); + assertThat(wire.toString()).doesNotContain(CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + assertThat(response.toString()).doesNotContain(CREDENTIAL); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + var fresh = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse( + fresh, AccountSelectedPublicationOrderGrpcCodec.toResponse(fresh, binding)) + .canonicalBytes()) + .isEqualTo(binding.canonicalBytes()); + } + + @Test + void rejectsUnknownNoncanonicalOversizedAndMissingRequestFieldsWithoutSecretDiagnostics() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var wire = AccountSelectedPublicationOrderGrpcCodec.toRequest(request); + for (AuthorizeSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().setRequestId(new UUID(0, 0).toString()).build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().clearOriginalSelection().build(), + wire.toBuilder().setOriginalSelection(ByteString.copyFrom(new byte[1048577])).build(), + wire.toBuilder() + .setOriginalSelection( + wire.getOriginalSelection().concat(ByteString.copyFromUtf8(" "))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(invalid, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + for (String invalid : List.of("", "x".repeat(16385), CREDENTIAL + "\n")) { + assertThatThrownBy(() -> AccountSelectedPublicationOrderGrpcCodec.fromRequest(wire, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + @Test + void rejectsChangedResponseEchoBindingAndUnknownFields() { + var binding = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", binding.input().selection(), CREDENTIAL); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + for (var invalid : + List.of( + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder().clearOriginalSelection().build(), + response.toBuilder() + .setTargetNamespace( + "x".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES)) + .build(), + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().clearPublicationAuthorizationBinding().build(), + response.toBuilder() + .setPublicationAuthorizationBinding(ByteString.copyFrom(new byte[] {1})) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageNotContaining(CREDENTIAL) + .hasNoCause(); + } + } + + @Test + void roundTripsMaximumCanonicalSelectionWithLargerBoundedBinding() { + var base = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var selectionWithoutNotes = withNotes(base.input().selection(), ""); + int notesBytes = + AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES + - selectionWithoutNotes.canonicalBytes().length; + var selection = withNotes(base.input().selection(), "n".repeat(notesBytes)); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create("test", selection, CREDENTIAL); + var binding = + new AccountPublicationAuthorizationBinding( + base.operationId(), + base.fenceId(), + new AccountPublicationAuthorizationBinding.PreallocationInput( + base.input().actorAccountId(), selection), + base.sources()); + + assertThat(request.originalSelection()) + .hasSize(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES); + assertThat(binding.canonicalBytes()) + .hasSizeGreaterThan(request.originalSelection().length) + .hasSizeLessThanOrEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_BINDING_BYTES); + var response = AccountSelectedPublicationOrderGrpcCodec.toResponse(request, binding); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); + assertThat( + AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(binding.canonicalBytes()); + + var oversizedSelection = + withNotes( + base.input().selection(), + "n".repeat(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES)); + assertThat(oversizedSelection.canonicalBytes()) + .hasSizeGreaterThan(AccountSelectedPublicationOrderGrpcCodec.MAX_SELECTION_BYTES); + assertThatThrownBy( + () -> + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", oversizedSelection, CREDENTIAL)) + .isInstanceOf(IllegalArgumentException.class) + .hasNoCause(); + } + + @Test + void rejectsOversizedBindingBeforeProducerAndConsumerDecode() { + var base = AccountPublicationAuthorizationReadGrpcCodecTest.binding(); + var request = + AccountSelectedPublicationOrderGrpcCodec.Request.create( + "test", base.input().selection(), CREDENTIAL); + var source = base.sources().get(0); + var oversizedSource = + new SourceEvidence( + source.kind(), + source.scopeId(), + source.generation(), + source.sourceVersion(), + source.checkpointStream(), + source.checkpointSequence(), + new byte[AccountSelectedPublicationOrderGrpcCodec.MAX_BINDING_BYTES + 1]); + var oversizedBinding = + new AccountPublicationAuthorizationBinding( + base.operationId(), base.fenceId(), base.input(), List.of(oversizedSource)); + + assertThat(oversizedBinding.canonicalBytes()) + .hasSizeGreaterThan(AccountSelectedPublicationOrderGrpcCodec.MAX_BINDING_BYTES); + assertThatThrownBy( + () -> AccountSelectedPublicationOrderGrpcCodec.toResponse(request, oversizedBinding)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid selected-publication order transport evidence") + .hasNoCause(); + + var wire = + AuthorizeSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalSelection(ByteString.copyFrom(request.originalSelection())) + .setPublicationAuthorizationBinding( + ByteString.copyFrom(oversizedBinding.canonicalBytes())) + .build(); + assertThat(wire.getSerializedSize()) + .isLessThanOrEqualTo(AccountSelectedPublicationOrderGrpcCodec.MAX_RESPONSE_MESSAGE_BYTES); + assertThatThrownBy(() -> AccountSelectedPublicationOrderGrpcCodec.fromResponse(request, wire)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Invalid selected-publication order transport evidence") + .hasNoCause(); + } + + private static AuthoredDraftPublishSelectionBinding withNotes( + AuthoredDraftPublishSelectionBinding selection, String notes) { + var intent = selection.intent(); + return AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + notes, + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()), + selection.target(), + selection.selectedCommit(), + new VisibilityFence( + selection.target(), + selection.fenceRequestId(), + selection.fenceCommitId(), + selection.fenceInputDigest(), + selection.fenceResultVectorJson(), + OffsetDateTime.parse(selection.fenceCreatedAt()))); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java new file mode 100644 index 0000000000..c7efe63fe5 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementClientTest.java @@ -0,0 +1,409 @@ +package net.firedevops.firemud.common.publication; + +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 io.grpc.Server; +import io.grpc.Status; +import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts; +import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder; +import io.grpc.netty.shaded.io.netty.handler.ssl.ClientAuth; +import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import io.grpc.stub.StreamObserver; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.Base64; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.account.v1.AccountSelectedPublicationSettlementServiceGrpc; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** Physical mTLS proof that Account settlement may complete after the former five-second window. */ +class AccountSelectedPublicationSettlementClientTest { + private static final String NAMESPACE = "test"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/test/sa/account-service"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static final String STORE_PASSWORD = "test-only-store-password"; + + @Test + void requiresFileBackedMtlsWithAccountSettlementContext(@TempDir Path directory) { + var endpoints = new ServiceEndpointsProperties(); + var factory = mock(GrpcChannelFactory.class); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new AccountSelectedPublicationSettlementClient( + endpoints, plaintext, factory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account publication settlement") + .hasNoCause(); + + var classpath = new CommonGrpcClientProperties(); + classpath.setPlaintext(false); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey(directory.resolve("client.key").toString()); + classpath.setCaCert(directory.resolve("ca.crt").toString()); + assertThatThrownBy( + () -> + new AccountSelectedPublicationSettlementClient( + endpoints, classpath, factory, NAMESPACE)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Account publication settlement") + .hasMessageNotContaining("classpath:client.crt") + .hasNoCause(); + verifyNoInteractions(factory); + } + + @Test + void returnsCanonicalReceiptFromAuthenticatedAccountPeerAfterFormerFiveSecondWindow( + @TempDir Path directory) throws Exception { + TestPki pki = TestPki.create(directory); + var operation = WorldPublicationTerminalTestFixtures.operation(); + var terminal = + WorldPublicationTerminalTestFixtures.terminal( + operation, GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()); + byte[] receipt = receipt(operation, terminal); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + AtomicReference received = new AtomicReference<>(); + var service = + new AccountSelectedPublicationSettlementServiceGrpc + .AccountSelectedPublicationSettlementServiceImplBase() { + @Override + public void settleSelectedPublication( + SettleSelectedPublicationRequest wireRequest, + StreamObserver observer) { + GrpcPeerIdentity peer = GrpcPeerIdentity.current(); + if (peer == null || !GAME_DESIGN_URI.equals(peer.uri())) { + observer.onError(Status.UNAUTHENTICATED.asRuntimeException()); + return; + } + received.set(wireRequest); + try { + TimeUnit.SECONDS.sleep(6L); + observer.onNext(response); + observer.onCompleted(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + observer.onError(Status.CANCELLED.withCause(interrupted).asRuntimeException()); + } + } + }; + + try (TransportServer server = startServer(pki, service); + AccountSelectedPublicationSettlementClient client = client(pki, server.port(), directory)) { + client.init(); + long started = System.nanoTime(); + byte[] actualReceipt = client.settle(request); + long elapsedNanos = System.nanoTime() - started; + + assertThat(elapsedNanos).isGreaterThanOrEqualTo(TimeUnit.SECONDS.toNanos(6L)); + assertThat(actualReceipt).containsExactly(receipt); + assertThat(received.get()) + .isEqualTo(AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + } + } + + private static byte[] receipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal) { + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, operation.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame( + out, + terminal.outcome() == GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED + ? "PUBLISHED" + : "ABORTED"); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + return out.toByteArray(); + } + + private static TransportServer startServer(TestPki pki, io.grpc.BindableService service) + throws Exception { + Server server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + pki.accountServer().privateKey(), pki.accountServer().certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(service) + .intercept(new GrpcPeerIdentityInterceptor()) + .build() + .start(); + return new TransportServer(server); + } + + private static AccountSelectedPublicationSettlementClient client( + TestPki pki, int port, Path directory) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService("127.0.0.1:" + port); + return new AccountSelectedPublicationSettlementClient( + endpoints, pki.clientProperties(directory), new GrpcChannelFactory(), NAMESPACE); + } + + private record TransportServer(Server server) implements AutoCloseable { + private int port() { + return server.getPort(); + } + + @Override + public void close() throws InterruptedException { + server.shutdownNow(); + if (!server.awaitTermination(2, TimeUnit.SECONDS)) { + throw new IllegalStateException("Account settlement loopback server did not terminate"); + } + } + } + + private record TestIdentity(PrivateKey privateKey, X509Certificate certificate) {} + + private record TestPki( + X509Certificate caCertificate, TestIdentity accountServer, TestIdentity gameDesignClient) { + private static TestPki create(Path directory) throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + runKeytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=FireMUD Account settlement test CA", + "-validity", + "30", + "-ext", + "BC=ca:true", + "-ext", + "KU=keyCertSign,cRLSign", + "-storetype", + "PKCS12", + "-keystore", + caStore.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + Path caFile = directory.resolve("test-ca.crt"); + runKeytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + return new TestPki( + readCertificate(caFile), + issueIdentity(directory, caStore, caFile, "account-server", ACCOUNT_URI, true), + issueIdentity(directory, caStore, caFile, "game-design-client", GAME_DESIGN_URI, false)); + } + + private CommonGrpcClientProperties clientProperties(Path directory) throws Exception { + Path certificate = + writePem( + directory.resolve("game-design-client.crt"), + "CERTIFICATE", + gameDesignClient.certificate().getEncoded()); + Path privateKey = + writePem( + directory.resolve("game-design-client.key"), + "PRIVATE KEY", + gameDesignClient.privateKey().getEncoded()); + Path caFile = + writePem( + directory.resolve("client-trust-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + + private static TestIdentity issueIdentity( + Path directory, Path caStore, Path caFile, String alias, String uri, boolean server) + throws Exception { + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + String san = "URI:" + uri + ",DNS:localhost,IP:127.0.0.1"; + String usage = server ? "serverAuth" : "clientAuth"; + runKeytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + runKeytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + runKeytool( + "-gencert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-infile", + request.toString(), + "-outfile", + certificate.toString(), + "-validity", + "30", + "-rfc", + "-ext", + "BC=ca:false", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + usage, + "-ext", + "SAN=" + san); + runKeytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + runKeytool( + "-importcert", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + certificate.toString(), + "-noprompt"); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (var input = Files.newInputStream(store)) { + keyStore.load(input, STORE_PASSWORD.toCharArray()); + } + return new TestIdentity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void runKeytool(String... arguments) throws Exception { + Path keytool = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(keytool.toString()); + command.addAll(List.of(arguments)); + Process process = + new ProcessBuilder(command) + .redirectErrorStream(true) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(2, TimeUnit.SECONDS); + throw new IllegalStateException("test keytool operation timed out"); + } + if (process.exitValue() != 0) { + throw new IllegalStateException( + "test keytool operation failed with exit " + process.exitValue()); + } + } + + private static X509Certificate readCertificate(Path path) throws Exception { + try (var input = Files.newInputStream(path)) { + return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(input); + } + } + + private static Path writePem(Path path, String label, byte[] bytes) throws IOException { + String body = Base64.getMimeEncoder(64, new byte[] {'\n'}).encodeToString(bytes); + return Files.writeString( + path, + "-----BEGIN " + label + "-----\n" + body + "\n-----END " + label + "-----\n", + StandardCharsets.US_ASCII); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java new file mode 100644 index 0000000000..39f7bd3eab --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AccountSelectedPublicationSettlementGrpcCodecTest.java @@ -0,0 +1,240 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationRequest; +import net.firedevops.firemud.account.v1.SettleSelectedPublicationResponse; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import org.junit.jupiter.api.Test; + +class AccountSelectedPublicationSettlementGrpcCodecTest { + @Test + void roundTripsBothCanonicalSixFrameReceiptsAndUsesIndependentCorrelation() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + for (Outcome outcome : Outcome.values()) { + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, outcome); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var decoded = + AccountSelectedPublicationSettlementGrpcCodec.fromRequest( + AccountSelectedPublicationSettlementGrpcCodec.toRequest(request)); + assertThat(decoded).isEqualTo(request); + + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + assertThat(AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, response)) + .containsExactly(receipt); + + var fresh = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + assertThat(fresh.requestId()).isNotEqualTo(request.requestId()); + assertThat(fresh.originalOperation()).containsExactly(request.originalOperation()); + } + } + + @Test + void retainsV1HistoryButRejectsItFromCurrentSettlementRequests() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var history = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(history, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(history, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(history, operation.world().canonicalBytes()); + byte[] original = history.toByteArray(); + assertThat(GameDesignPublicationOperationBinding.fromStored(original).canonicalBytes()) + .containsExactly(original); + + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.Request.create("test", original)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete canonical original publication operation required"); + var current = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var changed = + AccountSelectedPublicationSettlementGrpcCodec.toRequest(current).toBuilder() + .setOriginalOperation(ByteString.copyFrom(original)) + .build(); + assertThatThrownBy(() -> AccountSelectedPublicationSettlementGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Account publication settlement request is invalid"); + } + + @Test + void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var wire = AccountSelectedPublicationSettlementGrpcCodec.toRequest(request); + for (SettleSelectedPublicationRequest invalid : + List.of( + wire.toBuilder().setUnknownFields(unknown()).build(), + wire.toBuilder().setSchemaVersion(2).build(), + wire.toBuilder().setTargetNamespace("Test").build(), + wire.toBuilder().setRequestId("00000000-0000-0000-0000-000000000000").build(), + wire.toBuilder().setRequestId("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA").build(), + wire.toBuilder().setRequestId("1-1-1-1-1").build(), + wire.toBuilder().clearOriginalOperation().build(), + wire.toBuilder() + .setOriginalOperation( + wire.getOriginalOperation().concat(ByteString.copyFrom(new byte[] {0}))) + .build(), + wire.toBuilder().setOriginalOperation(ByteString.copyFrom(new byte[] {1})).build())) { + assertThatThrownBy(() -> AccountSelectedPublicationSettlementGrpcCodec.fromRequest(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", + new byte[GameDesignPublicationOperationBinding.MAX_OPERATION_BYTES + 1])) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("4 MiB"); + } + + @Test + void rejectsChangedRequestEchoUnknownFieldsAndChangedOrNoncanonicalReceiptFrames() + throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + var changedOperation = WorldPublicationTerminalTestFixtures.operation(); + var changedTerminal = + WorldPublicationTerminalTestFixtures.terminal(changedOperation, Outcome.PUBLISHED); + var sameOperationOtherOutcome = + WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.PUBLISHED); + byte[] receipt = receipt(operation, terminal, null, null, null, null); + var response = AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, receipt); + var changedBinding = new byte[] {1, 2, 3}; + byte[] wrongOutcome = receipt(operation, terminal, "PUBLISHED", null, null, null); + byte[] wrongBinding = receipt(operation, terminal, null, changedBinding, null, null); + byte[] wrongOperation = + receipt(operation, terminal, null, null, changedOperation.canonicalBytes(), null); + byte[] wrongTerminal = receipt(operation, changedTerminal, null, null, null, null); + byte[] wrongWorldTerminal = + receipt(operation, terminal, null, null, null, sameOperationOtherOutcome.canonicalBytes()); + byte[] missingWorldTerminal = receipt(operation, terminal, null, null, null, new byte[0]); + byte[] noncanonicalWorldTerminal = + receipt( + operation, + terminal, + null, + null, + null, + ByteString.copyFrom(terminal.canonicalBytes()) + .concat(ByteString.copyFrom(new byte[] {0})) + .toByteArray()); + for (var invalid : + List.of( + response.toBuilder().setUnknownFields(unknown()).build(), + response.toBuilder().setSchemaVersion(2).build(), + response.toBuilder().setTargetNamespace("other").build(), + response.toBuilder().setRequestId(UUID.randomUUID().toString()).build(), + response.toBuilder() + .setOriginalOperation(ByteString.copyFrom(changedOperation.canonicalBytes())) + .build(), + response.toBuilder().clearSettlementReceipt().build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOutcome)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongBinding)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongOperation)).build(), + response.toBuilder().setSettlementReceipt(ByteString.copyFrom(wrongTerminal)).build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(wrongWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(missingWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt(ByteString.copyFrom(noncanonicalWorldTerminal)) + .build(), + response.toBuilder() + .setSettlementReceipt( + response.getSettlementReceipt().concat(ByteString.copyFrom(new byte[] {0}))) + .build())) { + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.fromResponse(request, invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, wrongOutcome)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void enforcesCompleteSerializedMessageBudgetBeforeReceiptDecoding() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + AccountSelectedPublicationSettlementGrpcCodec.Request.create( + "test", operation.canonicalBytes()); + byte[] oversizedReceipt = + new byte[AccountSelectedPublicationSettlementGrpcCodec.MAX_MESSAGE_BYTES]; + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.toResponse(request, oversizedReceipt)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + + var oversizedResponse = + SettleSelectedPublicationResponse.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setRequestId(request.requestId().toString()) + .setOriginalOperation(ByteString.copyFrom(request.originalOperation())) + .setSettlementReceipt(ByteString.copyFrom(oversizedReceipt)) + .build(); + assertThatThrownBy( + () -> + AccountSelectedPublicationSettlementGrpcCodec.fromResponse( + request, oversizedResponse)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("32 MiB"); + } + + private static byte[] receipt( + GameDesignPublicationOperationBinding operation, + GameDesignPublicationTerminalEvidence terminal, + String outcomeOverride, + byte[] accountBindingOverride, + byte[] operationOverride, + byte[] worldTerminalOverride) { + String outcome = + outcomeOverride == null + ? terminal.outcome() == Outcome.PUBLISHED ? "PUBLISHED" : "ABORTED" + : outcomeOverride; + byte[] accountBinding = + accountBindingOverride == null + ? operation.account().canonicalBytes() + : accountBindingOverride; + byte[] operationBytes = + operationOverride == null ? operation.canonicalBytes() : operationOverride; + byte[] worldTerminal = + worldTerminalOverride == null ? terminal.canonicalBytes() : worldTerminalOverride; + var out = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(out, "account-selected-publication-settlement/v1"); + DraftAuthorizationFenceBinding.frame(out, accountBinding); + DraftAuthorizationFenceBinding.frame(out, operationBytes); + DraftAuthorizationFenceBinding.frame(out, terminal.canonicalBytes()); + DraftAuthorizationFenceBinding.frame(out, outcome); + DraftAuthorizationFenceBinding.frame(out, worldTerminal); + return out.toByteArray(); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java new file mode 100644 index 0000000000..0cd2843a8c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalClientTransactionTest.java @@ -0,0 +1,119 @@ +package net.firedevops.firemud.common.publication; + +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.clearInvocations; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Optional; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.gamedesign.v1.GameDesignPublicationTerminalReadServiceGrpc; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Transaction ordering units; mocked channels do not establish an mTLS handshake. */ +class GameDesignPublicationTerminalClientTransactionTest { + @AfterEach + void clearTransactionContext() { + TransactionSynchronizationManager.clear(); + } + + @Test + void requiresFileBackedMtlsWithGameDesignTerminalContext(@TempDir Path directory) { + var factory = mock(GrpcChannelFactory.class); + var endpoints = new ServiceEndpointsProperties(); + var plaintext = new CommonGrpcClientProperties(); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> new GameDesignPublicationTerminalClient(endpoints, plaintext, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Game Design publication terminal read") + .hasNoCause(); + + var classpath = new CommonGrpcClientProperties(); + classpath.setPlaintext(false); + classpath.setCertChain("classpath:client.crt"); + classpath.setPrivateKey(directory.resolve("client.key").toString()); + classpath.setCaCert(directory.resolve("ca.crt").toString()); + assertThatThrownBy( + () -> new GameDesignPublicationTerminalClient(endpoints, classpath, factory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Game Design publication terminal read") + .hasMessageNotContaining("classpath:client.crt") + .hasNoCause(); + verifyNoInteractions(factory); + } + + @Test + void excludesActiveAndSynchronizationOnlyTransactionsBeforeAnyRpc(@TempDir Path directory) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService("design.internal:6565"); + when(factory.buildChannel( + eq("design.internal:6565"), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenReturn(mock(ManagedChannel.class)); + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain(Files.writeString(directory.resolve("client.crt"), "certificate").toString()); + tls.setPrivateKey(Files.writeString(directory.resolve("client.key"), "private-key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "ca").toString()); + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = + GameDesignPublicationTerminalReadEvidence.ReadRequest.create( + "test", operation.canonicalBytes()); + var expected = + new GameDesignPublicationTerminalReadEvidence.ReadResult( + request, GameDesignPublicationTerminalReadEvidence.Status.UNKNOWN, Optional.empty()); + var stub = + mock( + GameDesignPublicationTerminalReadServiceGrpc + .GameDesignPublicationTerminalReadServiceBlockingStub.class); + when(stub.withDeadlineAfter(5, TimeUnit.SECONDS)).thenReturn(stub); + when(stub.readGameDesignPublicationTerminal(any())) + .thenReturn(GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, expected)); + + try (var client = new GameDesignPublicationTerminalClient(endpoints, tls, factory, "test")) { + client.init(); + var field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("stub"); + field.setAccessible(true); + field.set(client, stub); + assertThat(client.read(request).canonicalBytes()).containsExactly(expected.canonicalBytes()); + clearInvocations(stub); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + assertThatThrownBy(() -> client.read(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.read(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("requires no owner transaction"); + TransactionSynchronizationManager.clearSynchronization(); + verifyNoInteractions(stub); + + assertThat(client.read(request).canonicalBytes()).containsExactly(expected.canonicalBytes()); + } + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java new file mode 100644 index 0000000000..bee71c9c09 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/GameDesignPublicationTerminalReadGrpcCodecTest.java @@ -0,0 +1,172 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadRequest; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.ReadResult; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadEvidence.Status; +import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalReadGrpcCodec; +import org.junit.jupiter.api.Test; + +/** Preserved donor refusal vectors mapped to the canonical framed read, with controlled inputs. */ +class GameDesignPublicationTerminalReadGrpcCodecTest { + @Test + void retainsExactReadCorrelationAndTerminalBytesForEveryCanonicalStatus() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + GameDesignPublicationTerminalReadGrpcCodec.toRequest(request))) + .isEqualTo(request); + for (Status status : Status.values()) { + var terminal = + status == Status.UNKNOWN + ? Optional + . + empty() + : Optional.of( + WorldPublicationTerminalTestFixtures.terminal( + operation, Outcome.valueOf(status.name()))); + var result = new ReadResult(request, status, terminal); + var response = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(result.canonicalBytes()); + assertThat( + GameDesignPublicationTerminalReadGrpcCodec.fromResponse(request, response) + .canonicalBytes()) + .containsExactly(result.canonicalBytes()); + } + } + + @Test + void rejectsUnknownMalformedNoncanonicalAndIncompleteFramedRequests() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + var wire = GameDesignPublicationTerminalReadGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class); + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {1}, + replaceFrame(request.canonicalBytes(), 1, text("2")), + replaceFrame(request.canonicalBytes(), 2, text("Test")), + replaceFrame(request.canonicalBytes(), 2, text("other")), + replaceFrame(request.canonicalBytes(), 3, text("00000000-0000-0000-0000-000000000000")), + replaceFrame(request.canonicalBytes(), 3, text("AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA")), + replaceFrame(request.canonicalBytes(), 3, text("1-1-1-1-1")), + replaceFrame(request.canonicalBytes(), 4, new byte[0]), + replaceFrame(request.canonicalBytes(), 4, new byte[] {1}), + java.util.Arrays.copyOf( + request.canonicalBytes(), request.canonicalBytes().length + 1))) { + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromRequest( + wire.toBuilder() + .setCanonicalRequestBytes(ByteString.copyFrom(invalid)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Test + void rejectsChangedEchoUnknownMalformedMissingAndSubstitutedTerminalResponses() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var request = ReadRequest.create("test", operation.canonicalBytes()); + var terminal = WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var result = new ReadResult(request, Status.NO_PUBLICATION, Optional.of(terminal)); + var wire = GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, result); + var changedRequest = ReadRequest.create("test", operation.canonicalBytes()); + var changedTerminal = + WorldPublicationTerminalTestFixtures.terminal( + WorldPublicationTerminalTestFixtures.operation(), Outcome.NO_PUBLICATION); + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, wire.toBuilder().setUnknownFields(unknown()).build())) + .isInstanceOf(IllegalArgumentException.class); + for (byte[] invalid : + List.of( + new byte[0], + new byte[] {1}, + replaceFrame(result.canonicalBytes(), 1, changedRequest.canonicalBytes()), + replaceFrame(result.canonicalBytes(), 2, text("UNKNOWN")), + replaceFrame(result.canonicalBytes(), 2, text("PUBLISHED")), + replaceFrame(result.canonicalBytes(), 3, new byte[0]), + replaceFrame(result.canonicalBytes(), 3, new byte[] {1}), + replaceFrame(result.canonicalBytes(), 3, changedTerminal.canonicalBytes()), + java.util.Arrays.copyOf(result.canonicalBytes(), result.canonicalBytes().length + 1))) { + assertThatThrownBy( + () -> + GameDesignPublicationTerminalReadGrpcCodec.fromResponse( + request, + wire.toBuilder() + .setCanonicalResponseBytes(ByteString.copyFrom(invalid)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + } + var changedResult = + new ReadResult(changedRequest, Status.NO_PUBLICATION, Optional.of(terminal)); + assertThatThrownBy( + () -> GameDesignPublicationTerminalReadGrpcCodec.toResponse(request, changedResult)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.UNKNOWN, Optional.of(terminal))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new ReadResult(request, Status.PUBLISHED, Optional.empty())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void retainsDefensiveOperationBytesAndRejectsReusedOriginalIdentity() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + byte[] input = operation.canonicalBytes(); + var request = ReadRequest.create("test", input); + java.util.Arrays.fill(input, (byte) 0); + assertThat(request.operationBytes()).containsExactly(operation.canonicalBytes()); + byte[] returned = request.operationBytes(); + java.util.Arrays.fill(returned, (byte) 0); + assertThat(request.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThatThrownBy( + () -> + new ReadRequest( + 1, "test", operation.account().operationId(), operation.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class); + } + + private static UnknownFieldSet unknown() { + return UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + } + + private static byte[] text(String value) { + return value.getBytes(StandardCharsets.UTF_8); + } + + private static byte[] replaceFrame(byte[] framed, int target, byte[] replacement) { + var input = ByteBuffer.wrap(framed); + var output = new ByteArrayOutputStream(); + for (int index = 0; input.hasRemaining(); index++) { + int length = input.getInt(); + byte[] value = new byte[length]; + input.get(value); + DraftAuthorizationFenceBinding.frame(output, index == target ? replacement : value); + } + return output.toByteArray(); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java index c46c8135fe..af7d66dd4a 100644 --- a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/WorldPublicationTerminalCompletionGrpcCodecTest.java @@ -5,8 +5,10 @@ import com.google.protobuf.ByteString; import com.google.protobuf.UnknownFieldSet; +import java.io.ByteArrayOutputStream; import java.util.List; import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence; import net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalEvidence.Outcome; import net.firedevops.firemud.worldmanagement.v1.CompleteVersionPublicationRequest; @@ -41,6 +43,41 @@ void roundTripsBothTerminalOutcomesAndUsesIndependentTransportCorrelation() thro } } + @Test + void historicalTerminalReadbackCannotEnterCurrentV2CompletionTransport() throws Exception { + var operation = WorldPublicationTerminalTestFixtures.operation(); + var history = new ByteArrayOutputStream(); + DraftAuthorizationFenceBinding.frame(history, "game-design-publication-operation/v1"); + DraftAuthorizationFenceBinding.frame(history, operation.account().canonicalBytes()); + DraftAuthorizationFenceBinding.frame(history, operation.world().canonicalBytes()); + byte[] original = history.toByteArray(); + var historicalTerminal = + new GameDesignPublicationTerminalEvidence(original, Outcome.NO_PUBLICATION, null, null); + assertThat( + GameDesignPublicationTerminalEvidence.fromStored(historicalTerminal.canonicalBytes()) + .operationBytes()) + .containsExactly(original); + assertThatThrownBy( + () -> + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", original, historicalTerminal.canonicalBytes())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Complete canonical publication operation and terminal required"); + + var currentTerminal = + WorldPublicationTerminalTestFixtures.terminal(operation, Outcome.NO_PUBLICATION); + var current = + WorldPublicationTerminalCompletionGrpcCodec.Request.create( + "test", operation.canonicalBytes(), currentTerminal.canonicalBytes()); + var changed = + WorldPublicationTerminalCompletionGrpcCodec.toRequest(current).toBuilder() + .setOriginalOperation(ByteString.copyFrom(original)) + .setGameDesignTerminalEvidence(ByteString.copyFrom(historicalTerminal.canonicalBytes())) + .build(); + assertThatThrownBy(() -> WorldPublicationTerminalCompletionGrpcCodec.fromRequest(changed)) + .isInstanceOf(IllegalArgumentException.class); + } + @Test void rejectsMalformedAndNoncanonicalRequestsAndUnknownFields() throws Exception { var operation = WorldPublicationTerminalTestFixtures.operation(); diff --git a/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java new file mode 100644 index 0000000000..f92a8c58d1 --- /dev/null +++ b/services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionService.java @@ -0,0 +1,339 @@ +package net.firedevops.firemud.gamedesign.publication; + +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; +import net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelectionRepository; +import net.firedevops.firemud.gamedesign.draft.DraftCommitCoordinatorRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.jooq.DSLContext; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Unregistered Game Design admission boundary for one exact selected-Draft publication. Account + * authorization, World freeze and selector capture finish before the local reservation transaction. + */ +public final class SelectedDraftPublicationAdmissionService { + private final AccountPublicationAuthorizationReadClient accountClient; + private final WorldPublishedStartLocationClient worldClient; + private final WorldSelectedDraftPublicationFreezeClient freezeClient; + private final WorldSelectedPublicationArtifactInventoryClient inventoryClient; + private final SelectionReader selectionReader; + private final SelectedDraftPublicationOwner owner; + private final WorldAuthoredSourceIntakeClient worldSourceIntakeClient; + private final GameAuthoredWorldSourceRepository worldSourceRepository; + private final GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository; + private final TransactionTemplate reservationTransaction; + private final String workloadNamespace; + + public SelectedDraftPublicationAdmissionService( + DSLContext dsl, + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, + WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, + String workloadNamespace) { + this( + transactionManager, + accountClient, + freezeClient, + inventoryClient, + worldClient, + worldSourceIntakeClient, + new GameAuthoredWorldSourceRepository(Objects.requireNonNull(dsl, "dsl")), + new GameAuthoredWorldSourceDeliveryRepository(dsl), + new SelectedDraftPublicationOwner(Objects.requireNonNull(dsl, "dsl")), + intent -> + new AuthoredDraftPublishSelectionRepository( + dsl, new DraftCommitCoordinatorRepository(dsl)) + .read( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId()) + .map(AuthoredDraftPublishSelectionRepository.SelectionSnapshot::selection), + workloadNamespace); + } + + SelectedDraftPublicationAdmissionService( + PlatformTransactionManager transactionManager, + AccountPublicationAuthorizationReadClient accountClient, + WorldSelectedDraftPublicationFreezeClient freezeClient, + WorldSelectedPublicationArtifactInventoryClient inventoryClient, + WorldPublishedStartLocationClient worldClient, + WorldAuthoredSourceIntakeClient worldSourceIntakeClient, + GameAuthoredWorldSourceRepository worldSourceRepository, + GameAuthoredWorldSourceDeliveryRepository worldSourceDeliveryRepository, + SelectedDraftPublicationOwner owner, + SelectionReader selectionReader, + String workloadNamespace) { + this.accountClient = Objects.requireNonNull(accountClient, "accountClient"); + this.worldClient = Objects.requireNonNull(worldClient, "worldClient"); + this.freezeClient = Objects.requireNonNull(freezeClient, "freezeClient"); + this.inventoryClient = Objects.requireNonNull(inventoryClient, "inventoryClient"); + this.worldSourceIntakeClient = + Objects.requireNonNull(worldSourceIntakeClient, "worldSourceIntakeClient"); + this.worldSourceRepository = + Objects.requireNonNull(worldSourceRepository, "worldSourceRepository"); + this.worldSourceDeliveryRepository = + Objects.requireNonNull(worldSourceDeliveryRepository, "worldSourceDeliveryRepository"); + this.selectionReader = Objects.requireNonNull(selectionReader, "selectionReader"); + this.owner = Objects.requireNonNull(owner, "owner"); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Workload namespace must be one canonical DNS label"); + } + this.workloadNamespace = workloadNamespace; + this.reservationTransaction = + new TransactionTemplate(Objects.requireNonNull(transactionManager, "transactionManager")); + this.reservationTransaction.setName("selected-draft-publication-reservation"); + this.reservationTransaction.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED); + this.reservationTransaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + this.reservationTransaction.setReadOnly(false); + } + + /** + * Verifies the retained selection, authenticates Account HELD, freezes World, and reads the exact + * selector and complete source receipt before reserving locally. All owner reads complete outside + * SQL. + */ + public SelectedDraftPublicationOwner.Reservation admitAndReserve( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding) { + requireNoAmbientTransaction(); + Objects.requireNonNull(intent, "intent"); + Objects.requireNonNull(accountBinding, "accountBinding"); + AuthoredDraftPublishSelection selection = + selectionReader + .read(intent) + .orElseThrow( + () -> new IllegalStateException("SELECTED_PUBLICATION_SELECTION_UNAVAILABLE")); + requireRequestIdentity(intent, accountBinding, selection); + + AccountPublicationAuthorizationReadEvidence.Request accountReadRequest = + AccountPublicationAuthorizationReadEvidence.Request.create( + workloadNamespace, accountBinding); + AccountPublicationAuthorizationReadEvidence accountEvidence = + accountClient.read(accountReadRequest); + requireExactAccountReadback(accountReadRequest, accountBinding, accountEvidence); + + var freezeRequest = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + accountEvidence.request().binding()); + var freeze = freezeClient.begin(freezeRequest); + if (freeze == null + || !freezeRequest.equals(freeze.request()) + || !freezeRequest.equals(freeze.acknowledgement().request())) { + throw new IllegalStateException( + "World publication freeze readback differs from the exact request"); + } + var acknowledgement = freeze.acknowledgement(); + var inventory = inventoryClient.read(freeze); + if (inventory == null + || !freeze.request().equals(inventory.freezeEvidence().request()) + || !freeze.acknowledgement().equals(inventory.freezeEvidence().acknowledgement())) { + throw new IllegalStateException( + "World inventory readback differs from exact acknowledged freeze"); + } + var worldRequest = + new WorldPublishedStartLocationEvidence.Request( + workloadNamespace, + selection.target().canonicalTenantId(), + selection.target().canonicalVersionId(), + acknowledgement.intakeRequestId(), + acknowledgement.publicationFence(), + intent.publishRequestId(), + freezeRequest.requestDigest(), + acknowledgement.versionStateEpoch(), + PublicationDigestRequestBinding.full( + intent.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + intent.publishRequestId()) + .derivedWorkflowIdentity(), + acknowledgement.appliedCommitId(), + acknowledgement.contentDigest(), + acknowledgement.digestSchemaVersion(), + selection + .selectedCommit() + .affectedUnits(DraftCommitBinding.Owner.WORLD_MANAGEMENT) + .stream() + .map( + unit -> + new WorldPublishedStartLocationEvidence.OwnedAffectedTuple( + unit.owner().name(), + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch())) + .toList()); + WorldPublishedStartLocationEvidence worldEvidence = worldClient.read(worldRequest); + requireExactWorldReadback(worldRequest, worldEvidence); + new GameDesignPublicationOperationBinding( + accountEvidence.request().binding(), worldEvidence, inventory); + SelectedDraftTemplateWorldSourceAssociation.SourceRead worldSourceRead = + readAndVerifyWorldSource(worldEvidence, selection.target()); + + return Objects.requireNonNull( + reservationTransaction.execute( + status -> + owner.reserve( + intent, + accountEvidence.request().binding(), + worldEvidence, + inventory, + worldSourceRead)), + "Selected Draft publication reservation returned no result"); + } + + private SelectedDraftTemplateWorldSourceAssociation.SourceRead readAndVerifyWorldSource( + WorldPublishedStartLocationEvidence worldEvidence, + DraftCommitBinding.TargetProof selectedTarget) { + var selected = worldEvidence.request(); + java.util.UUID readRequestId = java.util.UUID.randomUUID(); + while (readRequestId.equals(selected.intakeRequestId())) { + readRequestId = java.util.UUID.randomUUID(); + } + var request = + new ByIdReadRequest( + 1, + selected.targetNamespace(), + readRequestId, + selected.intakeRequestId(), + selected.canonicalTenantId()); + var receipt = worldSourceIntakeClient.readById(request); + var worldRead = new SelectedDraftTemplateWorldSourceAssociation.SourceRead(request, receipt); + var source = + worldSourceRepository + .read( + receipt.sourceOperationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + selected.targetNamespace()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_GD_RECORD_UNAVAILABLE")); + var delivery = + worldSourceDeliveryRepository + .read(receipt.sourceOperationId()) + .orElseThrow( + () -> new IllegalStateException("SELECTED_WORLD_SOURCE_DELIVERY_UNAVAILABLE")); + var expectedReceipt = + new CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + receipt.receiptDigest()); + if (!source.equals(receipt.source()) + || !delivery.source().equals(source) + || !delivery.request().targetNamespace().equals(selected.targetNamespace()) + || !delivery.request().intakeRequestId().equals(selected.intakeRequestId()) + || !delivery.request().canonicalTenantId().equals(selected.canonicalTenantId()) + || !delivery.request().worldSlug().equals(receipt.worldSlug()) + || !delivery.request().sourceOperationId().equals(receipt.sourceOperationId()) + || !delivery.request().expectedSourceEvidenceDigest().equals(receipt.sourceEvidenceDigest()) + || source.sourceGameRowId() != selectedTarget.sourceGameRowId() + || !source.sourceGameTenantKey().equals(selectedTarget.sourceGameTenantKey()) + || !source.provenanceKind().equals(selectedTarget.sourceProvenanceKind()) + || !WorldAuthoredSourceIntakeGrpcCodec.requestDigest(delivery.request()) + .equals(receipt.requestDigest()) + || delivery.acknowledgedReceipt().filter(ack -> !ack.equals(expectedReceipt)).isPresent()) { + throw new IllegalStateException( + "SELECTED_WORLD_SOURCE_OWNER_READBACK_CONFLICT: World, retained source, and original delivery differ"); + } + return worldRead; + } + + private void requireRequestIdentity( + AuthoredDraftPublishSelection.PublishIntent intent, + AccountPublicationAuthorizationBinding accountBinding, + AuthoredDraftPublishSelection selection) { + var intentFromBinding = accountBinding.input().selection().intent(); + var expectedIntent = + new AuthoredDraftPublishSelectionBinding.PublishIntent( + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + intent.expectedVersionStateEpoch(), + intent.notes(), + intent.selectedCommitRequestId(), + intent.selectedCommitId(), + intent.selectedCommitDigest()); + if (!expectedIntent.equals(intentFromBinding) + || !intent.equals(selection.intent()) + || !Arrays.equals( + selection.canonicalBytes(), accountBinding.input().selection().canonicalBytes())) { + throw new IllegalArgumentException( + "Account publication binding and retained selection must match the exact selected Draft intent"); + } + } + + @FunctionalInterface + interface SelectionReader { + Optional read( + AuthoredDraftPublishSelection.PublishIntent intent); + } + + private static void requireExactAccountReadback( + AccountPublicationAuthorizationReadEvidence.Request expectedRequest, + AccountPublicationAuthorizationBinding expectedBinding, + AccountPublicationAuthorizationReadEvidence evidence) { + if (evidence == null + || !expectedRequest.equals(evidence.request()) + || !java.util.Arrays.equals( + expectedBinding.canonicalBytes(), evidence.request().binding().canonicalBytes())) { + throw new IllegalStateException( + "Account publication authorization readback differs from the exact request"); + } + } + + private static void requireExactWorldReadback( + WorldPublishedStartLocationEvidence.Request expectedRequest, + WorldPublishedStartLocationEvidence evidence) { + if (evidence == null || !expectedRequest.equals(evidence.request())) { + throw new IllegalStateException( + "World publication selector readback differs from the exact request"); + } + } + + private static void requireNoAmbientTransaction() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Selected Draft publication owner reads require no ambient transaction"); + } + } +} diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java index d8689ca770..bc956259e1 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/accountservice/service/session/SelectedFullOwnerPublicationPostgresIntegrationTest.java @@ -28,10 +28,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.HexFormat; +import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; +import java.util.function.Supplier; import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestGrpcReceiver; import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService; @@ -58,7 +61,7 @@ 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.common.publication.AccountPublicationAuthorizationBinding; +import net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; @@ -82,8 +85,6 @@ import net.firedevops.firemud.gamedesign.publication.GameDesignSourceRepository; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceipt; import net.firedevops.firemud.gamedesign.publication.SelectedDraftGameLogicReceiptRepository; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftPublicationOwner; -import net.firedevops.firemud.gamedesign.publication.SelectedDraftTemplateWorldSourceAssociation; import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; import net.firedevops.firemud.gamedesign.repository.GameRepository; import net.firedevops.firemud.gamedesign.repository.PublishedReleaseBundleRepository; @@ -134,7 +135,9 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.test.util.ReflectionTestUtils; +import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.PostgreSQLContainer; import org.testcontainers.junit.jupiter.Container; @@ -173,11 +176,61 @@ class SelectedFullOwnerPublicationPostgresIntegrationTest { static final PostgreSQLContainer GAME_LOGIC_POSTGRES = new PostgreSQLContainer<>(TestContainerImages.postgres()); + private static final org.testcontainers.containers.Network ACCOUNT_NETWORK = + org.testcontainers.containers.Network.newNetwork(); + + @Container + static final PostgreSQLContainer ACCOUNT_POSTGRES = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Container + static final org.testcontainers.containers.GenericContainer ACCOUNT_REDIS = + new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) + .withNetwork(ACCOUNT_NETWORK) + .withNetworkAliases("selected-reservation-primary") + .withExposedPorts(6379) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always"); + + @Container + static final org.testcontainers.containers.GenericContainer ACCOUNT_REPLICA = + new org.testcontainers.containers.GenericContainer<>(TestContainerImages.redis()) + .withNetwork(ACCOUNT_NETWORK) + .dependsOn(ACCOUNT_REDIS) + .withCommand( + "redis-server", + "--bind", + "0.0.0.0", + "--protected-mode", + "no", + "--appendonly", + "yes", + "--appendfsync", + "always", + "--replicaof", + "selected-reservation-primary", + "6379"); + @TempDir Path temporary; @Test void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchemaFourBundle() throws Exception { + var diagnostics = new SettlementDiagnostics(); + diagnostics.logPostgres("game-design", GDS_POSTGRES); + diagnostics.logPostgres("world-management", WORLD_POSTGRES); + diagnostics.logPostgres("entity-management", ENTITY_POSTGRES); + diagnostics.logPostgres("automation-scripting", AUTOMATION_POSTGRES); + diagnostics.logPostgres("game-logic", GAME_LOGIC_POSTGRES); + diagnostics.logPostgres("account", ACCOUNT_POSTGRES); Store gds = store("game-design", "selected_full_gds", GDS_POSTGRES, false); Store world = store("world-management", "selected_full_world", WORLD_POSTGRES, false); Store entity = store("entity-management", "selected_full_entity", ENTITY_POSTGRES, true); @@ -189,9 +242,19 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema var worldSource = registerControlledWorldSource(gds, draft.target()); DraftCommitBinding commit = selectedCommit(gds, draft.target()); applyGameDesignCommit(gds, commit); + var delivery = + new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository( + gds.dsl()) + .read(worldSource.operationId()) + .orElseThrow(); var worldGraph = WorldSelectedFullPublicationEvidenceFixture.applyGraph( - world.dsl(), world.transactions(), NAMESPACE, commit, worldSource); + world.dsl(), + world.transactions(), + NAMESPACE, + commit, + worldSource, + delivery.request().intakeRequestId()); completeGameDesignCommit(gds, commit, worldGraph.applied()); String publishRequestId = "selected-full-" + UUID.randomUUID(); @@ -213,489 +276,599 @@ void actualSelectedWorldFourAndParticipantOwnersProduceAndReadBackCompleteSchema gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())) .reserve(intent) .selection()); - var worldOwners = - WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( - world.dsl(), - world.transactions(), - NAMESPACE, - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()), - worldGraph, - SelectedFullOwnerPublicationPostgresIntegrationTest::controlledAccountBinding); - assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); - assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); - assertThat(worldOwners.graphBytes()).isNotEmpty(); - assertThat(worldOwners.inventoryEvidence().freezeEvidence()) - .isEqualTo(worldOwners.freezeEvidence()); - - var sourceScopeActor = UUID.randomUUID(); - var entityAuthorization = - selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor); - var entityWorldRead = - SelectedOwnerWorldInventoryReadEvidence.create( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()); - var entityInputs = - new SelectedOwnerEmptySourceInputs( - entityAuthorization, - new SelectedOwnerWorldInventoryReadEvidence( - entityWorldRead, worldOwners.inventoryEvidence())); - var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); - var entityReceipt = - entityRepository.retainFresh( - entityInputs, - EntityEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())); - assertThat( - entityRepository - .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(entityReceipt.canonicalBytes()); - assertThat( - entityRepository - .retainFresh( - entityInputs, - EntityEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())) - .canonicalBytes()) - .containsExactly(entityReceipt.canonicalBytes()); - - var automationAuthorization = - selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor); - var automationWorldRead = - SelectedOwnerWorldInventoryReadEvidence.create( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()); - var automationInputs = - new SelectedOwnerEmptySourceInputs( - automationAuthorization, - new SelectedOwnerWorldInventoryReadEvidence( - automationWorldRead, worldOwners.inventoryEvidence())); - var automationRepository = new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); - var automationReceipt = - automationRepository.retainFresh( - automationInputs, - net.firedevops.firemud.common.automation.sourceintake - .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())); - assertThat( - automationRepository - .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId()) - .orElseThrow() - .canonicalBytes()) - .containsExactly(automationReceipt.canonicalBytes()); - assertThat( - automationRepository - .retainFresh( - automationInputs, - net.firedevops.firemud.common.automation.sourceintake - .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( - NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())) - .canonicalBytes()) - .containsExactly(automationReceipt.canonicalBytes()); - - var synchronizedSources = - new GameDesignSourceRepository(gds.dsl()) - .readSynchronized(draft.target(), commit.commitId()) - .orElseThrow(); - assertThat(synchronizedSources.command().definitions()).isEmpty(); - var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow(); - assertThat(gameplaySnapshot.manifest().families().get(GameplayRuleManifest.Family.COMMANDS)) - .extracting(GameplayRuleManifest.Definition::key) - .containsExactly("LOOK"); - var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); - var glAuthorization = - new GameLogicIntakeAuthorizationBinding( - UUID.randomUUID(), - UUID.randomUUID(), - UUID.randomUUID(), - sourceScopeActor, - gameplaySource, - controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId())); - var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization); - var glTerminal = - GameLogicGameplayRuleIntakeTerminal.retained( - glOperation, - gameplaySource.canonicalBytes(), - gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); - var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); - gameLogic - .write() - .execute( - ignored -> { - glOwner.lockOperation(glAuthorization.operationId()); - glOwner.insertTerminal(glTerminal); - return null; - }); - var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); - assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); - - var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl()); - var glReceiptCandidate = - new SelectedDraftGameLogicReceipt( - selection, - glAuthorization, - new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal)); - var glReceipt = - gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate)); - assertThat( - selectedReceiptRepository - .readForPublication( - PublicationDigestRequestBinding.full( - draft.target().canonicalTenantId().toString(), - Long.toString(draft.version().getId()), - publishRequestId)) - .orElseThrow() - .receipt() - .canonicalBytes()) - .containsExactly(glReceipt.receipt().canonicalBytes()); - - var selectionBinding = - AuthoredDraftPublishSelectionBinding.fromStored( - selection.canonicalJson(), selection.digest()); - var accountBinding = worldOwners.accountBinding(); - var templateSourceRead = - new SelectedDraftTemplateWorldSourceAssociation.SourceRead( - worldOwners.sourceReadRequest(), worldOwners.sourceReadReceipt()); - var selectedOwnerReservation = - gds.write() - .execute( - ignored -> - new SelectedDraftPublicationOwner(gds.dsl()) - .reserve( - intent, - accountBinding, - worldOwners.startLocationEvidence(), - worldOwners.inventoryEvidence(), - templateSourceRead)); - assertThat(selectedOwnerReservation.selection().canonicalBytes()) - .containsExactly(selectionBinding.canonicalBytes()); - - Long gdsBundleBefore = - gds.dsl() - .fetchSingle( - "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", - draft.version().getTenantId(), - draft.version().getId()) - .get(0, Long.class); - assertThat(gdsBundleBefore).isZero(); - - ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); - Server entityServer = null; - Server automationServer = null; - Server gameLogicServer = null; - Throwable bodyFailure = null; - try { - entityServer = - ownerServer( - pki, - "entity-management-service", - new EntitySelectedEmptyPublicationDigestGrpcReceiver( - new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository), - NAMESPACE, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); - automationServer = - ownerServer( - pki, - "automation-scripting-service", - new AutomationSelectedEmptyPublicationDigestGrpcReceiver( - new AutomationSelectedEmptyPublicationDigestService( - NAMESPACE, automationRepository), - NAMESPACE, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); - gameLogicServer = - ownerServer( - pki, - "game-logic-service", - new GameLogicGrpcService( + try (var accountFixture = + new AccountControlUiOriginalOrderFixture( + ACCOUNT_POSTGRES.getJdbcUrl(), + ACCOUNT_POSTGRES.getUsername(), + ACCOUNT_POSTGRES.getPassword(), + ACCOUNT_REDIS.getHost(), + ACCOUNT_REDIS.getMappedPort(6379), + temporary.resolve("account-original"), + draft.target().canonicalTenantId())) { + var issuedCreator = accountFixture.issueCreator(); + var accountSources = issuedCreator.sources(); + var publicationPki = new ProofPki(temporary.resolve("fresh-world-begin-pki")); + var publicationAuthorization = + authenticatedAccountPublicationOrder( + gds, + issuedCreator, + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + publicationPki); + var worldOwners = + freshAuthenticatedWorldFreeze( + gds, + world, + accountSources.dsl, + accountSources.manager, + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()), + worldGraph, + publicationAuthorization, + publicationPki); + assertThat(worldOwners.selectedWorldDigest().digestSchemaVersion()).isEqualTo(4); + assertThat(worldOwners.appliedResultBytes()).isNotEmpty(); + assertThat(worldOwners.graphBytes()).isNotEmpty(); + assertThat(worldOwners.inventoryEvidence().freezeEvidence()) + .isEqualTo(worldOwners.freezeEvidence()); + + var sourceScopeActor = UUID.randomUUID(); + var entityAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.ENTITY_MANAGEMENT, sourceScopeActor); + var entityWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence()); + var entityInputs = + new SelectedOwnerEmptySourceInputs( + entityAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + entityWorldRead, worldOwners.inventoryEvidence())); + var entityRepository = new EntityEmptySelectedSourceIntakeRepository(entity.dsl()); + var entityReceipt = + entityRepository.retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())); + assertThat( + entityRepository + .read(entityReceipt.targetNamespace(), entityReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + assertThat( + entityRepository + .retainFresh( + entityInputs, + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, entityAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(entityReceipt.canonicalBytes()); + + var automationAuthorization = + selectedOwnerAuthorization(gds, selection, Owner.AUTOMATION_SCRIPTING, sourceScopeActor); + var automationWorldRead = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence()); + var automationInputs = + new SelectedOwnerEmptySourceInputs( + automationAuthorization, + new SelectedOwnerWorldInventoryReadEvidence( + automationWorldRead, worldOwners.inventoryEvidence())); + var automationRepository = + new AutomationEmptySelectedSourceIntakeRepository(automation.dsl()); + var automationReceipt = + automationRepository.retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())); + assertThat( + automationRepository + .read(automationReceipt.targetNamespace(), automationReceipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + assertThat( + automationRepository + .retainFresh( + automationInputs, + net.firedevops.firemud.common.automation.sourceintake + .AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, automationAuthorization, worldOwners.freezeEvidence())) + .canonicalBytes()) + .containsExactly(automationReceipt.canonicalBytes()); + + var synchronizedSources = + new GameDesignSourceRepository(gds.dsl()) + .readSynchronized(draft.target(), commit.commitId()) + .orElseThrow(); + assertThat(synchronizedSources.command().definitions()).isEmpty(); + var gameplaySnapshot = synchronizedSources.gameplayEvidence().orElseThrow(); + assertThat(gameplaySnapshot.manifest().families().get(GameplayRuleManifest.Family.COMMANDS)) + .extracting(GameplayRuleManifest.Definition::key) + .containsExactly("LOOK"); + var gameplaySource = new GameplayRuleSelectedSource(gameplaySnapshot.canonicalJson()); + var glAuthorization = + new GameLogicIntakeAuthorizationBinding( + UUID.randomUUID(), + UUID.randomUUID(), + UUID.randomUUID(), + sourceScopeActor, + gameplaySource, + controlledAccountSources(sourceScopeActor, draft.target().canonicalTenantId())); + var glOperation = new GameLogicGameplayRuleIntakeOperation(NAMESPACE, glAuthorization); + var glTerminal = + GameLogicGameplayRuleIntakeTerminal.retained( + glOperation, + gameplaySource.canonicalBytes(), + gameplaySource.manifest().canonicalJson().getBytes(StandardCharsets.UTF_8)); + var glOwner = new GameLogicGameplayRuleIntakeRepository(gameLogic.dsl()); + gameLogic + .write() + .execute( + ignored -> { + glOwner.lockOperation(glAuthorization.operationId()); + glOwner.insertTerminal(glTerminal); + return null; + }); + var committedGlTerminal = glOwner.findTerminal(glAuthorization.operationId()).orElseThrow(); + assertThat(committedGlTerminal.canonicalBytes()).containsExactly(glTerminal.canonicalBytes()); + + var selectedReceiptRepository = new SelectedDraftGameLogicReceiptRepository(gds.dsl()); + var glReceiptCandidate = + new SelectedDraftGameLogicReceipt( + selection, + glAuthorization, + new AccountGameLogicIntakeSettlementEvidence(committedGlTerminal)); + var glReceipt = + gds.write().execute(ignored -> selectedReceiptRepository.retain(glReceiptCandidate)); + assertThat( + selectedReceiptRepository + .readForPublication( + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId)) + .orElseThrow() + .receipt() + .canonicalBytes()) + .containsExactly(glReceipt.receipt().canonicalBytes()); + + var selectionBinding = + AuthoredDraftPublishSelectionBinding.fromStored( + selection.canonicalJson(), selection.digest()); + var accountBinding = worldOwners.accountBinding(); + + Long gdsBundleBefore = + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class); + assertThat(gdsBundleBefore).isZero(); + + ProofPki pki = new ProofPki(temporary.resolve("selected-full-pki")); + Server accountServer = null; + Server worldServer = null; + Server entityServer = null; + Server automationServer = null; + Server gameLogicServer = null; + // This case recovers the exact already-committed World freeze. Mutable owner reads must not + // repeat. + var replaySelection = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient + .class); + var replayVersion = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient.class); + var replayAccount = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient + .class); + var replaySource = + org.mockito.Mockito.mock( + net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient.class); + Throwable bodyFailure = null; + try { + accountServer = + ownerServer( + pki, + "account-service", + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(accountSources.dsl), + accountSources.manager, + NAMESPACE), + NAMESPACE)); + var worldReaders = + WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( + world.dsl(), + world.transactions(), + NAMESPACE, + replaySelection, + replayVersion, + replayAccount, + replaySource); + worldServer = + ownerServer( + pki, + "world-management-service", + worldReaders.toArray(io.grpc.BindableService[]::new)); + entityServer = + ownerServer( + pki, + "entity-management-service", + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + new EntitySelectedEmptyPublicationDigestService(NAMESPACE, entityRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + automationServer = + ownerServer( + pki, + "automation-scripting-service", + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + new AutomationSelectedEmptyPublicationDigestService( + NAMESPACE, automationRepository), + NAMESPACE, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry())); + gameLogicServer = + ownerServer( + pki, + "game-logic-service", + new GameLogicGrpcService( + null, + null, + null, + null, + null, + null, + new GameLogicDraftDesignDigestServiceImpl( + new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)), + null, + new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), + new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); + + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAccountService(loopback(accountServer)); + endpoints.setWorldManagementService(loopback(worldServer)); + endpoints.setEntityManagementService(loopback(entityServer)); + endpoints.setAutomationScriptingService(loopback(automationServer)); + endpoints.setGameLogicService(loopback(gameLogicServer)); + var channelFactory = new GrpcChannelFactory(); + try (var accountClient = + new net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var freezeClient = + new net.firedevops.firemud.common.publication + .WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var inventoryClient = + new net.firedevops.firemud.common.publication + .WorldSelectedPublicationArtifactInventoryClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var selectorClient = + new net.firedevops.firemud.common.world.WorldPublishedStartLocationClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var sourceClient = + new net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient( + endpoints, pki.client("game-design-service"), channelFactory, NAMESPACE); + var entityClient = + new ReadyEntityManagementClient( + endpoints, pki.client("game-design-service"), channelFactory); + var automationClient = + new ReadyAutomationScriptingClient( + endpoints, pki.client("game-design-service"), channelFactory); + var gameLogicClient = + new ReadyGameLogicClient( + endpoints, pki.client("game-design-service"), channelFactory)) { + accountClient.init(); + freezeClient.init(); + inventoryClient.init(); + selectorClient.init(); + sourceClient.init(); + var admission = + new net.firedevops.firemud.gamedesign.publication + .SelectedDraftPublicationAdmissionService( + gds.dsl(), + gds.transactions(), + accountClient, + freezeClient, + inventoryClient, + selectorClient, + sourceClient, + NAMESPACE); + var selectedOwnerReservation = admission.admitAndReserve(intent, accountBinding); + assertThat(selectedOwnerReservation.selection().canonicalBytes()) + .containsExactly(selectionBinding.canonicalBytes()); + var reservationReplay = admission.admitAndReserve(intent, accountBinding); + assertThat(reservationReplay.operation().canonicalBytes()) + .containsExactly(selectedOwnerReservation.operation().canonicalBytes()); + org.mockito.Mockito.verifyNoInteractions( + replaySelection, replayVersion, replayAccount, replaySource); + ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); + entityClient.connect(); + automationClient.connect(); + gameLogicClient.connect(); + var gate = + new PublishGateServiceImpl( null, null, + entityClient, + gameLogicClient, + automationClient, + gds.dsl(), + gds.transactions(), + NAMESPACE); + VersionDto versionDto = versionDto(draft.version()); + var publicationRequest = + PublicationDigestRequestBinding.full( + draft.target().canonicalTenantId().toString(), + Long.toString(draft.version().getId()), + publishRequestId); + var participantDigests = + gate.collectSelectedFullVersionParticipantDigests( + versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity()); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::participantKey) + .containsExactly( + "WORLD_MANAGEMENT", + "ENTITY_MANAGEMENT", + "GAME_LOGIC", + "AUTOMATION_SCRIPTING", + "GAME_DESIGN_CONTROL_PLANE"); + assertThat(participantDigests) + .extracting(PublishParticipantDigestDto::digestSchemaVersion) + .containsExactly(4, 3, 1, 6, 2); + assertThat(participantDigests) + .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) + .singleElement() + .satisfies( + digest -> + assertThat(digest.contentDigest()) + .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); + assertThat(participantDigests) + .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) + .singleElement() + .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); + gate.assertSelectedGatePassed(versionDto, participantDigests); + + var altered = new ArrayList<>(participantDigests); + int automationIndex = 3; + var validAutomation = altered.get(automationIndex); + altered.set( + automationIndex, + new PublishParticipantDigestDto( + validAutomation.participantKey(), + validAutomation.scopeValue(), + validAutomation.baseVersionId(), + validAutomation.appliedCommitId(), + validAutomation.contentDigest(), + 5, + validAutomation.abilitySchemaDigest(), + validAutomation.errorCode(), + validAutomation.errorMessage())); + assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) + .isInstanceOf(PublishGateFailureException.class) + .satisfies( + failure -> + assertThat(((PublishGateFailureException) failure).failureCode()) + .isEqualTo(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA)); + + var releaseService = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()); + var controlledEmptyManifest = controlledEmptyManifest(); + var artifactRepository = + new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository( + gds.dsl()); + var versions = new VersionRepository(gds.dsl()); + var artifactService = + new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl( + artifactRepository, null, + versions, null, null, null, - new GameLogicDraftDesignDigestServiceImpl( - new GameLogicPublicationSourceReadService(glOwner, NAMESPACE)), null, - new io.micrometer.core.instrument.simple.SimpleMeterRegistry(), - new net.firedevops.firemud.common.security.PublicationReadGuard(NAMESPACE))); - - var endpoints = new ServiceEndpointsProperties(); - endpoints.setEntityManagementService(loopback(entityServer)); - endpoints.setAutomationScriptingService(loopback(automationServer)); - endpoints.setGameLogicService(loopback(gameLogicServer)); - var channelFactory = new GrpcChannelFactory(); - try (var entityClient = - new ReadyEntityManagementClient( - endpoints, pki.client("game-design-service"), channelFactory); - var automationClient = - new ReadyAutomationScriptingClient( - endpoints, pki.client("game-design-service"), channelFactory); - var gameLogicClient = - new ReadyGameLogicClient( - endpoints, pki.client("game-design-service"), channelFactory)) { - ReflectionTestUtils.setField(gameLogicClient, "workloadNamespace", NAMESPACE); - entityClient.connect(); - automationClient.connect(); - gameLogicClient.connect(); - var gate = - new PublishGateServiceImpl( - null, - null, - entityClient, - gameLogicClient, - automationClient, - gds.dsl(), - gds.transactions(), - NAMESPACE); - VersionDto versionDto = versionDto(draft.version()); - var publicationRequest = - PublicationDigestRequestBinding.full( - draft.target().canonicalTenantId().toString(), - Long.toString(draft.version().getId()), - publishRequestId); - var participantDigests = - gate.collectSelectedFullVersionParticipantDigests( - versionDto, publicationRequest, publicationRequest.derivedWorkflowIdentity()); - assertThat(participantDigests) - .extracting(PublishParticipantDigestDto::participantKey) - .containsExactly( - "WORLD_MANAGEMENT", - "ENTITY_MANAGEMENT", - "GAME_LOGIC", - "AUTOMATION_SCRIPTING", - "GAME_DESIGN_CONTROL_PLANE"); - assertThat(participantDigests) - .extracting(PublishParticipantDigestDto::digestSchemaVersion) - .containsExactly(4, 3, 1, 6, 2); - assertThat(participantDigests) - .filteredOn(digest -> "WORLD_MANAGEMENT".equals(digest.participantKey())) - .singleElement() - .satisfies( - digest -> - assertThat(digest.contentDigest()) - .isEqualTo(worldOwners.selectedWorldDigest().contentDigest())); - assertThat(participantDigests) - .filteredOn(digest -> "GAME_LOGIC".equals(digest.participantKey())) - .singleElement() - .satisfies(digest -> assertThat(digest.abilitySchemaDigest()).startsWith("sha256:")); - gate.assertSelectedGatePassed(versionDto, participantDigests); - - var altered = new ArrayList<>(participantDigests); - int automationIndex = 3; - var validAutomation = altered.get(automationIndex); - altered.set( - automationIndex, - new PublishParticipantDigestDto( - validAutomation.participantKey(), - validAutomation.scopeValue(), - validAutomation.baseVersionId(), - validAutomation.appliedCommitId(), - validAutomation.contentDigest(), - 5, - validAutomation.abilitySchemaDigest(), - validAutomation.errorCode(), - validAutomation.errorMessage())); - assertThatThrownBy(() -> gate.assertSelectedGatePassed(versionDto, altered)) - .isInstanceOf(PublishGateFailureException.class) - .satisfies( - failure -> - assertThat(((PublishGateFailureException) failure).failureCode()) - .isEqualTo(PublishGateFailureCode.UNSUPPORTED_DIGEST_SCHEMA)); - - var releaseService = - new PublishedReleaseBundleServiceImpl( - new PublishedReleaseBundleRepository(gds.dsl()), - new VersionRepository(gds.dsl()), - new ObjectMapper()); - var controlledEmptyManifest = controlledEmptyManifest(); - var artifactRepository = - new net.firedevops.firemud.gamedesign.repository.VersionAssetArtifactRepository( - gds.dsl()); - var versions = new VersionRepository(gds.dsl()); - var artifactService = - new net.firedevops.firemud.gamedesign.service.impl.VersionAssetArtifactServiceImpl( - artifactRepository, - null, - versions, - null, - null, - null, - null, - null, - new ObjectMapper()); - var assetPublication = - new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository( - gds.dsl()); - var exportSnapshot = - gds.write() - .execute( - ignored -> - assetPublication.freezeOrReadSnapshot( - versionDto.tenantId(), versionDto.versionNumber())); - assertThat(exportSnapshot.items()).isEmpty(); - gds.write() - .execute( - ignored -> - artifactService.stageExport( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - publicationRequest.derivedWorkflowIdentity())); - var candidateService = - new net.firedevops.firemud.gamedesign.service.impl - .VersionAssetExportCandidateServiceImpl( - versions, - new GameRepository(gds.dsl()), - new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( - gds.dsl()), - artifactRepository, - assetPublication, - gds.transactions(), - new ObjectMapper()); - // Controlled delivery origin and manifest metadata; no object-store or public delivery - // proof. - var candidate = - new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate( - controlledEmptyManifest, "https://controlled.invalid/assets"); - assertThat( - candidateService.recordExportCandidate( - versionDto.tenantId(), versionDto.versionNumber(), candidate)) - .isEqualTo(candidate); - assertThat( - candidateService.readExportCandidate( - versionDto.tenantId(), versionDto.versionNumber())) - .isEqualTo(candidate); - assertThatThrownBy( - () -> - gds.write() - .execute( - ignored -> - releaseService.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - altered, - worldOwners.startLocationEvidence()))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("Selected-full release requires the exact 4/3/1/6/2"); - assertThat( - gds.dsl() - .fetchSingle( - "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", - draft.version().getTenantId(), - draft.version().getId()) - .get(0, Long.class)) - .isZero(); - - PublishedReleaseBundleService releaseOwner = releaseService; - var written = - gds.write() - .execute( - ignored -> { - String workflow = publicationRequest.derivedWorkflowIdentity(); - var exported = - artifactService.markExportedUnattested( - versionDto.tenantId(), - versionDto.id(), - versionDto.versionNumber(), - workflow, - controlledEmptyManifest); - var result = + null, + new ObjectMapper()); + var assetPublication = + new net.firedevops.firemud.gamedesign.repository.VersionAssetPublicationRepository( + gds.dsl()); + var exportSnapshot = + gds.write() + .execute( + ignored -> + assetPublication.freezeOrReadSnapshot( + versionDto.tenantId(), versionDto.versionNumber())); + assertThat(exportSnapshot.items()).isEmpty(); + gds.write() + .execute( + ignored -> + artifactService.stageExport( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + publicationRequest.derivedWorkflowIdentity())); + var candidateService = + new net.firedevops.firemud.gamedesign.service.impl + .VersionAssetExportCandidateServiceImpl( + versions, + new GameRepository(gds.dsl()), + new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( + gds.dsl()), + artifactRepository, + assetPublication, + gds.transactions(), + new ObjectMapper()); + // Controlled delivery origin and manifest metadata; no object-store or public delivery + // proof. + var candidate = + new net.firedevops.firemud.gamedesign.service.FrozenAssetExportCandidate( + controlledEmptyManifest, "https://controlled.invalid/assets"); + assertThat( + candidateService.recordExportCandidate( + versionDto.tenantId(), versionDto.versionNumber(), candidate)) + .isEqualTo(candidate); + assertThat( + candidateService.readExportCandidate( + versionDto.tenantId(), versionDto.versionNumber())) + .isEqualTo(candidate); + assertThatThrownBy( + () -> + gds.write() + .execute( + ignored -> + releaseService.createFullVersionBundle( + versionDto, + publicationRequest.derivedWorkflowIdentity(), + controlledEmptyManifest, + "controlled-generation-input", + altered, + worldOwners.startLocationEvidence()))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Selected-full release requires the exact 4/3/1/6/2"); + assertThat( + gds.dsl() + .fetchSingle( + "SELECT count(*) FROM published_release_bundle WHERE tenant_id = ? AND version_id = ?", + draft.version().getTenantId(), + draft.version().getId()) + .get(0, Long.class)) + .isZero(); + + PublishedReleaseBundleService releaseOwner = releaseService; + var written = + gds.write() + .execute( + ignored -> { + String workflow = publicationRequest.derivedWorkflowIdentity(); + var exported = + artifactService.markExportedUnattested( + versionDto.tenantId(), + versionDto.id(), + versionDto.versionNumber(), + workflow, + controlledEmptyManifest); + var result = + releaseOwner.createFullVersionBundle( + versionDto, + workflow, + controlledEmptyManifest, + "controlled-generation-input", + participantDigests, + worldOwners.startLocationEvidence()); + var version = + versions + .findByTenantIdAndIdForUpdate( + versionDto.tenantId(), versionDto.id()) + .orElseThrow(); + version.setVersionState(VersionLifecycleState.PUBLISHED); + version.setVersionStateEpoch( + Math.addExact(version.getVersionStateEpoch(), 1L)); + versions.save(version); + artifactService.markPublished( + versionDto.tenantId(), + versionDto.id(), + exported.stateEpoch(), + workflow, + controlledEmptyManifest.manifestHash()); + var attempts = + new net.firedevops.firemud.gamedesign.repository + .PublishAttemptRepository(gds.dsl()); + var attempt = + attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); + attempt.setStatus( + net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); + attempts.save(attempt); + var operation = selectedOwnerReservation.operation(); + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()) + .seal( + operation.tenantKey(), + workflow, + operation.versionId(), + operation.selectionDigest(), + true); + return result; + }); + assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); + assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) + .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); + String committedBundleRow = bundleOwnerRow(gds, draft.version()); + var independentRead = + new PublishedReleaseBundleServiceImpl( + new PublishedReleaseBundleRepository(gds.dsl()), + new VersionRepository(gds.dsl()), + new ObjectMapper()) + .findPublishedReleaseBundle( + draft.version().getTenantId(), draft.version().getId()) + .orElseThrow(); + assertThat(independentRead).isEqualTo(written); + assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4"); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + + var replay = + gds.write() + .execute( + ignored -> releaseOwner.createFullVersionBundle( versionDto, - workflow, + publicationRequest.derivedWorkflowIdentity(), controlledEmptyManifest, "controlled-generation-input", participantDigests, - worldOwners.startLocationEvidence()); - var version = - versions - .findByTenantIdAndIdForUpdate(versionDto.tenantId(), versionDto.id()) - .orElseThrow(); - version.setVersionState(VersionLifecycleState.PUBLISHED); - version.setVersionStateEpoch( - Math.addExact(version.getVersionStateEpoch(), 1L)); - versions.save(version); - artifactService.markPublished( - versionDto.tenantId(), - versionDto.id(), - exported.stateEpoch(), - workflow, - controlledEmptyManifest.manifestHash()); - var attempts = - new net.firedevops.firemud.gamedesign.repository.PublishAttemptRepository( - gds.dsl()); - var attempt = - attempts.findByPublishWorkflowIdForUpdate(workflow).orElseThrow(); - attempt.setStatus( - net.firedevops.firemud.gamedesign.model.PublishAttemptStatus.SUCCEEDED); - attempts.save(attempt); - var operation = selectedOwnerReservation.operation(); - new net.firedevops.firemud.gamedesign.publication - .GameDesignPublicationOperationRepository(gds.dsl()) - .seal( - operation.tenantKey(), - workflow, - operation.versionId(), - operation.selectionDigest(), - true); - return result; - }); - assertThat(written.attestationSchemaVersion()).isEqualTo("v4"); - assertThat(written.participantDigests()).containsExactlyElementsOf(participantDigests); - assertThat(written.worldPublishedStartLocationEvidence().canonicalBytes()) - .containsExactly(worldOwners.startLocationEvidence().canonicalBytes()); - String committedBundleRow = bundleOwnerRow(gds, draft.version()); - var independentRead = - new PublishedReleaseBundleServiceImpl( - new PublishedReleaseBundleRepository(gds.dsl()), - new VersionRepository(gds.dsl()), - new ObjectMapper()) - .findPublishedReleaseBundle(draft.version().getTenantId(), draft.version().getId()) - .orElseThrow(); - assertThat(independentRead).isEqualTo(written); - assertThat(independentRead.attestationSchemaVersion()).isEqualTo("v4"); - assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); - - var replay = - gds.write() - .execute( - ignored -> - releaseOwner.createFullVersionBundle( - versionDto, - publicationRequest.derivedWorkflowIdentity(), - controlledEmptyManifest, - "controlled-generation-input", - participantDigests, - worldOwners.startLocationEvidence())); - assertThat(replay).isEqualTo(written); - assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + worldOwners.startLocationEvidence())); + assertThat(replay).isEqualTo(written); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + completeActualWorldAndAccountTerminals( + gds, + world, + accountSources.dsl, + accountSources.manager, + pki, + selectedOwnerReservation.operation(), + diagnostics); + assertThat(bundleOwnerRow(gds, draft.version())).isEqualTo(committedBundleRow); + } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; + } finally { + stopServers( + bodyFailure, + accountServer, + worldServer, + entityServer, + automationServer, + gameLogicServer); } - } catch (Exception failure) { - bodyFailure = failure; - throw failure; - } catch (Error failure) { - bodyFailure = failure; - throw failure; - } finally { - stopServers(bodyFailure, entityServer, automationServer, gameLogicServer); } } @Test void ownerServerCleanupAttemptsEveryServerAndSuppressesFailuresOnBodyFailure() throws InterruptedException { - Server entityServer = mock(Server.class); - Server automationServer = mock(Server.class); - Server gameLogicServer = mock(Server.class); + Server firstServer = mock(Server.class); + Server secondServer = mock(Server.class); + Server thirdServer = mock(Server.class); RuntimeException bodyFailure = new IllegalStateException("publication body failed"); - RuntimeException shutdownFailure = new IllegalStateException("entity shutdown failed"); - RuntimeException waitFailure = new IllegalStateException("automation wait failed"); - doThrow(shutdownFailure).when(entityServer).shutdownNow(); - when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); - when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); - when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); + RuntimeException shutdownFailure = new IllegalStateException("first shutdown failed"); + RuntimeException waitFailure = new IllegalStateException("second wait failed"); + doThrow(shutdownFailure).when(firstServer).shutdownNow(); + when(firstServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(secondServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); + when(thirdServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(false); Throwable thrown = catchThrowable( @@ -707,7 +880,7 @@ void ownerServerCleanupAttemptsEveryServerAndSuppressesFailuresOnBodyFailure() primaryFailure = failure; throw failure; } finally { - stopServers(primaryFailure, entityServer, automationServer, gameLogicServer); + stopServers(primaryFailure, firstServer, secondServer, thirdServer); } }); @@ -716,27 +889,27 @@ void ownerServerCleanupAttemptsEveryServerAndSuppressesFailuresOnBodyFailure() assertThat(bodyFailure.getSuppressed()[0].getCause()).isSameAs(shutdownFailure); assertThat(bodyFailure.getSuppressed()[1].getCause()).isSameAs(waitFailure); assertThat(bodyFailure.getSuppressed()[2].getMessage()) - .contains("game logic owner server did not terminate"); - var order = inOrder(entityServer, automationServer, gameLogicServer); - order.verify(entityServer).shutdownNow(); - order.verify(automationServer).shutdownNow(); - order.verify(gameLogicServer).shutdownNow(); - order.verify(entityServer).awaitTermination(5, TimeUnit.SECONDS); - order.verify(automationServer).awaitTermination(5, TimeUnit.SECONDS); - order.verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS); + .contains("Owner server 3 did not terminate"); + var order = inOrder(firstServer, secondServer, thirdServer); + order.verify(firstServer).shutdownNow(); + order.verify(secondServer).shutdownNow(); + order.verify(thirdServer).shutdownNow(); + order.verify(firstServer).awaitTermination(5, TimeUnit.SECONDS); + order.verify(secondServer).awaitTermination(5, TimeUnit.SECONDS); + order.verify(thirdServer).awaitTermination(5, TimeUnit.SECONDS); } @Test void ownerServerCleanupFailureFailsWhenPublicationBodySucceeded() throws InterruptedException { - Server entityServer = mock(Server.class); - Server automationServer = mock(Server.class); - Server gameLogicServer = mock(Server.class); - RuntimeException waitFailure = new IllegalStateException("entity wait failed"); - when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); - when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); - when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); - - assertThatThrownBy(() -> stopServers(null, entityServer, automationServer, gameLogicServer)) + Server firstServer = mock(Server.class); + Server secondServer = mock(Server.class); + Server thirdServer = mock(Server.class); + RuntimeException waitFailure = new IllegalStateException("first wait failed"); + when(firstServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(waitFailure); + when(secondServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(thirdServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + + assertThatThrownBy(() -> stopServers(null, firstServer, secondServer, thirdServer)) .isInstanceOf(AssertionError.class) .satisfies( failure -> { @@ -744,27 +917,27 @@ void ownerServerCleanupFailureFailsWhenPublicationBodySucceeded() throws Interru assertThat(failure.getSuppressed()[0].getCause()).isSameAs(waitFailure); }); - verify(entityServer).shutdownNow(); - verify(automationServer).shutdownNow(); - verify(gameLogicServer).shutdownNow(); - verify(entityServer).awaitTermination(5, TimeUnit.SECONDS); - verify(automationServer).awaitTermination(5, TimeUnit.SECONDS); - verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS); + verify(firstServer).shutdownNow(); + verify(secondServer).shutdownNow(); + verify(thirdServer).shutdownNow(); + verify(firstServer).awaitTermination(5, TimeUnit.SECONDS); + verify(secondServer).awaitTermination(5, TimeUnit.SECONDS); + verify(thirdServer).awaitTermination(5, TimeUnit.SECONDS); } @Test void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits() throws InterruptedException { - Server entityServer = mock(Server.class); - Server automationServer = mock(Server.class); - Server gameLogicServer = mock(Server.class); - InterruptedException interruption = new InterruptedException("entity wait interrupted"); - when(entityServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(interruption); - when(automationServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); - when(gameLogicServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + Server firstServer = mock(Server.class); + Server secondServer = mock(Server.class); + Server thirdServer = mock(Server.class); + InterruptedException interruption = new InterruptedException("first wait interrupted"); + when(firstServer.awaitTermination(5, TimeUnit.SECONDS)).thenThrow(interruption); + when(secondServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); + when(thirdServer.awaitTermination(5, TimeUnit.SECONDS)).thenReturn(true); try { - assertThatThrownBy(() -> stopServers(null, entityServer, automationServer, gameLogicServer)) + assertThatThrownBy(() -> stopServers(null, firstServer, secondServer, thirdServer)) .isInstanceOf(AssertionError.class) .satisfies( failure -> { @@ -772,14 +945,642 @@ void ownerServerCleanupRestoresInterruptAfterAttemptingAllTerminationWaits() assertThat(failure.getSuppressed()[0].getCause()).isSameAs(interruption); }); assertThat(Thread.currentThread().isInterrupted()).isTrue(); - verify(entityServer).awaitTermination(5, TimeUnit.SECONDS); - verify(automationServer).awaitTermination(5, TimeUnit.SECONDS); - verify(gameLogicServer).awaitTermination(5, TimeUnit.SECONDS); + verify(firstServer).awaitTermination(5, TimeUnit.SECONDS); + verify(secondServer).awaitTermination(5, TimeUnit.SECONDS); + verify(thirdServer).awaitTermination(5, TimeUnit.SECONDS); } finally { Thread.interrupted(); } } + /** Actual authenticated Account ordering consumes the real GDS immutable selection owner. */ + private static net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding + authenticatedAccountPublicationOrder( + Store gds, + AccountControlUiOriginalOrderFixture.IssuedCreator issued, + AuthoredDraftPublishSelectionBinding selection, + ProofPki pki) + throws Exception { + var reads = new java.util.concurrent.atomic.AtomicInteger(); + var unavailable = new java.util.concurrent.atomic.AtomicBoolean(true); + var selectionOwner = + new net.firedevops.firemud.gamedesign.draft + .GameDesignSelectedDraftPublicationReadGrpcService( + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())), + NAMESPACE); + Server gdsServer = + ownerServer(pki, "game-design-service", observedRead(selectionOwner, reads, unavailable)); + Server accountServer = null; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsServer)); + var channels = new GrpcChannelFactory(); + var sources = issued.sources(); + Throwable bodyFailure = null; + try (var selectionClient = + new net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE)) { + selectionClient.init(); + var repository = new AccountPublicationAuthorizationRepository(sources.dsl); + var owner = + new AccountSelectedDraftPublicationOrderService( + selectionClient, + new AccountPublicationAuthorizationService( + issued.actors(), sources.fences, repository), + NAMESPACE); + accountServer = + ownerServer( + pki, + "account-service", + new AccountSelectedDraftPublicationOrderGrpcService(owner, sources.terms, NAMESPACE)); + endpoints.setAccountService(loopback(accountServer)); + try (var client = + new net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + client.init(); + var request = + net.firedevops.firemud.common.publication.AccountSelectedPublicationOrderGrpcCodec + .Request.create(NAMESPACE, selection, issued.compact()); + var before = publicationOrderRows(sources.dsl); + assertThat(before.get("account_selected_publication_authorizations")).isEmpty(); + assertThat(before.get("account_selected_publication_sources")).isEmpty(); + assertThatThrownBy(() -> client.authorize(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); + assertThat(publicationOrderRows(sources.dsl)).isEqualTo(before); + assertThat(reads.get()).isEqualTo(1); + unavailable.set(false); + var created = client.authorize(request); + assertThat(created.input().selection().canonicalBytes()) + .containsExactly(selection.canonicalBytes()); + var committed = publicationOrderRows(sources.dsl); + assertThat(committed.get("account_selected_publication_authorizations")).hasSize(1); + assertThat(committed.get("account_selected_publication_sources")).isNotEmpty(); + assertThat(client.authorize(request).canonicalBytes()) + .containsExactly(created.canonicalBytes()); + assertThat(publicationOrderRows(sources.dsl)).isEqualTo(committed); + assertThat(reads.get()).isEqualTo(3); + assertThat( + sources + .dsl + .fetchSingle( + "SELECT count(*) FROM account_control_ui_issuance_operations WHERE status = 'COMMITTED'") + .get(0, Long.class)) + .isEqualTo(1L); + return created; + } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; + } finally { + stopServers(bodyFailure, accountServer, gdsServer); + } + } + + private static java.util.Map> publicationOrderRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + List.of( + "account_selected_publication_authorizations", + "account_selected_publication_sources", + "account_selected_publication_settlements", + "account_control_ui_issuance_operations")) { + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + table + " r ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + + /** Fresh World begin uses real owner reads before any World freeze attempt exists. */ + private static WorldSelectedFullPublicationEvidenceFixture.Result freshAuthenticatedWorldFreeze( + Store gds, + Store world, + org.jooq.DSLContext accountDsl, + org.springframework.transaction.PlatformTransactionManager accountTransactions, + AuthoredDraftPublishSelectionBinding selection, + WorldSelectedFullPublicationEvidenceFixture.AppliedGraph graph, + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding account, + ProofPki pki) + throws Exception { + var selectionCalls = new java.util.concurrent.atomic.AtomicInteger(); + var versionCalls = new java.util.concurrent.atomic.AtomicInteger(); + var heldCalls = new java.util.concurrent.atomic.AtomicInteger(); + var unavailableAccount = new java.util.concurrent.atomic.AtomicBoolean(true); + var unavailableGds = new java.util.concurrent.atomic.AtomicBoolean(); + var sources = + new net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository( + gds.dsl()); + Server gdsServer = + ownerServer( + pki, + "game-design-service", + observedRead( + new net.firedevops.firemud.gamedesign.draft + .GameDesignSelectedDraftPublicationReadGrpcService( + new AuthoredDraftPublishSelectionRepository( + gds.dsl(), new DraftCommitCoordinatorRepository(gds.dsl())), + NAMESPACE), + selectionCalls, + unavailableGds), + observedRead( + new net.firedevops.firemud.gamedesign.service.impl + .AuthoredWorldVersionStateGrpcService( + new net.firedevops.firemud.gamedesign.service.impl + .AuthoredWorldVersionStateService(gds.transactions(), sources), + NAMESPACE), + versionCalls, + unavailableGds), + new net.firedevops.firemud.gamedesign.service.impl.AuthoredWorldSourceReadGrpcService( + sources, NAMESPACE)); + Server accountServer = null; + Server worldServer = null; + Throwable bodyFailure = null; + try { + accountServer = + ownerServer( + pki, + "account-service", + observedRead( + new AccountPublicationAuthorizationReadGrpcService( + new AccountPublicationAuthorizationReadService( + new AccountPublicationAuthorizationRepository(accountDsl), + accountTransactions, + NAMESPACE), + NAMESPACE), + heldCalls, + unavailableAccount)); + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsServer)); + endpoints.setAccountService(loopback(accountServer)); + var channels = new GrpcChannelFactory(); + try (var selectionClient = + new net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var versionClient = + new net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var accountClient = + new net.firedevops.firemud.common.publication + .AccountPublicationAuthorizationReadClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE); + var sourceClient = + new net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + selectionClient.init(); + versionClient.init(); + accountClient.init(); + sourceClient.init(); + var handlers = + WorldSelectedFullPublicationEvidenceFixture.reservationReadEndpoints( + world.dsl(), + world.transactions(), + NAMESPACE, + selectionClient, + versionClient, + accountClient, + sourceClient); + worldServer = + ownerServer( + pki, "world-management-service", handlers.toArray(io.grpc.BindableService[]::new)); + endpoints.setWorldManagementService(loopback(worldServer)); + try (var freeze = + new net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + freeze.init(); + var intent = selection.intent(); + var request = + net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence + .Request.create( + NAMESPACE, + intent.canonicalTenantId(), + intent.canonicalVersionId(), + intent.publishRequestId(), + Long.parseLong(intent.expectedVersionStateEpoch()), + selection.digest().substring("sha256:".length()), + account); + var before = freezeOwnerRows(world.dsl()); + for (String empty : + List.of( + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + assertThat(before.get(empty)).as("no prior %s", empty).isEmpty(); + } + assertThat( + world + .dsl() + .fetchSingle( + "SELECT owner_freeze_phase FROM world_design_publication_fence_owner") + .get(0, String.class)) + .isEqualTo("OPEN"); + assertThatThrownBy(() -> freeze.begin(request)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.UNAVAILABLE)); + assertThat(freezeOwnerRows(world.dsl())).isEqualTo(before); + assertThat(selectionCalls.get()).isEqualTo(1); + assertThat(versionCalls.get()).isEqualTo(1); + assertThat(heldCalls.get()).isEqualTo(1); + unavailableAccount.set(false); + var created = freeze.begin(request); + assertThat(created.request()).isEqualTo(request); + assertThat(created.acknowledgement().ownerFreezePhase()) + .isEqualTo( + net.firedevops.firemud.common.publication + .WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN); + assertThat(selectionCalls.get()).isEqualTo(2); + assertThat(versionCalls.get()).isEqualTo(2); + assertThat(heldCalls.get()).isEqualTo(2); + var retained = + WorldSelectedFullPublicationEvidenceFixture.readCommittedFreeze( + world.dsl(), NAMESPACE, selection, graph, account, created); + var committed = freezeOwnerRows(world.dsl()); + for (String written : + List.of( + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + assertThat(committed.get(written)).as("one committed %s", written).hasSize(1); + } + unavailableAccount.set(true); + unavailableGds.set(true); + assertThat(freeze.begin(request)).isEqualTo(created); + assertThat(freezeOwnerRows(world.dsl())).isEqualTo(committed); + assertThat(selectionCalls.get()).isEqualTo(2); + assertThat(versionCalls.get()).isEqualTo(2); + assertThat(heldCalls.get()).isEqualTo(2); + return retained; + } + } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; + } finally { + stopServers(bodyFailure, worldServer, accountServer, gdsServer); + } + } + + private static java.util.Map> freezeOwnerRows( + org.jooq.DSLContext dsl) { + var result = new java.util.LinkedHashMap>(); + for (String table : + List.of( + "world_design_publication_fence_owner", + "world_design_publication_fence_attempt", + "world_design_publication_account_binding", + "world_selected_publication_artifact_inventory", + "world_canonical_frozen_topology")) { + result.put( + table, + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM " + table + " r ORDER BY 1") + .getValues(0, String.class)); + } + return result; + } + + private static io.grpc.BindableService observedRead( + io.grpc.BindableService owner, + java.util.concurrent.atomic.AtomicInteger calls, + java.util.concurrent.atomic.AtomicBoolean unavailable) { + return () -> + ServerInterceptors.intercept( + owner, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata metadata, + io.grpc.ServerCallHandler next) { + calls.incrementAndGet(); + if (unavailable.get()) { + call.close( + io.grpc.Status.UNAVAILABLE.withDescription( + "test-only owner transport outage"), + new io.grpc.Metadata()); + return new io.grpc.ServerCall.Listener<>() {}; + } + return next.startCall(call, metadata); + } + }); + } + + /** + * Actual immutable owner terminals and Account ingress over controlled loopback workload mTLS. + */ + private static void completeActualWorldAndAccountTerminals( + Store gds, + Store world, + org.jooq.DSLContext accountDsl, + org.springframework.transaction.PlatformTransactionManager accountTransactions, + ProofPki pki, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + SettlementDiagnostics diagnostics) + throws Exception { + requireAccountClosureInventoryRefusals(accountDsl, operation); + var gdsOwner = + new net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperationService( + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationOperationRepository(gds.dsl()), + gds.transactions()); + Server gdsTerminalServer = + ownerServer( + pki, + "game-design-service", + diagnostics.timedGrpc( + "gds-terminal-read", + new net.firedevops.firemud.gamedesign.publication + .GameDesignPublicationTerminalReadGrpcService(gdsOwner, NAMESPACE))); + Server worldTerminalServer = null; + Server accountSettlementServer = null; + var endpoints = new ServiceEndpointsProperties(); + endpoints.setGameDesignService(loopback(gdsTerminalServer)); + var channels = new GrpcChannelFactory(); + Throwable bodyFailure = null; + try (var worldGdsRead = + new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + worldGdsRead.init(); + var worldRepository = + new net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalRepository( + world.dsl(), world.transactions()); + var worldOwner = + net.firedevops.firemud.worldmanagement.tenant.WorldPublicationTerminalService + .authenticated(worldRepository, worldGdsRead, NAMESPACE); + worldTerminalServer = + ownerServer( + pki, + "world-management-service", + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalCompletionGrpcService(worldOwner, NAMESPACE), + diagnostics.timedGrpc( + "world-terminal-read", + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalReadGrpcService( + new net.firedevops.firemud.worldmanagement.tenant + .WorldPublicationTerminalReadService(worldRepository, NAMESPACE), + NAMESPACE))); + endpoints.setWorldManagementService(loopback(worldTerminalServer)); + try (var accountGdsRead = + new net.firedevops.firemud.common.gamedesign.GameDesignPublicationTerminalClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var accountWorldRead = + new net.firedevops.firemud.common.publication.WorldPublicationTerminalReadClient( + endpoints, pki.client("account-service"), channels, NAMESPACE); + var producer = + net.firedevops.firemud.gamedesign.publication + .GameDesignWorldPublicationTerminalProducer.usingFileBackedMtls( + gdsOwner, endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + accountGdsRead.init(); + accountWorldRead.init(); + var accountOwner = + new AccountSelectedDraftPublicationSettlementService( + new AccountPublicationAuthorizationRepository(accountDsl), + accountGdsRead, + accountWorldRead, + diagnostics.timeTransactions(accountTransactions), + NAMESPACE); + var binding = + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding + .fromStored(operation.canonicalBytes()); + accountSettlementServer = + ownerServer( + pki, + "account-service", + diagnostics.timedGrpc( + "account-settlement", + new AccountSelectedPublicationSettlementGrpcService(accountOwner, NAMESPACE))); + endpoints.setAccountService(loopback(accountSettlementServer)); + try (var settlementClient = + new net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementClient( + endpoints, pki.client("game-design-service"), channels, NAMESPACE)) { + settlementClient.init(); + var settlementRequest = + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()); + try (var wrongCaller = + new net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementClient( + endpoints, pki.client("world-management-service"), channels, NAMESPACE)) { + wrongCaller.init(); + assertThatThrownBy(() -> wrongCaller.settle(settlementRequest)) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.PERMISSION_DENIED)); + } + diagnostics.phase( + "account-settlement-before-world-terminal", + () -> { + assertThatThrownBy( + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))) + .isInstanceOf(io.grpc.StatusRuntimeException.class) + .satisfies( + error -> + assertThat(io.grpc.Status.fromThrowable(error).getCode()) + .isEqualTo(io.grpc.Status.Code.FAILED_PRECONDITION)); + return null; + }); + assertThat( + accountDsl + .fetchSingle( + "SELECT count(*) FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, Long.class)) + .isZero(); + var published = + diagnostics.phase( + "world-producer-reconcile", + () -> + producer.reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + net.firedevops.firemud.common.gamedesign + .GameDesignPublicationTerminalEvidence.Outcome.PUBLISHED)); + assertThat(published.operationBytes()).containsExactly(operation.canonicalBytes()); + assertThat( + diagnostics.phase( + "world-producer-exact-retry", + () -> + producer + .reconcile( + operation.tenantKey(), + operation.workflowId(), + operation.versionId(), + operation.selectionDigest(), + published.outcome()) + .canonicalBytes())) + .containsExactly(published.canonicalBytes()); + byte[] receipt = + diagnostics.phase( + "account-settlement-positive", + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes()))); + assertThat(receipt).isNotEmpty(); + String retained = + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class); + assertThat( + diagnostics.phase( + "account-settlement-exact-retry", + () -> + settlementClient.settle( + net.firedevops.firemud.common.publication + .AccountSelectedPublicationSettlementGrpcCodec.Request.create( + NAMESPACE, operation.canonicalBytes())))) + .containsExactly(receipt); + assertThat( + accountDsl + .fetchSingle( + "SELECT to_jsonb(s)::text || ':' || xmin::text FROM account_selected_publication_settlements s WHERE operation_id = ?", + binding.account().operationId()) + .get(0, String.class)) + .isEqualTo(retained); + assertThat( + accountDsl + .fetchSingle( + "SELECT game_design_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + assertThat( + accountDsl + .fetchSingle( + "SELECT world_terminal FROM account_selected_publication_settlements WHERE operation_id = ?", + binding.account().operationId()) + .get(0, byte[].class)) + .containsExactly(published.canonicalBytes()); + } + } + } catch (Exception failure) { + bodyFailure = failure; + throw failure; + } catch (Error failure) { + bodyFailure = failure; + throw failure; + } finally { + stopServers(bodyFailure, accountSettlementServer, worldTerminalServer, gdsTerminalServer); + } + } + + private static void requireAccountClosureInventoryRefusals( + org.jooq.DSLContext dsl, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation) + throws Exception { + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", operation.canonicalBytes()); + var mapper = new ObjectMapper(); + java.util.List> changes = + java.util.List.of( + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .remove("inboundSourceClosure"), + tree -> + ((tools.jackson.databind.node.ObjectNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts/0")) + .put("count", 1), + tree -> + ((tools.jackson.databind.node.ArrayNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts")) + .remove(6), + tree -> { + var families = + (tools.jackson.databind.node.ArrayNode) + tree.at("/sourceModel/inboundSourceClosure/familyCounts"); + families.add(families.remove(0)); + }, + tree -> + ((tools.jackson.databind.node.ObjectNode) + tree.at("/sourceModel/inboundSourceClosure")) + .put("unknown", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .put("unknown", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("sourceModel")) + .put("graphSchemaVersion", 2), + tree -> tree.put("schemaVersion", 1), + tree -> + ((tools.jackson.databind.node.ObjectNode) tree.get("checkpoint")) + .put("digestSchemaVersion", 3)); + var before = + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM account_selected_publication_authorizations r ORDER BY 1") + .getValues(0, String.class); + for (var change : changes) { + var tree = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(operation.inventory().canonicalBytes()); + change.accept(tree); + byte[] inventory = mapper.writeValueAsBytes(tree); + var raw = new java.io.ByteArrayOutputStream(); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, + net.firedevops.firemud.common.publication.GameDesignPublicationOperationBinding.SCHEMA); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, operation.account().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, operation.world().canonicalBytes()); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame(raw, inventory); + net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding.frame( + raw, + "sha256:" + + java.util.HexFormat.of() + .formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(inventory))); + assertThatThrownBy( + () -> + dsl.fetch( + "SELECT require_selected_inventory_operation_v2(?::bytea)", + raw.toByteArray())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .satisfies( + failure -> { + var cause = failure; + while (cause != null && !(cause instanceof java.sql.SQLException)) + cause = cause.getCause(); + assertThat(cause).isInstanceOf(java.sql.SQLException.class); + assertThat(((java.sql.SQLException) cause).getSQLState()).isEqualTo("23514"); + }); + } + assertThat( + dsl.fetch( + "SELECT to_jsonb(r)::text || ':' || r.xmin::text FROM account_selected_publication_authorizations r ORDER BY 1") + .getValues(0, String.class)) + .isEqualTo(before); + } + private static Draft createDraft(Store gds) { Version savedVersion = gds.write() @@ -1122,17 +1923,6 @@ private static void completeGameDesignCommit( }); } - private static AccountPublicationAuthorizationBinding controlledAccountBinding( - AuthoredDraftPublishSelectionBinding selection) { - UUID actor = UUID.randomUUID(); - var input = new AccountPublicationAuthorizationBinding.PreallocationInput(actor, selection); - return new AccountPublicationAuthorizationBinding( - UUID.randomUUID(), - UUID.randomUUID(), - input, - controlledAccountSources(actor, selection.intent().canonicalTenantId())); - } - private static SelectedOwnerIntakeAuthorizationBinding selectedOwnerAuthorization( Store gds, AuthoredDraftPublishSelection selection, Owner recipient, UUID actor) { var scope = @@ -1229,24 +2019,288 @@ private static String loopback(Server server) { return "127.0.0.1:" + server.getPort(); } - private static Server ownerServer(ProofPki pki, String service, io.grpc.BindableService handler) - throws Exception { + private static final class SettlementDiagnostics { + private final boolean enabled = Boolean.getBoolean("firemud.settlementDiagnostics"); + private final AtomicLong sequence = new AtomicLong(); + private final long diagnosticOriginNanos = System.nanoTime(); + + void logPostgres(String role, PostgreSQLContainer postgres) { + if (!enabled) return; + try { + System.out.printf( + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d container=%s host=%s mapped_port=%d running=%s%n", + role, + System.nanoTime() - diagnosticOriginNanos, + postgres.getContainerId(), + postgres.getHost(), + postgres.getMappedPort(5432), + postgres.isRunning()); + } catch (RuntimeException unavailable) { + System.out.printf( + "SETTLEMENT_DIAGNOSTIC event=postgres-container role=%s elapsed_since_diagnostic_start_nanos=%d status=unavailable error=%s%n", + role, + System.nanoTime() - diagnosticOriginNanos, + unavailable.getClass().getSimpleName()); + } + } + + T phase(String stage, Supplier action) { + long call = sequence.incrementAndGet(); + long started = System.nanoTime(); + event(call, stage, "start", 0L, "none"); + try { + T result = action.get(); + event(call, stage, "complete", System.nanoTime() - started, "OK"); + return result; + } catch (RuntimeException | Error failure) { + event( + call, stage, "failed", System.nanoTime() - started, failure.getClass().getSimpleName()); + throw failure; + } + } + + io.grpc.BindableService timedGrpc(String stage, io.grpc.BindableService owner) { + return () -> + ServerInterceptors.intercept( + owner, + new io.grpc.ServerInterceptor() { + @Override + public io.grpc.ServerCall.Listener interceptCall( + io.grpc.ServerCall call, + io.grpc.Metadata headers, + io.grpc.ServerCallHandler next) { + long callSequence = sequence.incrementAndGet(); + long started = System.nanoTime(); + String method = call.getMethodDescriptor().getFullMethodName(); + var recorded = new java.util.concurrent.atomic.AtomicBoolean(); + var timedCall = + new io.grpc.ForwardingServerCall.SimpleForwardingServerCall<>(call) { + @Override + public void sendMessage(ResponseT message) { + long sendStarted = System.nanoTime(); + String serializedSize = serializedSize(message); + event( + callSequence, + stage + "/" + method, + "send-message-before", + sendStarted - started, + serializedSize); + try { + super.sendMessage(message); + long sendFinished = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "send-message-after", + sendFinished - started, + serializedSize + + ",delegate_elapsed_nanos=" + + (sendFinished - sendStarted)); + } catch (RuntimeException | Error failure) { + long sendFailed = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "send-message-failed", + sendFailed - started, + serializedSize + + ",delegate_elapsed_nanos=" + + (sendFailed - sendStarted) + + ",failure=" + + failure.getClass().getSimpleName()); + throw failure; + } + } + + @Override + public void close(io.grpc.Status status, io.grpc.Metadata trailers) { + if (recorded.compareAndSet(false, true)) { + event( + callSequence, + stage + "/" + method, + "closed", + System.nanoTime() - started, + status.getCode().name()); + } + super.close(status, trailers); + } + }; + event(callSequence, stage + "/" + method, "start", 0L, "STARTED"); + var listener = next.startCall(timedCall, headers); + return new io.grpc.ForwardingServerCallListener + .SimpleForwardingServerCallListener<>(listener) { + @Override + public void onMessage(RequestT message) { + event( + callSequence, + stage + "/" + method, + "request-message", + System.nanoTime() - started, + serializedSize(message)); + super.onMessage(message); + } + + @Override + public void onHalfClose() { + long handlerStarted = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-enter", + handlerStarted - started, + "ENTERED"); + try { + super.onHalfClose(); + long handlerFinished = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-return", + handlerFinished - started, + "handler_elapsed_nanos=" + (handlerFinished - handlerStarted)); + } catch (RuntimeException | Error failure) { + long handlerFailed = System.nanoTime(); + event( + callSequence, + stage + "/" + method, + "handler-failed", + handlerFailed - started, + "handler_elapsed_nanos=" + + (handlerFailed - handlerStarted) + + ",failure=" + + failure.getClass().getSimpleName()); + throw failure; + } + } + + @Override + public void onCancel() { + if (recorded.compareAndSet(false, true)) { + event( + callSequence, + stage + "/" + method, + "cancelled", + System.nanoTime() - started, + "CANCELLED"); + } + super.onCancel(); + } + }; + } + }); + } + + PlatformTransactionManager timeTransactions(PlatformTransactionManager delegate) { + return new PlatformTransactionManager() { + private final Map active = new IdentityHashMap<>(); + + @Override + public TransactionStatus getTransaction(TransactionDefinition definition) { + long call = sequence.incrementAndGet(); + long started = System.nanoTime(); + event(call, "account-transaction", "acquire-start", 0L, "STARTED"); + try { + TransactionStatus status = delegate.getTransaction(definition); + synchronized (active) { + active.put(status, new TransactionTiming(call, started)); + } + event(call, "account-transaction", "acquired", System.nanoTime() - started, "OK"); + return status; + } catch (RuntimeException | Error failure) { + event( + call, + "account-transaction", + "acquire-failed", + System.nanoTime() - started, + failure.getClass().getSimpleName()); + throw failure; + } + } + + @Override + public void commit(TransactionStatus status) { + finish(status, true); + } + + @Override + public void rollback(TransactionStatus status) { + finish(status, false); + } + + private void finish(TransactionStatus status, boolean commit) { + TransactionTiming timing; + synchronized (active) { + timing = active.remove(status); + } + long completionStarted = System.nanoTime(); + try { + if (commit) { + delegate.commit(status); + } else { + delegate.rollback(status); + } + if (timing != null) { + event( + timing.sequence(), + "account-transaction", + commit ? "committed" : "rolled-back", + System.nanoTime() - timing.startedNanos(), + "completion_ns=" + (System.nanoTime() - completionStarted)); + } + } catch (RuntimeException | Error failure) { + if (timing != null) { + event( + timing.sequence(), + "account-transaction", + commit ? "commit-failed" : "rollback-failed", + System.nanoTime() - timing.startedNanos(), + failure.getClass().getSimpleName()); + } + throw failure; + } + } + }; + } + + private String serializedSize(Object message) { + if (message instanceof com.google.protobuf.MessageLite protobufMessage) { + try { + return "serialized_size_bytes=" + protobufMessage.getSerializedSize(); + } catch (RuntimeException unavailable) { + return "serialized_size_bytes=unavailable"; + } + } + return "serialized_size_bytes=unavailable"; + } + + private void event(long call, String stage, String event, long elapsedNanos, String result) { + if (!enabled) return; + long elapsedSinceDiagnosticStartNanos = System.nanoTime() - diagnosticOriginNanos; + System.out.printf( + "SETTLEMENT_DIAGNOSTIC call=%d stage=%s event=%s elapsed_nanos=%d elapsed_since_diagnostic_start_nanos=%d result=%s%n", + call, stage, event, elapsedNanos, elapsedSinceDiagnosticStartNanos, result); + } + + private record TransactionTiming(long sequence, long startedNanos) {} + } + + private static Server ownerServer( + ProofPki pki, String service, io.grpc.BindableService... handlers) throws Exception { var identity = pki.server(service); - return NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) - .sslContext( - GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) - .trustManager(pki.ca().toFile()) - .clientAuth(ClientAuth.REQUIRE) - .build()) - .addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())) - .build() - .start(); + var builder = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMetadataSize(AccountSelectedPublicationOrderGrpcCodec.MAX_METADATA_BYTES) + .sslContext( + GrpcSslContexts.forServer(identity.certificate().toFile(), identity.key().toFile()) + .trustManager(pki.ca().toFile()) + .clientAuth(ClientAuth.REQUIRE) + .build()); + for (var handler : handlers) + builder.addService(ServerInterceptors.intercept(handler, new GrpcPeerIdentityInterceptor())); + return builder.build().start(); } - private static void stopServers( - Throwable bodyFailure, Server entityServer, Server automationServer, Server gameLogicServer) { - Server[] servers = {entityServer, automationServer, gameLogicServer}; - String[] serverNames = {"entity", "automation", "game logic"}; + private static void stopServers(Throwable bodyFailure, Server... servers) { List cleanupFailures = new ArrayList<>(); boolean interrupted = bodyFailure instanceof InterruptedException; @@ -1258,7 +2312,7 @@ private static void stopServers( } catch (RuntimeException | Error failure) { cleanupFailures.add( new IllegalStateException( - "Failed to request shutdown for " + serverNames[index] + " owner server", failure)); + "Failed to request shutdown for owner server " + (index + 1), failure)); } } @@ -1269,19 +2323,18 @@ private static void stopServers( if (!server.awaitTermination(5, TimeUnit.SECONDS)) { cleanupFailures.add( new IllegalStateException( - serverNames[index] + " owner server did not terminate within 5 seconds")); + "Owner server " + (index + 1) + " did not terminate within 5 seconds")); } } catch (InterruptedException failure) { interrupted = true; cleanupFailures.add( new IllegalStateException( - "Interrupted while awaiting " + serverNames[index] + " owner server termination", + "Interrupted while awaiting owner server " + (index + 1) + " termination", failure)); } catch (RuntimeException | Error failure) { cleanupFailures.add( new IllegalStateException( - "Failed while awaiting " + serverNames[index] + " owner server termination", - failure)); + "Failed while awaiting owner server " + (index + 1) + " termination", failure)); } } @@ -1438,6 +2491,8 @@ private static final class ProofPki { for (String service : List.of( "game-design-service", + "account-service", + "world-management-service", "entity-management-service", "automation-scripting-service", "game-logic-service")) { diff --git a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java index 56104b7ac5..341be17fd1 100644 --- a/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java +++ b/services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedReleaseCanonicalIdentityIntegrationTest.java @@ -449,6 +449,375 @@ void repositoryNestedTransactionRollsBackWithOuterJooqOwnerTransaction() { assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); } + @Test + void selectedFullV4StorageRejectsMixedProfilesAndExactlyReplaysOriginalBytes() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-v4-profile-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var json = new tools.jackson.databind.ObjectMapper(); + var participants = + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures.participants( + version.getId(), operation.world(), 4); + String original = + new String(operation.world().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + for (int index = 0; index < participants.size(); index++) { + var mixed = + (tools.jackson.databind.node.ArrayNode) + json.readTree(json.writeValueAsString(participants)); + var participant = participants.get(index); + ((tools.jackson.databind.node.ObjectNode) mixed.get(index)) + .put( + "digestSchemaVersion", + participant.digestSchemaVersion() == 1 ? 2 : participant.digestSchemaVersion() - 1); + assertThatThrownBy( + () -> + insertRawSelectedFull( + fixture, version, operation, original, json.writeValueAsString(mixed))) + .as("mixed storage profile for %s", participant.participantKey()) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining("selected participant differs from commit/digest/schema"); + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + } + var requested = selectedFullBundle(version, operation.world()); + var saved = + fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> fixture.releaseBundleRepository().save(requested))); + assertThat(saved).isNotNull(); + var tuple = releaseBundleTuple(fixture.dsl(), saved.getId()); + var independent = + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + assertThat(independent).usingRecursiveComparison().isEqualTo(saved); + assertThat(independent.getWorldPublishedStartLocationEvidenceJson()).isEqualTo(original); + assertThat(independent.getParticipantDigestsJson()) + .isEqualTo(json.writeValueAsString(participants)); + assertThat(fixture.releaseBundleRepository().save(requested)) + .usingRecursiveComparison() + .isEqualTo(saved); + var changed = selectedFullBundle(version, operation.world()); + changed.setGenerationConfigRevision("changed-selected-generation"); + assertThatThrownBy(() -> fixture.releaseBundleRepository().save(changed)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("IDEMPOTENCY_CONFLICT"); + assertThat(releaseBundleTuple(fixture.dsl(), saved.getId())).isEqualTo(tuple); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + @Test + void concurrentExactSelectedFullRetriesCommitOneImmutableBundle() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-full-concurrent-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var start = new java.util.concurrent.CountDownLatch(1); + var executor = java.util.concurrent.Executors.newFixedThreadPool(2); + Throwable testFailure = null; + try { + java.util.concurrent.Callable save = + () -> { + start.await(); + return fixture + .transactionTemplate() + .execute( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> + new PublishedReleaseBundleRepository(fixture.dsl()) + .save(selectedFullBundle(version, operation.world())))); + }; + var first = executor.submit(save); + var second = executor.submit(save); + start.countDown(); + var one = first.get(20, java.util.concurrent.TimeUnit.SECONDS); + var two = second.get(20, java.util.concurrent.TimeUnit.SECONDS); + assertThat(two).usingRecursiveComparison().isEqualTo(one); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + var beforeRetry = releaseBundleTuple(fixture.dsl(), one.getId()); + assertThat( + fixture + .releaseBundleRepository() + .save(selectedFullBundle(version, operation.world()))) + .usingRecursiveComparison() + .isEqualTo(one); + assertThat(releaseBundleTuple(fixture.dsl(), one.getId())).isEqualTo(beforeRetry); + } catch (Exception | Error failure) { + testFailure = failure; + if (failure instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + throw failure; + } finally { + try { + executor.shutdownNow(); + if (!executor.awaitTermination(10, java.util.concurrent.TimeUnit.SECONDS)) { + throw new IllegalStateException("Executor did not terminate within 10 seconds"); + } + } catch (InterruptedException cleanupFailure) { + Thread.currentThread().interrupt(); + if (testFailure != null) { + testFailure.addSuppressed(cleanupFailure); + } else { + throw cleanupFailure; + } + } catch (RuntimeException cleanupFailure) { + if (testFailure != null) { + testFailure.addSuppressed(cleanupFailure); + } else { + throw cleanupFailure; + } + } + } + } + + @Test + void sqlGuardRejectsMissingAndChangedSelectedFullBindingsWithoutAnyRelease() throws Exception { + Fixture fixture = fixture(null); + Game owner = saveGame(fixture, "selected-full-guard-source"); + Version version = saveVersion(fixture, owner); + var operation = selectedFullOperation(fixture, version); + var json = new tools.jackson.databind.ObjectMapper(); + String original = + new String(operation.world().canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8); + String participants = + json.writeValueAsString( + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(version.getId(), operation.world(), 4)); + var gameBefore = sourceRow(fixture.dsl(), "game", owner.getId()); + var versionBefore = sourceRow(fixture.dsl(), "version", version.getId()); + assertThat(json.readTree(original).path("request").path("versionStateEpoch").isTextual()) + .isTrue(); + // The exact operation-byte guard rejects substituted evidence before its semantic checks. + assertSelectedFullMutationRejected( + fixture, + version, + operation, + null, + participants, + "selected publication is absent, sealed, or changed"); + for (String epoch : java.util.List.of("0", "01", "-1", "9223372036854775808")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) changed.get("request")) + .put("versionStateEpoch", epoch); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(changed), + participants, + "selected publication is absent, sealed, or changed"); + } + var numericEpoch = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + ((tools.jackson.databind.node.ObjectNode) numericEpoch.get("request")) + .put("versionStateEpoch", 1L); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(numericEpoch), + participants, + "selected publication is absent, sealed, or changed"); + for (String field : + java.util.List.of( + "canonicalTenantId", + "canonicalVersionId", + "publishWorkflowId", + "appliedCommitId", + "contentDigest", + "digestSchemaVersion", + "intakeRequestId")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + var request = (tools.jackson.databind.node.ObjectNode) changed.get("request"); + if (field.equals("digestSchemaVersion")) request.put(field, 3); + else request.put(field, field.endsWith("Id") ? UUID.randomUUID().toString() : "changed"); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(changed), + participants, + "selected publication is absent, sealed, or changed"); + } + for (String field : + java.util.List.of( + "selectorReceiptBytesBase64", + "originalAccountBindingBytesBase64", + "appliedResultBytesBase64")) { + var changed = (tools.jackson.databind.node.ObjectNode) json.readTree(original); + changed.remove(field); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + json.writeValueAsString(changed), + participants, + "selected publication is absent, sealed, or changed"); + } + // Keep the original operation-bound evidence so participant-specific checks remain reachable. + assertSelectedFullMutationRejected( + fixture, + version, + operation, + original, + "[]", + "selected release requires all five participant owners"); + var changedParticipants = (tools.jackson.databind.node.ArrayNode) json.readTree(participants); + ((tools.jackson.databind.node.ObjectNode) changedParticipants.get(0)) + .put("contentDigest", "c".repeat(64)); + assertSelectedFullMutationRejected( + fixture, + version, + operation, + original, + json.writeValueAsString(changedParticipants), + "selected participant differs from commit/digest/schema"); + assertThat(bundleCount(fixture.dsl())).isZero(); + assertThat(sourceRow(fixture.dsl(), "game", owner.getId())).isEqualTo(gameBefore); + assertThat(sourceRow(fixture.dsl(), "version", version.getId())).isEqualTo(versionBefore); + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup.commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelectedFull(fixture, version, operation, original, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow(); + })); + assertThat( + new PublishedReleaseBundleRepository(fixture.dsl()) + .findByTenantIdAndVersionId(owner.getTenantId(), version.getId()) + .orElseThrow() + .getWorldPublishedStartLocationEvidenceJson()) + .isEqualTo(original); + assertThat(bundleCount(fixture.dsl())).isEqualTo(1); + } + + private void assertSelectedFullMutationRejected( + Fixture fixture, + Version version, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + String evidence, + String participants, + String rejectionMessage) { + assertThatThrownBy( + () -> + fixture + .transactionTemplate() + .executeWithoutResult( + status -> + net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .commitStorage( + fixture.dsl(), + fixture.versionRepository(), + operation, + () -> { + insertRawSelectedFull( + fixture, version, operation, evidence, participants); + return fixture + .releaseBundleRepository() + .findByTenantIdAndVersionId( + operation.tenantKey(), operation.versionId()) + .orElseThrow(); + }))) + .isInstanceOf(DataAccessException.class) + .hasMessageContaining(rejectionMessage); + } + + /** Actual GDS owner selection/captures with explicitly stipulated remote Account/World input. */ + private net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation + selectedFullOperation(Fixture fixture, Version version) { + var target = + new net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof( + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + version.getId(), + version.getTenantId(), + version.getIdentitySourceGameRowId(), + version.getIdentitySourceGameTenantKey(), + version.getIdentitySourceProvenanceKind()); + return fixture + .transactionTemplate() + .execute( + status -> { + try { + return net.firedevops.firemud.gamedesign.draft.IsolatedPublicationOwnerSetup + .retainFrozenSourceBackedSelectedFull( + fixture.dsl(), + target, + version.getVersionStateEpoch(), + "ISOLATED selected-full storage regression", + java.util.List.of()); + } catch (Exception failure) { + throw new IllegalStateException(failure); + } + }); + } + + private PublishedReleaseBundle selectedFullBundle( + Version version, + net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence evidence) { + var candidate = bundle(version.getTenantId(), version.getId()); + candidate.setAttestationSchemaVersion("v4"); + candidate.setPublishWorkflowId(evidence.request().publishWorkflowId()); + candidate.setParticipantDigestsJson( + new tools.jackson.databind.ObjectMapper() + .writeValueAsString( + net.firedevops.firemud.gamedesign.service.impl.PublishedWorldSelectorFixtures + .participants(version.getId(), evidence, 4))); + candidate.setWorldPublishedStartLocationEvidenceJson( + new String(evidence.canonicalBytes(), java.nio.charset.StandardCharsets.UTF_8)); + return candidate; + } + + private void insertRawSelectedFull( + Fixture fixture, + Version version, + net.firedevops.firemud.gamedesign.publication.GameDesignPublicationOperation operation, + String evidence, + String participants) { + fixture + .dsl() + .execute( + "INSERT INTO published_release_bundle (tenant_id, version_id, version_number, " + + "canonical_tenant_id, canonical_version_id, published_release_bundle_ref, attestation_schema_version, " + + "publish_workflow_id, manifest_hash, generation_config_revision, manifest_schema_version, artifact_digests_json, " + + "required_manifest_asset_keys_json, participant_digests_json, command_definitions_json, script_only, " + + "world_published_start_location_evidence_json) VALUES (?, ?, 1, ?, ?, ?, 'v4', ?, ?, ?, 1, '[]', '[]', ?, '[]', FALSE, ?)", + version.getTenantId(), + version.getId(), + version.getCanonicalTenantId(), + version.getCanonicalVersionId(), + UUID.randomUUID().toString(), + operation.workflowId(), + MANIFEST_HASH, + GENERATION_CONFIG_REVISION, + participants, + evidence); + } + private Fixture fixture(MigrationVersion target) { String schema = "game_design_release_identity_" + UUID.randomUUID().toString().replace("-", ""); DriverManagerDataSource dataSource = dataSource(schema); diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java new file mode 100644 index 0000000000..4f54642590 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/AssetSnapshotTest.java @@ -0,0 +1,101 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.gamedesign.AssetSource; +import net.firedevops.firemud.common.gamedesign.CommandSource; +import org.junit.jupiter.api.Test; + +class AssetSnapshotTest { + @Test + void exactTypedSnapshotRoundTripsAndOwnsItsImmutableCollection() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var item = + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[] {1, 2}), 2); + var mutable = new ArrayList<>(List.of(item)); + var snapshot = new AssetSnapshot(binding, "1", null, UUID.randomUUID(), mutable); + mutable.clear(); + assertThat(AssetSnapshot.fromStored(snapshot.canonicalJson())).isEqualTo(snapshot); + assertThat(snapshot.items()).containsExactly(item); + assertThatThrownBy(() -> snapshot.items().clear()) + .isInstanceOf(UnsupportedOperationException.class); + assertThat(snapshot.items().getFirst().reference().family()).isEqualTo("ORDINARY"); + assertThat(snapshot.items().getFirst().reference().role()).isEqualTo("RESOURCE"); + assertThat(new AssetApplication(binding, "0", snapshot).appliedEpoch().resultingEpoch()) + .isEqualTo("1"); + assertThatThrownBy(() -> new AssetApplication(binding, "1", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void storedSnapshotCannotChangeBoundRequirednessIdentityOrCanonicalRepresentation() { + var binding = binding(); + var reference = AssetSource.replay(List.of(), binding).references().getFirst(); + var snapshot = + new AssetSnapshot( + binding, + "1", + null, + UUID.randomUUID(), + List.of( + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), 0))); + String json = snapshot.canonicalJson(); + for (String invalid : + List.of( + json.replace("\"requiredness\":\"REQUIRED\"", "\"requiredness\":\"OPTIONAL\""), + json.replace("\"family\":\"ORDINARY\"", "\"family\":\"UNKNOWN\""), + json.replace("\"role\":\"RESOURCE\"", "\"role\":\"PRESENTATION\""), + " " + json)) { + assertThatThrownBy(() -> AssetSnapshot.fromStored(invalid)) + .isInstanceOf(IllegalArgumentException.class); + } + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "", CommandSource.sha256(new byte[0]), 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", "sha256:00", 0)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new net.firedevops.firemud.common.gamedesign.AssetSnapshot.Item( + reference, "image/png", CommandSource.sha256(new byte[0]), -1)) + .isInstanceOf(IllegalArgumentException.class); + } + + private static DraftCommitBinding binding() { + var target = + new DraftCommitBinding.TargetProof( + UUID.randomUUID(), UUID.randomUUID(), 1, "tenant", 2, "tenant", "NEW_GAME_ROW"); + return DraftCommitBinding.create( + target, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + List.of( + new DraftCommitBinding.RevisionPayload( + "0", + UUID.randomUUID(), + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.upsertPayload("3", "logo.png", AssetSource.Requiredness.REQUIRED))), + List.of( + new DraftCommitBinding.AffectedUnit( + DraftCommitBinding.Owner.GAME_DESIGN_CONTROL_PLANE, + AssetSource.SCOPE, + target.canonicalVersionId().toString(), + AssetSource.SCOPE, + AssetSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java new file mode 100644 index 0000000000..7a614e30f7 --- /dev/null +++ b/services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRetentionTest.java @@ -0,0 +1,129 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.BrandingSource; +import net.firedevops.firemud.common.publication.RealmEntryPolicy; +import org.junit.jupiter.api.Test; + +class RealmPolicySourceRetentionTest { + private static final UUID TENANT_ID = UUID.fromString("11111111-1111-4111-8111-111111111111"); + private static final UUID VERSION_ID = UUID.fromString("22222222-2222-4222-8222-222222222222"); + private static final UUID COMMIT_ID = UUID.fromString("33333333-3333-4333-8333-333333333333"); + private static final UUID REQUEST_ID = UUID.fromString("44444444-4444-4444-8444-444444444444"); + private static final UUID REVISION_ID = UUID.fromString("55555555-5555-4555-8555-555555555555"); + private static final UUID GENESIS_ID = UUID.fromString("66666666-6666-4666-8666-666666666666"); + + @Test + void schema3ActorCoreAndOriginalPolicyProvenanceSurviveOwnerApplication() { + String policyJson = + "{\"schemaVersion\":3,\"worldSlug\":\"world\",\"worldDisplayName\":\"World\"," + + "\"realmSlug\":\"realm\",\"realmDisplayName\":\"Realm\",\"visible\":true," + + "\"publicProduction\":true,\"stateScope\":\"SHARED\",\"entryPolicy\":\"PLAYER_CREATED\"," + + "\"creationDescriptor\":{\"schemaVersion\":1,\"descriptorId\":\"11111111-1111-4111-8111-111111111111\"," + + "\"descriptorRevisionId\":\"22222222-2222-4222-8222-222222222222\"," + + "\"inputKind\":\"EMPTY_OBJECT\",\"dependencies\":[]}," + + "\"initialActorCore\":{\"displayName\":\"Wayfarer\",\"dispositionKey\":\"newcomer\"}}"; + String payload = + RealmPolicySource.canonical( + Map.of( + "revisionKind", + RealmEntryPolicy.REVISION_KIND, + "logicalRevisionId", + "policy-logical-r3", + "policy", + RealmPolicySource.tree(policyJson))); + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of( + new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, payload)), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + var policy = RealmPolicySource.revision(binding, binding.revisions().getFirst()); + var snapshot = new RealmPolicySnapshot(binding, "1", List.of(policy)); + var application = new RealmPolicyApplication(freshGenesis(), null, "0", snapshot); + var retained = RealmPolicySnapshot.fromStored(application.snapshot().canonicalJson()); + var retainedPolicy = retained.policies().getFirst(); + + assertThat(retainedPolicy.commitId()).isEqualTo(COMMIT_ID); + assertThat(retainedPolicy.revisionId()).isEqualTo(REVISION_ID); + assertThat(retainedPolicy.logicalRevisionId()).isEqualTo("policy-logical-r3"); + assertThat(retainedPolicy.policy().initialActorCore().displayName()).isEqualTo("Wayfarer"); + assertThat(retainedPolicy.policy().initialActorCore().dispositionKey()).isEqualTo("newcomer"); + assertThat(application.canonicalBytes()).containsSequence(retained.canonicalBytes()); + } + + @Test + void missingBothGenesisAndInheritedCommitAndInvalidRequiredTextAreRejected() { + RealmPolicySnapshot snapshot = snapshot(); + + assertThatThrownBy(() -> new RealmPolicyApplication(null, null, "0", snapshot)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> new RealmPolicyApplication(freshGenesis(), null, "invalid", snapshot())) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void knownSiblingSourceKindsAreNonPolicyAndUnknownKindsStillDeny() { + assertThat(RealmPolicySource.isPolicyRevision(revision(BrandingSource.REVISION_KIND))) + .isFalse(); + assertThat(RealmPolicySource.isPolicyRevision(revision(TemplateConfigSource.REVISION_KIND))) + .isFalse(); + assertThatThrownBy(() -> RealmPolicySource.isPolicyRevision(revision("UNKNOWN_SOURCE"))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Unsupported Game Design owner revision kind"); + } + + private static RealmPolicyGenesis freshGenesis() { + return new RealmPolicyGenesis(target(), GENESIS_ID, "17"); + } + + private static RealmPolicySnapshot snapshot() { + DraftCommitBinding binding = + DraftCommitBinding.create( + target(), + REQUEST_ID, + COMMIT_ID, + "base-commit-0", + List.of(new RevisionPayload("0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{}")), + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + RealmPolicySource.SCOPE, + VERSION_ID.toString(), + RealmPolicySource.SCOPE, + "effective", + "0"))); + return new RealmPolicySnapshot(binding, "1", List.of()); + } + + private static TargetProof target() { + return new TargetProof( + TENANT_ID, VERSION_ID, 23L, "tenant-key", 42L, "tenant-key", "NEW_GAME_ROW"); + } + + private static RevisionPayload revision(String kind) { + return new RevisionPayload( + "0", REVISION_ID, Owner.GAME_DESIGN_CONTROL_PLANE, "{\"revisionKind\":\"" + kind + "\"}"); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java new file mode 100644 index 0000000000..8dc7c51ca7 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/GameplayRuleSourceTest.java @@ -0,0 +1,412 @@ +package net.firedevops.firemud.gamedesign.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.EnumMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.AffectedUnit; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.gamedesign.GameplayRuleSource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Ability; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Action; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionCategory; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ActorRole; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.AdmissionTag; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Audience; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CandidateSelector; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CapacityChangePolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cardinality; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Command; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.CommitPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Condition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ContinuousOverlay; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cooldown; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Cost; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DefaultBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Definition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Disposition; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.DurationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Effect; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectBinding; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.EffectOperation; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ExecutionDiscipline; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Family; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Feedback; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Lifecycle; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ObservationPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Predicate; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PredicateKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PrimitiveKind; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.PromptPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Reapplication; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.ReplayPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Resource; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.SelectionStrategy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stage; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Stat; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.StatField; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetSet; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.TargetingPolicy; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest.Visibility; +import org.junit.jupiter.api.Test; + +class GameplayRuleSourceTest { + private static final TargetProof TARGET = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 1L, + "private-owner-key", + 1L, + "private-owner-key", + "NEW_GAME_ROW"); + + @Test + void realNonemptyCatalogRetainsOrderedDeclarationsAndEveryOriginalRevision() { + var manifest = exampleManifest(); + var binding = + binding( + manifest.families().values().stream() + .flatMap(List::stream) + .map(GameplayRuleSource::upsertPayload) + .toList()); + var entries = GameplayRuleSource.replay(List.of(), binding); + var snapshot = new GameplayRuleSnapshot(binding, "1", null, UUID.randomUUID(), entries); + var read = GameplayRuleSnapshot.fromStored(snapshot.canonicalJson()); + + assertThat(read.canonicalBytes()).containsExactly(snapshot.canonicalBytes()); + assertThat(read.manifest().canonicalBytes()).containsExactly(manifest.canonicalBytes()); + assertThat(read.entries()).hasSize(entries.size()); + assertThat(read.entries()) + .allSatisfy(entry -> assertThat(entry.sourceBinding()).isEqualTo(binding)); + var action = (Action) read.manifest().families().get(Family.ACTIONS).getFirst(); + assertThat(action.admissionTags()).containsExactly("gameplay", "canFocus"); + assertThat(action.effects()) + .extracting(EffectBinding::effectKey) + .containsExactly("restore", "cleanse"); + var command = (Command) read.manifest().families().get(Family.COMMANDS).getFirst(); + assertThat(command.actionTags()).containsExactly(ActionTag.COMBAT); + assertThat(command.admissionTags()).containsExactly("gameplay", "canFocus"); + } + + @Test + void inheritedCatalogPreservesUnchangedProvenanceAndExplicitDelete() { + var initial = + binding( + List.of( + GameplayRuleSource.upsertPayload(new AdmissionTag("first")), + GameplayRuleSource.upsertPayload(new AdmissionTag("second")))); + var original = GameplayRuleSource.replay(List.of(), initial); + var changed = + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "first"), + GameplayRuleSource.upsertPayload(new AdmissionTag("third")))); + var replayed = GameplayRuleSource.replay(original, changed); + assertThat(replayed) + .extracting(entry -> entry.definition().key()) + .containsExactly("second", "third"); + assertThat(replayed.getFirst().sourceBinding()).isEqualTo(initial); + assertThat(replayed.getLast().sourceBinding()).isEqualTo(changed); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + replayed, + binding( + List.of( + GameplayRuleSource.deletePayload(Family.ADMISSION_TAGS, "missing"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void authoredDispositionAndRequiredFeedbackRetainTypedSelectedRevisionProvenance() { + var disposition = new Disposition("newcomer", List.of(), "welcome"); + var feedback = + new Feedback( + "welcome", + "actor.created", + Audience.SOURCE_ACTOR, + "actor.created", + "Welcome, traveler.", + List.of(), + Visibility.PUBLIC, + ReplayPolicy.EFFECT_IDEMPOTENT); + var selected = + binding( + List.of( + GameplayRuleSource.upsertPayload(disposition), + GameplayRuleSource.upsertPayload(feedback))); + var entries = GameplayRuleSource.replay(List.of(), selected); + var manifest = GameplayRuleSource.manifest(entries); + + assertThat(manifest.families().keySet()).containsExactlyInAnyOrder(Family.values()); + for (Family family : Family.values()) { + if (family != Family.DISPOSITIONS && family != Family.FEEDBACK) { + assertThat(manifest.families().get(family)).isEmpty(); + } + } + assertThat(manifest.families().get(Family.DISPOSITIONS)).containsExactly(disposition); + assertThat(manifest.families().get(Family.FEEDBACK)).containsExactly(feedback); + assertThat(entries).extracting(GameplayRuleSource.Entry::sourceBinding).containsOnly(selected); + assertThat(entries) + .extracting(GameplayRuleSource.Entry::revisionOrder) + .containsExactly("0", "1"); + } + + @Test + void incompleteInventoryAndUnresolvedReferencesDenyInsteadOfBecomingEmpty() { + var families = + new EnumMap>(GameplayRuleManifest.explicitEmpty().families()); + families.remove(Family.FEEDBACK); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.replay( + List.of(), + binding( + List.of( + GameplayRuleSource.upsertPayload( + new Ability("ability", "Ability", "missingAction")))))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unresolved ACTIONS"); + assertThatThrownBy( + () -> + GameplayRuleManifest.fromStored( + "{\"schema\":\"gameplay-rule-manifest/v1\",\"families\":{}}")) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void unknownDefinitionFieldsDuplicateFieldsAndMissingAdmissionTagsDeny() { + String command = + GameplayRuleManifest.canonical( + exampleManifest().families().get(Family.COMMANDS).getFirst()); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.COMMANDS, + command.replace("\"admissionTags\":[\"gameplay\",\"canFocus\"],", ""))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"tag\",\"unknownPolicy\":true}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.ADMISSION_TAGS, "{\"tagKey\":\"first\",\"tagKey\":\"second\"}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition(Family.ADMISSION_TAGS, "{\"tagKey\":\"first\"} {}")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleSource.mutations( + binding(List.of("{\"revisionKind\":\"UNKNOWN_RULE_FAMILY\"}")))) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void continuousEffectsCannotBecomeInstantActionEffectsOrGrantDeniedAdmission() { + var source = exampleManifest(); + var families = new EnumMap>(source.families()); + Action action = (Action) families.get(Family.ACTIONS).getFirst(); + families.put( + Family.ACTIONS, + List.of( + new Action( + action.key(), + action.name(), + action.admissionTags(), + action.targetSets(), + action.costs(), + action.cooldowns(), + List.of(new EffectBinding("capacity", "SOURCE")), + action.feedbackKeys()))); + assertThatThrownBy(() -> new GameplayRuleManifest(families)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + GameplayRuleManifest.definition( + Family.CONTINUOUS_OVERLAYS, + GameplayRuleManifest.canonical( + Map.of( + "overlayKey", + "overlay", + "eligibleWhen", + truth(), + "deniedAdmissionTags", + List.of(), + "effectKeys", + List.of(), + "grantedAdmissionTags", + List.of("gameplay"))))) + .isInstanceOf(IllegalArgumentException.class); + } + + static GameplayRuleManifest exampleManifest() { + List definitions = + List.of( + new Stat( + "focus", + PrimitiveKind.NUMERIC, + BigDecimal.ONE, + null, + BigDecimal.ZERO, + BigDecimal.TEN, + Visibility.PUBLIC, + List.of()), + new Resource( + "energy", + BigDecimal.TEN, + BigDecimal.ZERO, + BigDecimal.TEN, + BigDecimal.valueOf(100), + Visibility.PUBLIC, + List.of()), + new Condition( + "weary", + Reapplication.REFRESH, + DurationPolicy.RESET, + 5L, + null, + Visibility.PUBLIC, + List.of(), + List.of(), + 0), + new Effect( + "restore", + Lifecycle.INSTANT, + EffectOperation.ADJUST_RESOURCE, + "energy", + null, + BigDecimal.ONE, + null, + null), + new Effect( + "cleanse", + Lifecycle.INSTANT, + EffectOperation.REMOVE_CONDITION, + null, + null, + null, + "weary", + null), + new Effect( + "capacity", + Lifecycle.CONTINUOUS, + EffectOperation.ADD, + "energy", + StatField.MAXIMUM, + BigDecimal.ONE, + null, + CapacityChangePolicy.CLAMP_ONLY), + new AdmissionTag("gameplay"), + new AdmissionTag("canFocus"), + new Feedback( + "unavailable", + "ACTION_REJECTED", + Audience.SOURCE_ACTOR, + "action.unavailable", + "Unavailable.", + List.of(), + Visibility.PRIVATE, + ReplayPolicy.EFFECT_IDEMPOTENT), + new Disposition("ready", List.of(), "unavailable"), + new ContinuousOverlay( + "wearyOverlay", + new Predicate( + PredicateKind.CONDITION_PRESENT, + ActorRole.SOURCE, + "weary", + null, + null, + List.of()), + List.of("canFocus"), + List.of("capacity")), + new ObservationPolicy("observable", truth()), + new TargetingPolicy( + "self", CandidateSelector.SELF, "observable", truth(), "unavailable"), + new SelectionPolicy( + "one", + Cardinality.EXACTLY_ONE, + null, + null, + SelectionStrategy.CANONICAL_ORDER, + null, + List.of()), + new DefaultBinding( + "focusDefault", List.of(new TargetSet("subject", "self", "one", true, null, null))), + new Action( + "focusAction", + "Focus", + List.of("gameplay", "canFocus"), + List.of(new TargetSet("subject", "self", "one", true, null, null)), + List.of(new Cost("energy", BigDecimal.ONE, CommitPolicy.ON_EXECUTION)), + List.of(new Cooldown("focusCooldown", 3L, CommitPolicy.ON_EFFECT_SUCCESS)), + List.of( + new EffectBinding("restore", "subject"), + new EffectBinding("cleanse", "SOURCE")), + List.of("unavailable")), + new Ability("focusAbility", "Focus ability", "focusAction"), + new Command( + "focusCommand", + "focusAction", + "GAME_LOGIC", + ExecutionDiscipline.DURABLE_GAMEPLAY, + Stage.GAMEPLAY, + PromptPolicy.WHEN_GAMEPLAY, + ActionCategory.GAMEPLAY, + true, + List.of("focus"), + List.of(ActionTag.COMBAT), + List.of("gameplay", "canFocus"))); + Map> families = new EnumMap<>(Family.class); + for (Family family : Family.values()) families.put(family, new ArrayList<>()); + for (Definition definition : definitions) families.get(definition.family()).add(definition); + return new GameplayRuleManifest(families); + } + + private static Predicate truth() { + return new Predicate(PredicateKind.TRUE, null, null, null, null, List.of()); + } + + private static DraftCommitBinding binding(List payloads) { + List revisions = new ArrayList<>(); + for (int i = 0; i < payloads.size(); i++) + revisions.add( + new RevisionPayload( + Integer.toString(i), + UUID.randomUUID(), + Owner.GAME_DESIGN_CONTROL_PLANE, + payloads.get(i))); + return DraftCommitBinding.create( + TARGET, + UUID.randomUUID(), + UUID.randomUUID(), + "base-commit-0", + revisions, + List.of( + new AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + GameplayRuleSource.SCOPE, + TARGET.canonicalVersionId().toString(), + GameplayRuleSource.SCOPE, + GameplayRuleSource.SCOPE_ID, + "0"))); + } +} diff --git a/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java new file mode 100644 index 0000000000..f23215b237 --- /dev/null +++ b/services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/SelectedDraftPublicationAdmissionServiceTest.java @@ -0,0 +1,675 @@ +package net.firedevops.firemud.gamedesign.publication; + +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.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.same; +import static org.mockito.Mockito.inOrder; +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.Status; +import java.util.Arrays; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient; +import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryClient; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceDigest; +import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeClient; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationClient; +import net.firedevops.firemud.common.world.WorldPublishedStartLocationEvidence; +import net.firedevops.firemud.gamedesign.draft.AuthoredDraftPublishSelection; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceDeliveryRepository; +import net.firedevops.firemud.gamedesign.repository.GameAuthoredWorldSourceRepository; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unit proof for the admission ordering and exact preflight checks; clients are transport doubles. + */ +class SelectedDraftPublicationAdmissionServiceTest { + private static final String NAMESPACE = "test"; + + @Test + void retainedSelectionAccountFreezeAndDerivedSelectorPrecedeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = freezeClient(fixture); + var inventory = inventoryClient(fixture); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var sourceFixture = sourceFixture(fixture.worldRequest()); + when(sourceIntake.readById(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return sourceReceipt(invocation.getArgument(0), sourceFixture); + }); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), sourceFixture.intakeRequest(), Optional.empty()))); + var owner = mock(SelectedDraftPublicationOwner.class); + var reader = mock(SelectedDraftPublicationAdmissionService.SelectionReader.class); + var transactions = mock(PlatformTransactionManager.class); + var retained = + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest()); + when(reader.read(fixture.intent())).thenReturn(Optional.of(retained)); + when(account.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + when(world.read(fixture.worldRequest())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().world(); + }); + var reservation = mock(SelectedDraftPublicationOwner.Reservation.class); + // Request.binding() reconstructs the exact Account bytes; its nested selection does not use + // value equality. Match the complete canonical binding rather than decoded object identity. + when(owner.reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world()), + same(fixture.operation().inventory()), + any())) + .thenReturn(reservation); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + reader, + NAMESPACE); + + assertThat(service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(reservation); + var order = + inOrder( + reader, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + transactions, + owner); + order.verify(reader).read(fixture.intent()); + order.verify(account).read(any()); + order.verify(freeze).begin(any()); + order.verify(inventory).read(any()); + order.verify(world).read(fixture.worldRequest()); + order + .verify(sourceIntake) + .readById( + argThat( + request -> + request.schemaVersion() == 1 + && request.targetNamespace().equals(NAMESPACE) + && request + .intakeRequestId() + .equals(fixture.worldRequest().intakeRequestId()) + && request + .canonicalTenantId() + .equals(fixture.worldRequest().canonicalTenantId()) + && !request.readRequestId().equals(request.intakeRequestId()))); + order + .verify(sourceRepository) + .read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE); + order.verify(deliveryRepository).read(sourceFixture.source().operationId()); + order.verify(transactions).getTransaction(any()); + order + .verify(owner) + .reserve( + eq(fixture.intent()), + argThat( + binding -> + Arrays.equals( + binding.canonicalBytes(), fixture.operation().account().canonicalBytes())), + same(fixture.operation().world()), + same(fixture.operation().inventory()), + any()); + } + + @Test + void missingRetainedSelectionNeverReadsAccountFreezesWorldOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> Optional.empty(), + NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("SELECTION_UNAVAILABLE"); + verifyNoInteractions( + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + transactions); + } + + @Test + void mismatchedRetainedDeliveryAcknowledgementDeniesBeforeReservation() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var sourceFixture = sourceFixture(fixture.worldRequest()); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + when(sourceIntake.readById(any())) + .thenAnswer(invocation -> sourceReceipt(invocation.getArgument(0), sourceFixture)); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + when(sourceRepository.read( + sourceFixture.source().operationId(), + sourceFixture.source().canonicalTenantId(), + sourceFixture.source().worldSlug(), + NAMESPACE)) + .thenReturn(Optional.of(sourceFixture.source())); + var receipt = + sourceReceipt( + new WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest( + 1, + NAMESPACE, + UUID.randomUUID(), + fixture.worldRequest().intakeRequestId(), + fixture.worldRequest().canonicalTenantId()), + sourceFixture); + var wrongAcknowledgement = + new WorldAuthoredSourceIntakeGrpcCodec.CommittedReceipt( + receipt.schemaVersion(), + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.operationId(), + receipt.canonicalTenantId(), + receipt.worldSlug(), + receipt.sourceOperationId(), + receipt.sourceEvidenceDigest(), + receipt.requestDigest(), + "sha256:" + "b".repeat(64)); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + when(deliveryRepository.read(sourceFixture.source().operationId())) + .thenReturn( + Optional.of( + new GameAuthoredWorldSourceDeliveryRepository.DeliveryClaim( + sourceFixture.source(), + sourceFixture.intakeRequest(), + Optional.of(wrongAcknowledgement)))); + var world = mock(WorldPublishedStartLocationClient.class); + when(world.read(fixture.worldRequest())).thenReturn(fixture.operation().world()); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventoryClient(fixture), + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("OWNER_READBACK_CONFLICT"); + verifyNoInteractions(transactions, owner); + } + + @Test + void freezeFailureNeverReadsSelectorOrReserves() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + var freeze = mock(WorldSelectedDraftPublicationFreezeClient.class); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freeze, + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(freeze.begin(any())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + verifyNoInteractions(inventory, world, owner, transactions); + } + + @AfterEach + void clearTransactionState() { + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void missingInventoryAfterAcknowledgedFreezeNeverReadsSelectorOrOpensSql() throws Exception { + var fixture = fixture(); + var account = mock(AccountPublicationAuthorizationReadClient.class); + when(account.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var inventory = mock(WorldSelectedPublicationArtifactInventoryClient.class); + var world = mock(WorldPublishedStartLocationClient.class); + var sourceIntake = mock(WorldAuthoredSourceIntakeClient.class); + var sourceRepository = mock(GameAuthoredWorldSourceRepository.class); + var deliveryRepository = mock(GameAuthoredWorldSourceDeliveryRepository.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var transactions = mock(PlatformTransactionManager.class); + var selection = fixture.operation().account().input().selection(); + var service = + new SelectedDraftPublicationAdmissionService( + transactions, + account, + freezeClient(fixture), + inventory, + world, + sourceIntake, + sourceRepository, + deliveryRepository, + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + selection.canonicalJson(), selection.digest())), + NAMESPACE); + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("inventory readback"); + verify(inventory).read(any()); + verifyNoInteractions( + world, sourceIntake, sourceRepository, deliveryRepository, owner, transactions); + } + + @Test + void rejectsAmbientSqlTransactionBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.setActualTransactionActive(true); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsAmbientSynchronizationBeforeEitherOwnerRead() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + TransactionSynchronizationManager.initSynchronization(); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("no ambient transaction"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void rejectsChangedIntentBeforeOwnerReads() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var service = + service(fixture, accountClient, worldClient, mock(SelectedDraftPublicationOwner.class)); + var original = fixture.intent(); + var changedIntent = + new AuthoredDraftPublishSelection.PublishIntent( + original.canonicalTenantId(), + original.canonicalVersionId(), + original.publishRequestId(), + original.expectedVersionStateEpoch(), + "changed notes", + original.selectedCommitRequestId(), + original.selectedCommitId(), + original.selectedCommitDigest()); + + assertThatThrownBy(() -> service.admitAndReserve(changedIntent, fixture.operation().account())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("exact selected Draft intent"); + + verifyNoInteractions(accountClient, worldClient); + } + + @Test + void accountDenialOrUnavailableReadNeverReadsWorldOrReserves() throws Exception { + for (Status.Code code : + new Status.Code[] {Status.Code.PERMISSION_DENIED, Status.Code.UNAVAILABLE}) { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(fixture, accountClient, worldClient, owner); + var failure = Status.fromCode(code).asRuntimeException(); + when(accountClient.read(any())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verifyNoInteractions(worldClient, owner); + } + } + + @Test + void worldUnavailableAfterAccountReadNeverOpensReservation() throws Exception { + var fixture = fixture(); + var accountClient = mock(AccountPublicationAuthorizationReadClient.class); + var worldClient = mock(WorldPublishedStartLocationClient.class); + var owner = mock(SelectedDraftPublicationOwner.class); + var service = service(fixture, accountClient, worldClient, owner); + + // The client is a transport double here; the mock evidence is never accepted as proof because + // the World read fails before the reservation boundary. + when(accountClient.read(any())) + .thenAnswer( + invocation -> { + var evidence = mock(AccountPublicationAuthorizationReadEvidence.class); + when(evidence.request()).thenReturn(invocation.getArgument(0)); + return evidence; + }); + var failure = Status.UNAVAILABLE.asRuntimeException(); + when(worldClient.read(fixture.worldRequest())).thenThrow(failure); + + assertThatThrownBy( + () -> service.admitAndReserve(fixture.intent(), fixture.operation().account())) + .isSameAs(failure); + + verify(accountClient).read(any()); + verify(worldClient).read(fixture.worldRequest()); + verifyNoInteractions(owner); + } + + private static SelectedDraftPublicationAdmissionService service( + Fixture fixture, + AccountPublicationAuthorizationReadClient accountClient, + WorldPublishedStartLocationClient worldClient, + SelectedDraftPublicationOwner owner) { + return new SelectedDraftPublicationAdmissionService( + mock(PlatformTransactionManager.class), + accountClient, + freezeClient(fixture), + inventoryClient(fixture), + worldClient, + mock(WorldAuthoredSourceIntakeClient.class), + mock(GameAuthoredWorldSourceRepository.class), + mock(GameAuthoredWorldSourceDeliveryRepository.class), + owner, + intent -> + Optional.of( + AuthoredDraftPublishSelection.fromStored( + fixture.operation().account().input().selection().canonicalJson(), + fixture.operation().account().input().selection().digest())), + NAMESPACE); + } + + private static WorldSelectedPublicationArtifactInventoryClient inventoryClient(Fixture fixture) { + var client = mock(WorldSelectedPublicationArtifactInventoryClient.class); + when(client.read(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + return fixture.operation().inventory(); + }); + return client; + } + + private static WorldSelectedDraftPublicationFreezeClient freezeClient(Fixture fixture) { + var client = mock(WorldSelectedDraftPublicationFreezeClient.class); + when(client.begin(any())) + .thenAnswer( + invocation -> { + assertThat(TransactionSynchronizationManager.isActualTransactionActive()).isFalse(); + assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse(); + WorldSelectedDraftPublicationFreezeEvidence.Request request = + invocation.getArgument(0); + var world = fixture.worldRequest(); + var acknowledgement = + new WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement( + request, + world.intakeRequestId(), + world.versionStateEpoch(), + world.publicationFence(), + WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase.FROZEN, + world.appliedCommitId(), + world.contentDigest(), + world.digestSchemaVersion()); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + }); + return client; + } + + private static SourceFixture sourceFixture(WorldPublishedStartLocationEvidence.Request selected) { + UUID registrationRequestId = UUID.randomUUID(); + UUID sourceOperationId = UUID.randomUUID(); + String tenantSlug = "fixture-tenant"; + String worldSlug = "fixture-world"; + String worldDisplayName = "Fixture World"; + String requestDigest = + AuthoredWorldSourceDigest.requestDigest( + selected.targetNamespace(), + registrationRequestId, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName); + var source = + new AuthoredWorldSourceEvidence( + 1, + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW", + AuthoredWorldSourceDigest.evidenceDigest( + selected.targetNamespace(), + registrationRequestId, + sourceOperationId, + requestDigest, + selected.canonicalTenantId(), + tenantSlug, + worldSlug, + worldDisplayName, + 42L, + "tenant-key", + "NEW_GAME_ROW")); + var intakeRequest = + new WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest( + 1, + selected.targetNamespace(), + selected.intakeRequestId(), + selected.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest()); + return new SourceFixture(source, intakeRequest); + } + + private static WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt sourceReceipt( + WorldAuthoredSourceIntakeGrpcCodec.ByIdReadRequest request, SourceFixture fixture) { + var source = fixture.source(); + return new WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt( + 1, + request.targetNamespace(), + request.intakeRequestId(), + UUID.nameUUIDFromBytes( + "synthetic-world-operation".getBytes(java.nio.charset.StandardCharsets.UTF_8)), + request.canonicalTenantId(), + source.worldSlug(), + source.operationId(), + source.evidenceDigest(), + WorldAuthoredSourceIntakeGrpcCodec.requestDigest(fixture.intakeRequest()), + "sha256:" + "a".repeat(64), + source); + } + + private static Fixture fixture() throws Exception { + var target = + new TargetProof( + UUID.randomUUID(), + UUID.randomUUID(), + 19L, + "tenant-key", + 42L, + "tenant-key", + "NEW_GAME_ROW"); + var original = IsolatedPublicationOperationFixtures.fresh(target); + var selectionIntent = original.account().input().selection().intent(); + var intent = + new AuthoredDraftPublishSelection.PublishIntent( + selectionIntent.canonicalTenantId(), + selectionIntent.canonicalVersionId(), + selectionIntent.publishRequestId(), + selectionIntent.expectedVersionStateEpoch(), + selectionIntent.notes(), + selectionIntent.selectedCommitRequestId(), + selectionIntent.selectedCommitId(), + selectionIntent.selectedCommitDigest()); + return new Fixture(original, intent, original.world().request()); + } + + private record Fixture( + GameDesignPublicationOperation operation, + AuthoredDraftPublishSelection.PublishIntent intent, + WorldPublishedStartLocationEvidence.Request worldRequest) {} + + private record SourceFixture( + AuthoredWorldSourceEvidence source, + WorldAuthoredSourceIntakeGrpcCodec.IntakeRequest intakeRequest) {} +} diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index a60246f703..4f2e8b377a 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -153,6 +153,8 @@ 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.dao.TransientDataAccessResourceException; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DriverManagerDataSource; @@ -240,9 +242,11 @@ class WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest { @TempDir Path temporary; - @Test - void actualOwnersPrepareAndReplayOneExactOriginalOperation() throws Exception { - compose(Refusal.NONE); + @ParameterizedTest + @ValueSource(longs = {9_007_199_254_740_992L, 9_007_199_254_740_993L, Long.MAX_VALUE}) + void actualOwnersPrepareAndReplayOneExactOriginalOperation( + long reservationClaimFence, @TempDir Path proofDirectory) throws Exception { + compose(Refusal.NONE, reservationClaimFence, proofDirectory); } @Test @@ -328,10 +332,24 @@ private enum ActivationFailure { } private void compose(Refusal refusal) throws Exception { - compose(refusal, ActivationFailure.NONE); + compose(refusal, 9_007_199_254_740_993L, temporary, ActivationFailure.NONE); + } + + private void compose(Refusal refusal, long reservationClaimFence, Path proofDirectory) + throws Exception { + compose(refusal, reservationClaimFence, proofDirectory, ActivationFailure.NONE); } private void compose(Refusal refusal, ActivationFailure activationFailure) throws Exception { + compose(refusal, 9_007_199_254_740_993L, temporary, activationFailure); + } + + private void compose( + Refusal refusal, + long reservationClaimFence, + Path proofDirectory, + ActivationFailure activationFailure) + throws Exception { UUID tenant = UUID.randomUUID(); try (var account = new AccountControlUiOriginalOrderFixture( @@ -340,13 +358,13 @@ private void compose(Refusal refusal, ActivationFailure activationFailure) throw ACCOUNT.getPassword(), REDIS.getHost(), REDIS.getMappedPort(6379), - temporary.resolve("account"), + proofDirectory.resolve("account"), tenant); var world = database(WORLD, "world-management-service", true); var gs = database(GS, "game-session-service", false)) { var issuer = new AccountOriginalStartSessionAuthorizationProofFixture( - account, temporary.resolve("issuer"), NAMESPACE); + account, proofDirectory.resolve("issuer"), NAMESPACE); Duration lease = refusal == Refusal.EXPIRED_ATTEMPT ? Duration.ofSeconds(30) @@ -366,7 +384,6 @@ private void compose(Refusal refusal, ActivationFailure activationFailure) throw new StartSessionOperatorAction.Mutation(StartSessionOperatorAction.ClientIp.absent()), "TEST_ONLY owner composition"); String requestId = "controlled-original-prepare-" + UUID.randomUUID(); - long reservationClaimFence = 9_007_199_254_740_993L; var original = issuer.issueAndRedeemOriginal( requestId, @@ -446,7 +463,7 @@ public void attachAccountRedemptionProjection( claim.get().ownerMutationId(), input.gameSessionOwnerAttemptId(), claim.get().ownerFence()); - var pki = new WorldOriginalStartSessionPreparationProofPki(temporary.resolve("pki")); + var pki = new WorldOriginalStartSessionPreparationProofPki(proofDirectory.resolve("pki")); var factory = new GrpcChannelFactory(); var currentAttemptRefusal = new AtomicReference(); var currentAttemptReceiver = @@ -494,6 +511,8 @@ public void close(Status status, Metadata trailers) { currentAttempt.init(); launchAssociation.init(); if (refusal == Refusal.NONE) { + var beforeAuthenticatedRead = + rows(gs.dsl(), "game_session_start_session_operator_attempt"); var authenticatedCurrent = currentAttempt.read( new net.firedevops.firemud.common.gamesession @@ -506,8 +525,12 @@ public void close(Status status, Metadata trailers) { claim.get().ownerFence())); assertThat(authenticatedCurrent.request().originalTuple().reservationClaimFence()) .isEqualTo(reservationClaimFence); + assertThat(authenticatedCurrent.request().canonicalPostAuthorizationTuple()) + .containsExactly(tuple.canonicalBytes()); assertThat(authenticatedCurrent.accountRedemptionProjection()) .containsExactly(tuple.canonicalBytes()); + assertThat(rows(gs.dsl(), "game_session_start_session_operator_attempt")) + .isEqualTo(beforeAuthenticatedRead); } int accountPort = availablePort(); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java index a08009b045..e41f3a32f2 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixture.java @@ -3,7 +3,6 @@ import java.util.List; import java.util.Objects; import java.util.UUID; -import java.util.function.Function; import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; @@ -13,7 +12,6 @@ import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; -import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; import net.firedevops.firemud.common.tenant.AuthoredWorldSourceEvidence; import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec; @@ -109,26 +107,19 @@ public DraftCommitBinding selectedCommit() { } } - /** - * Applies and freezes the exact already-retained GDS selection in current World owners. - * - *

The supplied selection is read from GDS's synchronized Version/commit owner before this - * method is called. The callback supplies only controlled upstream Account authorization bytes; - * its selected binding must be byte-for-byte that retained selection. - */ - public static Result applyFreezeAndCapture( + /** Independently reads actual owner rows after the authenticated World begin has committed. */ + public static Result readCommittedFreeze( DSLContext worldDsl, - PlatformTransactionManager worldTransactions, String namespace, AuthoredDraftPublishSelectionBinding selection, AppliedGraph worldGraph, - Function - controlledAccountBindingFactory) { + AccountPublicationAuthorizationBinding accountBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { Objects.requireNonNull(worldDsl, "worldDsl"); - Objects.requireNonNull(worldTransactions, "worldTransactions"); Objects.requireNonNull(selection, "selection"); Objects.requireNonNull(worldGraph, "worldGraph"); - Objects.requireNonNull(controlledAccountBindingFactory, "controlledAccountBindingFactory"); + Objects.requireNonNull(accountBinding, "accountBinding"); + Objects.requireNonNull(freezeEvidence, "freezeEvidence"); var target = selection.target(); DraftCommitBinding binding = selection.selectedCommit(); @@ -154,9 +145,6 @@ public static Result applyFreezeAndCapture( var applied = worldGraph.applied(); requireExactAppliedReadback(applications, topology, application, plan, applied); - AccountPublicationAuthorizationBinding accountBinding = - Objects.requireNonNull( - controlledAccountBindingFactory.apply(selection), "controlled Account binding"); if (!selection.equals(accountBinding.input().selection())) { throw new IllegalArgumentException( "Controlled Account binding does not retain the exact GDS synchronized selection"); @@ -189,50 +177,8 @@ public static Result applyFreezeAndCapture( var authorizationRepository = new WorldSelectedDraftPublicationAuthorizationRepository(worldDsl); var inventoryRepository = new WorldSelectedPublicationArtifactInventoryRepository(worldDsl); - var checkpointRepository = - new WorldSelectedDraftPublicationCheckpointRepository( - fence, applications, topology, digestService); - var capturedCheckpoint = - new java.util.concurrent.atomic.AtomicReference< - WorldSelectedDraftPublicationCheckpointRepository.CapturedCheckpoint>(); - var createdCheckpointInTransaction = new java.util.concurrent.atomic.AtomicBoolean(); - var freezeTransaction = new TransactionTemplate(worldTransactions); - freezeTransaction.setIsolationLevel( - org.springframework.transaction.TransactionDefinition.ISOLATION_READ_COMMITTED); - var frozenAttempt = - Objects.requireNonNull( - freezeTransaction.execute( - status -> { - createdCheckpointInTransaction.set(false); - var attempt = - fence.claimFreeze( - freeze, - () -> { - var captured = checkpointRepository.captureWithSource(freeze, plan); - capturedCheckpoint.set(captured); - createdCheckpointInTransaction.set(true); - return captured.checkpoint(); - }); - var retainedAccount = - authorizationRepository.retainOrRequireExact( - attempt, accountBinding, createdCheckpointInTransaction.get()); - if (!java.util.Arrays.equals( - retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { - throw new IllegalStateException( - "World did not retain the exact original Account publication binding"); - } - inventoryRepository.retainOrRequireExact( - attempt, - retainedAccount, - createdCheckpointInTransaction.get(), - capturedCheckpoint.get()); - return attempt; - })); + var frozenAttempt = fence.readAttempt(freeze).orElseThrow(); - var checkpoint = - Objects.requireNonNull( - capturedCheckpoint.get(), - "World selected freeze reused an existing checkpoint; fixture requires a fresh capture"); var retainedAccount = authorizationRepository.readCommitted(frozenAttempt).orElseThrow(); if (!java.util.Arrays.equals( retainedAccount.canonicalBytes(), accountBinding.canonicalBytes())) { @@ -257,10 +203,11 @@ public static Result applyFreezeAndCapture( frozenAttempt.checkpoint().appliedCommitId(), frozenAttempt.checkpoint().contentDigest(), frozenAttempt.checkpoint().digestSchemaVersion()); - var freezeEvidence = - WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( - freezeRequest, - WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + if (!freezeRequest.equals(freezeEvidence.request()) + || !acknowledgement.equals(freezeEvidence.acknowledgement())) { + throw new IllegalStateException( + "Authenticated begin differs from independent committed World rows"); + } var inventoryEvidence = new WorldSelectedPublicationArtifactInventoryReadService( namespace, fence, authorizationRepository, inventoryRepository) @@ -270,13 +217,7 @@ public static Result applyFreezeAndCapture( var frozenRepository = new WorldCanonicalFrozenTopologyRepository( worldDsl, new WorldAuthoredGraphSnapshotRepository(worldDsl), topology, digestService); - var captured = - new WorldCanonicalFrozenTopologyService(frozenRepository, worldTransactions) - .capture(new WorldCanonicalFrozenTopology.Request(plan, captureRequest)); - var committedCapture = frozenRepository.readCommitted(captureRequest).orElseThrow(); - if (!java.util.Arrays.equals(committedCapture.graphBytes(), captured.graphBytes())) { - throw new IllegalStateException("Committed World frozen-graph readback changed bytes"); - } + var captured = frozenRepository.readCommitted(captureRequest).orElseThrow(); var publishedSource = new WorldPublishedStartLocationRepository(worldDsl, frozenRepository, applications) .readCommitted(captureRequest) @@ -284,8 +225,8 @@ public static Result applyFreezeAndCapture( var worldEvidence = publishedStartLocationEvidence(publishedSource); var worldDigest = new WorldDraftDesignDigestService.WorldDraftDesignDigest( - Long.toString(checkpoint.owner().localTenantKey()), - Long.toString(checkpoint.owner().localVersionKey()), + Long.toString(worldGraph.sourceIntake().localTenantKey()), + Long.toString(worldGraph.versionIdentity().localVersionKey()), frozenAttempt.checkpoint().appliedCommitId(), frozenAttempt.checkpoint().contentDigest(), frozenAttempt.checkpoint().digestSchemaVersion()); @@ -339,6 +280,24 @@ public static AppliedGraph applyGraph( String namespace, DraftCommitBinding selectedCommit, AuthoredWorldSourceEvidence controlledWorldSource) { + return applyGraph( + worldDsl, + worldTransactions, + namespace, + selectedCommit, + controlledWorldSource, + UUID.randomUUID()); + } + + /** Uses the existing GDS outbox's original World intake identity in composed proof. */ + public static AppliedGraph applyGraph( + DSLContext worldDsl, + PlatformTransactionManager worldTransactions, + String namespace, + DraftCommitBinding selectedCommit, + AuthoredWorldSourceEvidence controlledWorldSource, + UUID originalIntakeRequestId) { + Objects.requireNonNull(originalIntakeRequestId, "originalIntakeRequestId"); Objects.requireNonNull(worldDsl, "worldDsl"); Objects.requireNonNull(worldTransactions, "worldTransactions"); Objects.requireNonNull(selectedCommit, "selectedCommit"); @@ -354,7 +313,7 @@ public static AppliedGraph applyGraph( write.execute( status -> intakeRepository.acceptFresh( - namespace, UUID.randomUUID(), controlledWorldSource))); + namespace, originalIntakeRequestId, controlledWorldSource))); var versionStateRequest = new AuthoredWorldVersionStateEvidence.Request( 1, @@ -573,4 +532,54 @@ private static WorldPublishedStartLocationEvidence publishedStartLocationEvidenc source.appliedResult().application().operation().accountBindingBytes(), source.appliedResult().canonicalBytes()); } + + /** Explicit test-only composition of existing readers; no runtime registration or authority. */ + public static java.util.List reservationReadEndpoints( + DSLContext dsl, + PlatformTransactionManager transactions, + String namespace, + net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionReadClient + selectionClient, + net.firedevops.firemud.common.gamedesign.AuthoredWorldVersionStateClient versionClient, + net.firedevops.firemud.common.publication.AccountPublicationAuthorizationReadClient + accountClient, + net.firedevops.firemud.common.tenant.AuthoredWorldSourceClient sourceClient) { + var intake = new WorldAuthoredSourceIntakeRepository(dsl); + var fence = new WorldDesignPublicationFenceRepository(dsl, intake); + var topology = new WorldDraftTopologyCommitRepository(dsl, fence, JSON); + var applications = new WorldDraftGraphApplicationRepository(dsl, fence, JSON); + var digest = digestService(dsl); + var authorization = new WorldSelectedDraftPublicationAuthorizationRepository(dsl); + var inventory = new WorldSelectedPublicationArtifactInventoryRepository(dsl); + var frozen = + new WorldCanonicalFrozenTopologyRepository( + dsl, new WorldAuthoredGraphSnapshotRepository(dsl), topology, digest); + var service = + new WorldSelectedDraftPublicationFreezeService( + namespace, + selectionClient, + versionClient, + accountClient, + intake, + fence, + new WorldSelectedDraftPublicationCheckpointRepository( + fence, applications, topology, digest), + authorization, + inventory, + applications, + new WorldSelectedPublicationSelectorCapture( + namespace, new WorldCanonicalFrozenTopologyService(frozen, transactions)), + transactions); + return java.util.List.of( + new WorldSelectedDraftPublicationFreezeGrpcService( + service, + new WorldSelectedPublicationArtifactInventoryReadService( + namespace, fence, authorization, inventory), + namespace), + new WorldPublishedStartLocationReadGrpcService( + new WorldPublishedStartLocationRepository(dsl, frozen, applications), namespace), + new WorldAuthoredSourceIntakeGrpcService( + new WorldAuthoredSourceIntakeService(sourceClient, intake, transactions, namespace), + namespace)); + } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java index 9689dbbce2..f6082e5461 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldSelectedFullPublicationEvidenceFixtureTest.java @@ -1,27 +1,23 @@ package net.firedevops.firemud.worldmanagement.tenant; 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.never; -import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import java.util.UUID; -import java.util.function.Function; import net.firedevops.firemud.common.authoring.DraftCommitBinding; import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; import net.firedevops.firemud.common.publication.AccountPublicationAuthorizationBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding; import net.firedevops.firemud.common.publication.AuthoredDraftPublishSelectionBinding.PublishIntent; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; import org.jooq.DSLContext; import org.junit.jupiter.api.Test; -import org.springframework.transaction.PlatformTransactionManager; class WorldSelectedFullPublicationEvidenceFixtureTest { @Test - void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountCallback() { + void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountEvidenceRead() { UUID tenant = UUID.fromString("11111111-1111-4111-8111-111111111111"); UUID versionId = UUID.fromString("22222222-2222-4222-8222-222222222222"); UUID intakeOperationId = UUID.fromString("33333333-3333-4333-8333-333333333333"); @@ -45,10 +41,8 @@ void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountCallback( var version = mock(WorldAuthoredVersionIdentityReceipt.class); var graph = mock(WorldSelectedFullPublicationEvidenceFixture.AppliedGraph.class); var worldDsl = mock(DSLContext.class); - var transactions = mock(PlatformTransactionManager.class); - @SuppressWarnings("unchecked") - Function - accountBindingFactory = mock(Function.class); + var accountBinding = mock(AccountPublicationAuthorizationBinding.class); + var freezeEvidence = mock(WorldSelectedDraftPublicationFreezeEvidence.class); when(selection.target()).thenReturn(target); when(selection.intent()).thenReturn(intent); @@ -67,12 +61,11 @@ void rejectsVersionWithDifferentSourceIntakeOperationBeforeSqlOrAccountCallback( assertThatThrownBy( () -> - WorldSelectedFullPublicationEvidenceFixture.applyFreezeAndCapture( - worldDsl, transactions, "test", selection, graph, accountBindingFactory)) + WorldSelectedFullPublicationEvidenceFixture.readCommittedFreeze( + worldDsl, "test", selection, graph, accountBinding, freezeEvidence)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("World retained source/Version rows differ"); - verifyNoInteractions(worldDsl, transactions); - verify(accountBindingFactory, never()).apply(any()); + verifyNoInteractions(worldDsl, accountBinding, freezeEvidence); } }