diff --git a/design/architecture/microservices/automation-scripting-service/api-contracts.md b/design/architecture/microservices/automation-scripting-service/api-contracts.md index 6839cc3dc8..5a8bf331e5 100644 --- a/design/architecture/microservices/automation-scripting-service/api-contracts.md +++ b/design/architecture/microservices/automation-scripting-service/api-contracts.md @@ -12,6 +12,8 @@ For `ListScriptHandoffEvents`, the target command identity is the complete Comma ## Implementation Status +The prepared empty selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1003 retains empty selected source over the current combined Automation/Saga parent; it neither attests arbitrary scripts nor enables evaluation, dispatch or runtime publication. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-entity-and-automation-intake-prerequisite). + This section records the current implementation boundary only. The API sections below remain normative target contracts; a current implementation note does not relax those contracts, and a target-only surface must not be inferred as shipped. The unsupported NPC formation REST family has been removed from the runtime and authoritative OpenAPI. Formation operations remain available only through the authenticated internal gRPC control-plane path; no REST caller can supply a tenant or NPC identifier to reach the formation service. The gRPC path retains its existing global admin guard, which is neither tenant-bound `tenantAdmin` authorization nor Entity-owned NPC namespace/ownership proof; formation behavior remains partial until those target checks are implemented and proven. @@ -272,10 +274,16 @@ This service is a required digest participant for full publishes and script-patc Publish gating must fail closed when the service cannot attest a digest under its documented manifest for the reported `digestSchemaVersion`. +**Current selected-empty status:** An unregistered owner-local reader now provides a bounded selected-empty full-version primitive over Automation's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. The existing registered full-version reader remains unchanged; this primitive does not make Automation publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with all three declared script, event-binding, and patch-base-binding families explicitly empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted. This selected-empty full-version semantic path uses `digestSchemaVersion=6`; the existing script-patch digest remains schema 5 with its existing behavior. + +The selected-empty reader resolves by configured namespace, canonical tenant UUID, and the numeric Game Design Version row in the incoming full-version request. It scans only that namespace/tenant association prefix, fully validates each receipt, and requires exactly one association whose retained original selected-target proof matches the tenant, canonical Version UUID, and numeric Game Design Version row. The retained proof supplies the canonical Version UUID; the caller does not invent or submit it, and no mapping migration is introduced. Missing, ambiguous, corrupt, or mismatched evidence fails closed. Private Automation numeric keys, receipt digests/bytes, request/operation/authorization provenance, World read evidence, and timestamps are not publication identity or digest input. Its SHA-256 content preimage uses ADR 0047 byte-length framing over these ordered segments: the owner-specific domain `automation-selected-empty-publication-digest/v1`, schema `6`, canonical tenant UUID, numeric Game Design Version row, canonical Version UUID retained in the selected-target proof, and the exact canonical Automation inventory declaration. `appliedCommitId` is the original selected commit UUID retained in the receipt. This subset is not a claim that nonempty full-version script graphs or bindings are covered, and schema-6 participant evidence is not created by rewriting old evidence. + +The selected-empty service also requires the complete incoming publication request, derived workflow and digest to match its original retained World freeze and exact selected commit/acknowledgement. This schema-6 participant is admitted only through the [canonical selected-full profile](../game-design-service/version-control.md#selected-full-publication-profile) with independent retained recipient validation; it supplies no activation or publication authority on its own. + ### Game Design owner-to-owner digest authorization For publication-gate calls, `GetDraftDesignDigest` is not an admin or user operation. The target receiver authorization is a method-level allowlist for the authenticated Game Design workload identity, under the shared [Security Architecture](../../system-architecture-security.md) and [Authentication & Authorization](../../system-architecture-authentication.md) owner rules. The call must carry and validate the exact `{tenantId, scope}` (`versionId` or `scriptPatchVersion`) together with the stable caller `publishRequestId`, derived workflow identity, and canonical `requestDigest`; omitted or changed binding fails closed. This context is authorization and replay evidence, not a digest input. Other internal workloads are denied, and no user/admin JWT is accepted as a substitute. Game Design's Temporal activities must never forward the initiating human operator JWT; operator authority terminates at workflow admission. -**Current status:** `GetDraftDesignDigest` now invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated Game Design workload peer in the trusted namespace and a role-free internal JWT; the JWT `serviceName` claim is not treated as workload identity, and user/admin JWT substitution or a different peer is denied. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before reading content and exact-compares the returned tenant and scope. Focused unit proof covers the allowlisted peer, missing/wrong peer, JWT-only/user/admin substitution, and changed request digest. This closes the former empty-role/admin-guard authorization failure, but does not claim live mounted-certificate or real Temporal-activity proof. The schema-5 script-patch content digest includes the retained base version. Remaining content/proof gaps are explicit: the full-version digest input is still tenant-wide rather than version-mapped, and multi-version/cross-tenant owner proof is still required. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. +**Current status:** `GetDraftDesignDigest` now invokes `PublicationReadGuard` for the exact Automation publication-read method. The guard requires the authenticated exact Game Design workload mTLS peer in the configured trusted namespace and denies account, global-role, or scoped-role context. It does not add an end-user JWT requirement; a role-free internal identity is neither workload authorization nor an independent denial condition when the exact peer is present. The request proto carries tenant, typed scope, the patch `baseVersionId` when applicable, stable `publishRequestId`, derived workflow identity, and canonical `requestDigest`; the handler validates that complete binding before reading content and exact-compares the returned tenant and scope. Focused unit proof covers the allowlisted peer without end-user context, missing/wrong peer, account/global/scoped-role context denial, and changed request digest. This does not claim live mounted-certificate or real Temporal-activity proof. The existing script-patch content digest remains schema 5 and includes the retained base version; the selected-empty schema-6 primitive is unregistered and does not replace the live full-version reader, whose input remains tenant-wide. Multi-version/cross-tenant owner proof is still required. See the [Game Design publication/Temporal contract](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) for the coordinator-side boundary. -The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The shared negative proof covers missing or wrong peer identity and JWT-only/user/admin substitution; live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here. +The same owner-to-owner authorization now covers the WMS, Entity, Game Logic, and Automation participant reads: each handler applies the shared exact-method `PublicationReadGuard`, validates the complete typed request binding, and checks the returned tenant/scope before exposing its digest. The guard requires the exact authenticated Game Design workload mTLS peer and denies account or role-bearing context; role-free internal identity alone is not authorization or a substitute for that peer. Live mounted-certificate, real Temporal-activity, and multi-version/cross-tenant proof remain separate gaps. Content manifests remain owner-local: Automation's patch digest now binds the retained base version, while its existing live full-version mapping remains tenant-wide, so the authorization boundary must not be read as complete digest correctness. The shared target and proof requirements are maintained in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity), not redefined here. diff --git a/design/architecture/microservices/entity-management-service/api-contracts.md b/design/architecture/microservices/entity-management-service/api-contracts.md index 8d5e80bed4..d2e94081c0 100644 --- a/design/architecture/microservices/entity-management-service/api-contracts.md +++ b/design/architecture/microservices/entity-management-service/api-contracts.md @@ -6,6 +6,8 @@ The authoritative REST schema source lives in [../../../../services/entity-manag ## Implementation Status +The prepared selected-source command and immutable receipt/digest reads remain standalone, unregistered and unqualified. Forward V1011 adds the empty selected source catalogue over the current combined Entity/Saga parent, retaining explicit family and equipment evidence; this does not enable arbitrary authored templates, placement or gameplay admission. Its publication consumption follows the [canonical Game Design profile](../game-design-service/version-control.md#selected-full-publication-profile); current controlled-input proof limits and pending cross-owner qualification belong to the [selected-full owner tracker](../../../project-management/implementation-tracking/game-authoring-publishing-and-activation.md#selected-entity-and-automation-intake-prerequisite). + Entity V1003–V1010 and the manually composed, unregistered assignment/receipt/roster services are passive source and storage preparation. The canonical roster proto has no runtime handler, authenticated client, peer interceptor, or bean registration in this boundary. Legacy adapters and consumers retain develop behavior. The qualified immutable donor contains the complete migration tail; focused qualification of this recut, including the default combined Entity/Saga locations and actual-parent upgrade, is recorded under [GR-3.1](../../../project-management/implementation-tracking/gameplay-rules-entities-and-effects.md#validation-and-proof). Neither storage fixtures nor discovery references establish actual owner provenance, fresh Account eligibility, gameplay admission, or PLAY. Authenticated owner handoff and real caller/execution replacement remain required. The target read semantics are: any policy other than `PRESEEDED_ONLY` is non-authorizing and returns `FAILED_PRECONDITION`; `ListPreseededRoster` may successfully return zero actors and binds the exact target to its snapshot UUID and digest. PRESEEDED_ONLY actor display names are nonblank, trimmed, control-free text bounded to 100 Unicode code points, matching the accepted assignment core. `ReadSelectedPreseededAssignment` requires that same typed snapshot reference, echoes the exact request/account/selected-character/target/snapshot bindings, and returns `FAILED_PRECONDITION` if the snapshot is stale or the selected actor is absent from it. It also returns the original non-nil assignment operation UUID and immutable intent digest from the unique matching committed `ASSIGNED` `PRESEEDED_ONLY` `PLAYER` receipt. Entity resolves that receipt only for the exact account, selected actor, complete expected target, current owner counters, and published owner-proof digest; zero or multiple matches disclose no reference, and readback must match the same receipt. The response is persisted owner evidence, not a newly minted identity, an admission grant, or proof that Account eligibility remains current. Both methods require a server-derived typed `PlayerExecutionContext`, the exact same-namespace Game Session mTLS caller allowlist, and equality between context and request/target fields. Context `playable_state_scope` is exactly the text `SHARED` or `ISOLATED` matching the target enum, never numeric enum text. The initial roster read has no selected actor and requires no admitted-character or current-binding proof; the selection read requires `context.character_id` to equal `selected_character_uuid`. The context is unsigned scope data, not a credential, and does not authorize an additional Account lookup solely for the read. Malformed input is `INVALID_ARGUMENT`; authorization failures are `UNAUTHENTICATED` or `PERMISSION_DENIED` as applicable; unavailable dependencies are `UNAVAILABLE`. Failures use non-OK gRPC status with no partial response, not response-level `ErrorDetail`. These semantics do not authorize the legacy numeric `ListCharactersByAccount` RPC for canonical gameplay. @@ -91,12 +93,22 @@ Entity Management must also expose a read-only design-time synchronization surfa - `GetDraftDesignDigest(GetDraftDesignDigestRequest)` uses request shape `{tenantId, scope: oneof {versionId, scriptPatchVersion}}`. Entity Management supports `versionId` scope only and returns `UNSUPPORTED_SCOPE` otherwise. - Response returns `{tenantId, scope, appliedCommitId, contentDigest, digestSchemaVersion}` as described in [`world-editing-tools.md`](../game-design-service/world-editing-tools.md). -- Current drift: the digest handler has no owner/method authorization or exact Game Design publication binding beyond shared bearer parsing. The target workload, tenant/scope/request/workflow/digest context and denial proof are canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). +- Current boundary: `GetDraftDesignDigest` requires a configured trusted namespace and the exact authenticated Game Design workload peer through `PublicationReadGuard`, and denies authenticated account or role-bearing caller context. A role-free internal identity is not workload authorization or an additional JWT requirement. The handler validates the complete typed publication request binding and exact returned tenant/scope. Its registered reader still supplies synthetic `appliedCommitId = "version:"`; that projection is not selected-commit evidence. The target binding and proof requirements remain canonical in [Game Design Version Control](../game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity). ## Digest Input Manifest Entity Management is a required publish-gate participant and must maintain a stable digest manifest for `GetDraftDesignDigest(versionId)`: +**Current selected-empty status:** An unregistered owner-local reader now provides a bounded selected-empty full-version primitive over Entity's immutable validated fresh-empty receipt. Its native receiver applies the existing exact `PublicationReadGuard` and validates the complete publication request binding before lookup. The existing registered digest reader remains unchanged; this primitive does not make Entity publication readiness or runtime registration complete. It accepts only a receipt created by the fresh `retainFresh` path with the complete 23-family census explicitly empty, including `equipmentApplicability=NOT_APPLICABLE` and every declared family empty. Nonempty or historical participant evidence outside this exact fresh-empty path is unsupported and denied; old participant evidence is not silently rewritten or reinterpreted. + +The selected-empty reader resolves by configured namespace, canonical tenant UUID, and the numeric Game Design Version row in the incoming full-version request. It scans only that namespace/tenant association prefix, fully validates each receipt, and requires exactly one association whose retained original selected-target proof matches the tenant, canonical Version UUID, and numeric Game Design Version row. The retained proof supplies the canonical Version UUID; the caller does not invent or submit it, and no mapping migration is introduced. Missing, ambiguous, corrupt, or mismatched evidence fails closed. Private Entity numeric keys, receipt digests/bytes, request/operation/authorization provenance, World read evidence, and timestamps are not publication identity or digest input. + +The local V1011 storage guard treats an owner-resolved character's private Entity tenant-row ID as runtime identity rather than an authored-source TENANT key only when the row has complete canonical provenance, its tenant UUID and private row ID match the immutable tenant mapping, and its namespace and scope match the enrolled namespace tuple. Legacy writes using a reserved numeric key remain denied, and the guard continues to require READ COMMITTED. Canonical assignment currently writes no inventory, equipment, or actor-state child rows; this storage distinction does not enable those writers or gameplay admission. + +The registered version-scoped `GetDraftDesignDigest` response emits `digestSchemaVersion=1`. Changing the equipment-slot-group digest to schema 2 remains unimplemented target work. This standalone, unregistered selected-empty reader emits `digestSchemaVersion=3` and does not change the registered RPC. The schema-3 SHA-256 content preimage uses ADR 0047 byte-length framing over these ordered segments: the owner-specific domain `entity-selected-empty-publication-digest/v1`, schema `3`, canonical tenant UUID, numeric Game Design Version row, canonical Version UUID retained in the selected-target proof, and the exact canonical Entity inventory declaration. `appliedCommitId` is the original selected commit UUID retained in the receipt. Existing participant evidence must remain preserved under its original schema, meaning, and bytes; this standalone reader does not rewrite or upgrade existing evidence in place. This is a separately versioned, bounded semantic digest, not a receipt digest and not a claim that all nonempty Entity template families are covered. Only the new selected full-release profile may accept schema 3 after its compatible recorded owner evidence and exact readback pass. + +The selected-empty service additionally compares the incoming publication request, derived workflow and request digest with the original retained World freeze, its exact selected commit and acknowledgement. A later read correlation or latest owner state cannot substitute for that publication operation. Its schema-3 digest participates only in the [selected-full publication profile](../game-design-service/version-control.md#selected-full-publication-profile), where Game Design independently validates retained recipient evidence. Controlled receipt fixtures, local content integrity and a successful standalone read do not establish genuine Account authority, an authored producer, continuous currentness or permission to publish. + Implementation Notes: - The current implementation hashes the version-scoped entity-definition rows for the requested `(tenantId, versionId)` and returns synthetic `appliedCommitId = "version:"` until the later applied-revision ledger lands. diff --git a/design/project-management/ai-observations.md b/design/project-management/ai-observations.md index 4f2d53bf3b..8ca2757ded 100644 --- a/design/project-management/ai-observations.md +++ b/design/project-management/ai-observations.md @@ -263,6 +263,11 @@ Entry format: - Observation: Testcontainers 2.0.5 `HostPortWaitStrategy` checks internal container and external mapped-port reachability concurrently, then reports a generic timeout without preserving the subcheck cause. Redis-ready logs alone do not isolate host forwarding. A child-command timeout or Future cancellation does not prove the Docker exec RPC ended. - Expected pattern: Match exact container, fixture and mapped-port evidence before assigning a cause. Credit a focused rerun as its own proof; it neither erases the original failed aggregate nor proves a repair. +- `2026-10-23`: Give expired-certificate fixtures explicit past validity dates + - Context: [#3269's dev-tool contract job](https://github.com/benhook1013/FireMUD/actions/runs/39914844923/job/120286735224) failed while generating its expired RSA CA fixture with `openssl x509 -days -1`, before the bootstrap denial assertion could run. + - Expected pattern: Use an explicitly ordered past validity interval for an expired test certificate, retaining its CA/key-usage constraints and the assertion that expired authority cannot enable active mode. A fixture-generation failure is not evidence that the production expiry check failed; qualify the replacement fixture and the complete owning contract separately. + - Status: The corrected fixture, complete owning contract and ShellCheck passed locally on OpenSSL 3.0.2. Current-head CI remains required, and the earlier failed job remains failed evidence. + - `2026-10-23`: Isolate uv managed-Python launchers as well as installations - Observation: A temporary docs-lock generator set `UV_PYTHON_INSTALL_DIR` inside its task directory, but uv 0.13.5 also created `~/.local/bin/python3.15`. The exact newly created task-owned symlink was verified and removed; no preexisting launcher was overwritten. - Expected pattern: Set `UV_PYTHON_BIN_DIR` to a task-private path before temporary installation and confirm it with `uv python dir --bin`; this override was verified locally. Alternatively, `uv python install --no-bin` is supported by the installed help. Installation-directory isolation alone does not isolate launchers. 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 46d26224a8..85b2a01644 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 @@ -6,6 +6,14 @@ This is a non-normative implementation tracker for game authoring, publishing, a ## Current Status +### Selected Entity and Automation intake prerequisite + +The Entity and Automation owner-local empty selected-source intake commands, terminal and digest primitives, shared codecs and security clients remain source-prepared, standalone, unregistered and default-denied. Exact namespace, workload, current Account and World binding guards remain part of the owner boundary. This work grants no fresh public publication, finalizer registration, continuous protection, genuine issuer or creator authority, admission or activation. Selected-full Game Design and Game Logic publication composition and five-store proof remain downstream in the existing 3251 closure. Canonical behavior remains in the [Entity contract](../../architecture/microservices/entity-management-service/api-contracts.md), [Automation contract](../../architecture/microservices/automation-scripting-service/api-contracts.md) and [Game Design selected-full profile](../../architecture/microservices/game-design-service/version-control.md#selected-full-publication-profile). + +At source `f9e3f879d137b9a6fa54085e9c0b797586636a00`, the focused gate passed 1,105 cases across 224 suites (Gradle reported 4m 22s): 915 Common, 184 Common Security, five `EntityRetainedAuthoredActorCoreSourceService` cases, and one physical `AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest` case. There were zero failures, errors or skips. Common and Common Security full checks passed, along with affected style and documentation checks. This qualifies only these recorded scopes; it is not a fresh whole-service Entity or Automation rerun. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`, after this `f9e3f879d137b9a6fa54085e9c0b797586636a00` source checkpoint; its later current-source executions are attributed below, not to this gate. + +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. + ### Historical membership and upstream source validation proof The existing runtime membership validator test now checks three supported Account source event formats alongside a positive issuer source while retaining the original historical membership bytes. It verifies positive upstream evidence before returning an empty missing-membership result. Freshly resealed membership events cannot lead the current issuer generation, Account generation, issuance fence or historical Account cutoff sequence; equal and earlier valid Account cutoffs retain their original bytes. The added source fixtures use representable initialized counters above JavaScript's exact-integer range, while the existing maximum-counter case remains intact. The current exact tenant-generation and billing-cutoff rules retain their preceding tests and attribution. @@ -224,6 +232,8 @@ AR-1.5 full-version publication remains fail-closed at public and registered Tem Selected source capture, candidate staging/export, finalization, and terminal sealing remain non-ingress package-private conditional mechanics, not production publication. The asset candidate retains its frozen origin and snapshot-integrity checks; the selected finalizer requires a captured publication operation and same-transaction terminal seal. The private asset path uses immutable content-addressed keys, conditional writes, and exact readback, while physical deletion is hard-disabled. Local transaction, participant, and ambiguous-readback proof does not establish authorization, a production World freeze, or a reachable success path. PostgreSQL rollback, physical object-store behavior, live Temporal-owner publication, cross-phase recovery, and historical revision/version lineage remain unproved. Current ingress status is owned by [Game Design API Contracts](../../architecture/microservices/game-design-service/api-contracts.md#implementation-status); digest and candidate rules are owned by [Version Control](../../architecture/microservices/game-design-service/version-control.md#owner-to-owner-digest-authorization-and-tenant-identity) and [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#asset-lifecycle-and-publish-workflow). +The local canonical-assignment/source-key coexistence correction is implemented in Entity's V1011 guard. Child writers and gameplay admission remain disabled; see [Entity Management API Contracts](../../architecture/microservices/entity-management-service/api-contracts.md#digest-input-manifest) for the owning implementation status. + The existing publication proof remains limited to local gate, release-bundle, participant-digest, and transaction-unit seams; it does not prove a complete successful producer or end-to-end Temporal activity-to-owner path. V28 corrects V13-inferred full-version publication state without deleting retained rows: focused source-shape proof covers the exact epoch-1 marker, exact tenant/version bundle correlation, preservation of bundled and script-only rows, and idempotent epoch/timestamp quarantine, while PostgreSQL retained-row execution remains outstanding. Database rollback/ambiguous-commit recovery and live workload-certificate admission are likewise unproved. This migration correction is separate from the `CompareAndSetVersionState` transition gap: state-changing requests now fail closed pending owner proof, but the legal transition matrix remains absent. Asset lifecycle status remains partial: publication and artifact services provide the current bounded release-bundle and asset-storage seams, but destructive lifecycle operations still lack proved durable operation handling and complete owner-local epoch/CAS protection. `BeginPurgeVersionAssets` currently mints a random workflow identity. Artifact saves now include an epoch predicate and affected-row check; Version saves still lack a database epoch predicate and affected-row check, and physical database proof for artifact CAS is unavailable. The canonical lifecycle and operation contract is owned by [Asset Storage](../../architecture/microservices/game-design-service/asset-storage.md#implementation-status), with [ADR 0048](../../architecture/decisions/adr-0048-durable-idempotent-operator-write-execution.md) providing provenance. @@ -260,7 +270,7 @@ The published `888f` GDS foundation slice contains source-operation/outbox stora | `AR-1.2` Procedural, LLM-assisted, and external authoring tools | `partial` | `proven` for bounded procedural generation and the owner-local typed generation mutation algorithm; registered typed generation ingress, LLM-assisted authoring, destructive plans, staging bounds, and large-grid behavior remain unproved. Whole-game package import/export, filesystem/Git interchange, and portable snapshots are outside the current target per [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md), not merely unproved. The [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) typed creator-API/scoped-proposal path is target-only and remains unimplemented/unproved. | [LLM content tools](../../architecture/system-architecture-llm-content-tools.md); [procedural generation](../../architecture/system-architecture-procedural-generation.md); [generation control](../../architecture/microservices/world-management-service/procedural-generation-control.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [ADR 0125](../../architecture/decisions/adr-0125-defer-whole-game-portability-and-external-authoring-formats.md); [ADR 0126](../../architecture/decisions/adr-0126-untrusted-models-and-scoped-authoring-tools.md) | [GenerationServiceImpl.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImpl.java); [DungeonGenerator.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/generator/DungeonGenerator.java); [WorldDesignMutationServiceImpl.java](../../../services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImpl.java) | [GenerationServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/GenerationServiceImplTest.java); [DungeonGeneratorTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/generator/DungeonGeneratorTest.java); [WorldDesignMutationServiceImplTest.java](../../../services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/service/impl/WorldDesignMutationServiceImplTest.java) | [world runtime](./world-runtime-and-movement.md); [automation](./automation-and-scheduler-runtime.md) | Partial: bounded procedural generation and owner-local typed generation mutation tests exist, but registered typed generation ingress, destructive plan protocol, staging bounds, and large-grid proof remain incomplete. Whole-game portability remains non-target under ADR 0125; model-assisted authoring remains target-only under ADR 0126 with no production contract or focused proof. | | `AR-1.3` Script, plugin, mod, and extension packaging | `partial` | `proven` only for signed plugin intake, design-time script-patch publication, and bounded local activation-preflight/control-plane seams; full activation admission and canonical compatibility remain unproved because the dedicated Game Logic ability-schema attestation, tenant runtime readiness, and exact instance pin/epoch gates are not wired. Broader mod/extension packaging, creator tooling, and distribution lifecycle also remain unproved. | [Modding framework](../../architecture/microservices/game-design-service/modding-framework.md); [scripting control-plane API](../../architecture/system-architecture-scripting-control-plane-api.md); [scripting rollout and rollback](../../architecture/system-architecture-scripting-rollout-and-rollback.md) | [PluginBundleIntakeServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleIntakeServiceImpl.java); [PluginBundleStorageServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PluginBundleStorageServiceImpl.java); [AutomationPluginControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneService.java); [AutomationPatchControlPlaneService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneService.java); [V18 published plugins](../../../services/game-design-service/src/main/resources/db/migration/V18__published_plugin_versions.sql) | [AutomationPluginControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPluginControlPlaneServiceTest.java); [PluginActivationPreflightServiceImplTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/PluginActivationPreflightServiceImplTest.java); [AutomationPatchControlPlaneServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationPatchControlPlaneServiceTest.java); [AutomationScriptingControlPlaneGrpcServiceTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/service/impl/AutomationScriptingControlPlaneGrpcServiceTest.java) | [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: signed plugin and script-patch publication/readiness seams exist, but live compatibility preflight uses Automation's aggregate participant digest instead of the required dedicated Game Logic-owned ability-schema attestation. Canonical ability-schema compatibility, broader mod/extension package formats, creator tooling, distribution lifecycle, complete runtime readiness convergence, and complete target signature-set persistence/exposure remain incomplete. Current live intake selects, persists, and exposes one allowlisted `signerKeyId`, not the complete target `verifiedSignatures[]` set. ADR 0111 owns the accepted target provenance and lifecycle boundary. | | `AR-1.4` Game-authored assets, branding, and release manifests | `partial` | `proven` only for controlled-input ordinary asset-source creation and synchronized projection, with focused proof in `GameDesignSourcePostgresIntegrationTest` and `VersionAssetExportSnapshotIntegrationTest`; production authoring ingress and the full publication workflow, durable object-store proof, purge, and runtime delivery remain absent or unproved. Earlier frozen-origin, snapshot-integrity, candidate export/readback, and release-v2 selector migration proof retains its exact historical attribution below. | [Game Design asset storage](../../architecture/microservices/game-design-service/asset-storage.md); [Game Design Version Control](../../architecture/microservices/game-design-service/version-control.md); [game customization](../../architecture/system-architecture-game-customization.md); [versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md) | [AssetExportServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/AssetExportServiceImpl.java); [VersionAssetArtifactServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImpl.java); [VersionAssetExportCandidateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImpl.java); [VersionAssetPublicationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionAssetPublicationRepository.java); [PublishedReleaseBundleServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImpl.java); [PublishedReleaseBundleContract.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContract.java); [V8 release bundle](../../../services/game-design-service/src/main/resources/db/migration/V8__published_release_bundle.sql); [V10 asset artifact](../../../services/game-design-service/src/main/resources/db/migration/V10__version_asset_artifact.sql); [V35.2 canonical release version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V37 mapping and export snapshot](../../../services/game-design-service/src/main/resources/db/migration/V37__version_asset_export_snapshot.sql); [V38 published asset digest evidence](../../../services/game-design-service/src/main/resources/db/migration/V38__published_asset_digest_evidence.sql); [V49 published-world selector evidence](../../../services/game-design-service/src/main/resources/db/migration/V49__published_world_start_location_evidence.sql); [V49.1 selected-world release participant schema](../../../services/game-design-service/src/main/resources/db/migration/V49.1__selected_world_release_participant_schema.sql); [V50 frozen candidate origin](../../../services/game-design-service/src/main/resources/db/migration/V50__freeze_asset_export_candidate_public_origin.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [AssetExportServiceImplTest.java](../../../services/game-design-service/src/test/java/net/firedevops/firemud/gamedesign/service/AssetExportServiceImplTest.java); [VersionAssetExportCandidateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetExportCandidateServiceImplTest.java); [VersionAssetArtifactServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionAssetArtifactServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [PublishedReleaseBundleContractTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleContractTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [PublishedWorldSelectorSchemaMigrationIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/PublishedWorldSelectorSchemaMigrationIntegrationTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java) | [platform operations](./platform-operations-and-delivery.md); [player experience](./player-experience-commands-and-communication.md) | Partial: the current source includes Draft `version_asset` mappings, a durable version-scoped export snapshot with independent readback, candidate export/readback, and immutable v1 bundle storage with canonical identity, opaque reference, manifest-schema metadata, and artifact digests. Release-v2 selector binding is enforced by `PublishedReleaseBundleContract.requireSelectorBinding`; current pinned-source physical proof covers V49 and V49.1, the frozen V50 candidate origin, and database-computed snapshot hash/length verification. Normal export consumes the frozen snapshot and records candidate manifest/artifact digest evidence before object writes; published repair independently reads the immutable candidate and checks it against the exact release bundle before object writes. Production authoring ingress remains absent, so public and registered Temporal full-version ingress fails closed before mutation. Complete Draft quota admission, unbounded whole-selection hash work, durable object-store candidate isolation, integrated lifecycle migration closure, global publication/purge fencing, destructive lifecycle safety, complete creator UX, approved external delivery, and runtime launch readiness remain incomplete or unproved. Ordinary asset-source creation and synchronized projection are owned by `AssetSourceRepository` and `GameDesignSourceRepository`; direct `associateDraftAsset` fails closed. Migration V1003 establishes ordinary asset source storage and V1024 binds reviewed-base evidence to its asset. | -| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Historical published source proof checkpoint `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The combined local proof described above covers the V50.15 owner-list guard and exact publication-terminal denial assertions; current-head source Validation `38361682862` (job `115177242916`) independently confirms all 476 unit and 114 physical PostgreSQL cases pass without skips on published `3e8126217206419bc379497988884739a8e1fda0`. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 3, and the full-Version gate requires schema 3. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | +| `AR-1.5` Revisions, versions, publishing, validation, and attestation | `partial` | `proven` for focused immutable-source unit/static boundaries and the fail-closed publish gate, exact terminal replay, release-bundle readback, and bounded participant-digest seams; current happy-path full-version publication and bundle creation are refused, and private finalization tests substitute a mocked bundle service; this does not prove historical revision/version lineage. Post-bundle failure reconciliation and same-commit attestation convergence, complete digest/attestation tuples, and the end-to-end publication-bound generation proof remain unproved. Historical lineage remains a retained-data deployment blocker: the owner must record a verified no-data boundary or explicit retained-row disposition/mapping with exact readback before migration cleanup or any completion claim. Historical published source proof checkpoint `9bf78e22f742c3830821c920e70570eb1bc03e2b`: Validation `38354137185` (source job `115153084495`) physically executed 473 unit and 109 physical PostgreSQL cases with zero skips. The local primary log `gameplay3120-cli4-full-gds-proof.log` covers 05:45:24–05:49:53; after the nullable-query assertion fixes, `gameplay3120-cli4-final-affected-proof.log` records 27 affected physical PostgreSQL cases with zero skips at 05:52–05:54. Formatting/fullCheck, Checkstyle, and all three SpotBugs tasks passed on those matching postimages. The combined local proof described above covers the V50.15 owner-list guard and exact publication-terminal denial assertions; current-head source Validation `38361682862` (job `115177242916`) independently confirms all 476 unit and 114 physical PostgreSQL cases pass without skips on published `3e8126217206419bc379497988884739a8e1fda0`. This checkpoint does not claim new-head CI, packaged-runtime, full-workflow, or runtime-activation completion. The bounded Entity/Automation selected-source intake and terminal-read slice has focused source/storage/transport proof at `f9e3f879d137b9a6fa54085e9c0b797586636a00`. The shared selected-source digest helper was introduced at `fdcc676597d33a154c92967baf33ad540387ddf8`; it is absent at `f9e3f879d137b9a6fa54085e9c0b797586636a00` and present at the later `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` Entity checkpoint. The current-source Entity execution at `17c82ab6462868a2f66dfe8a3cbc737bdd013383` passed 44 cases across seven suites in 67.986 seconds with zero failures, errors, or skips. Its 11-case physical PostgreSQL `EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow`; that test calls the Entity digest reader and compares the returned digest with an independently framed expected value. This was a focused gate, not a fresh whole-service Entity run. Separately, the exact-source Automation gate at `f2d3142214654736c224cb02f817d33f751b744d` passed 33 cases across eight suites in 75.453 seconds with zero failures, errors, or skips: 20 unit cases, nine physical PostgreSQL repository cases, three mocked service-integration cases, and one actual terminal-read mTLS/PostgreSQL case. The six-case physical PostgreSQL `AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest` included `selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest`. The earlier Entity attribution at `a5d501ca95f30a6dd86fc7a24290d443fb75fba4` remains a separate historical checkpoint and is not part of the Automation aggregate. The Entity digest receiver unit result belongs to initial `e2c38ec63dc3664877ee0f7c8fb62ef6574777ce`: 917 Common, 187 Common Security, and 23 Entity unit cases passed on unchanged postimages, but that aggregate failed at test compilation. The receiver result does not establish a fresh whole-service aggregate. The slice remains standalone and unregistered; this proof does not establish complete owner publication, registration, or runtime activation. | [Versioning/runtime](../../architecture/system-architecture-versioning-runtime.md); [promotion attestation](../../architecture/system-architecture-promotion-attestation.md); [Game Design API contracts](../../architecture/microservices/game-design-service/api-contracts.md); [ADR 0093](../../architecture/decisions/adr-0093-game-design-coordinated-digest-attested-content-publication.md); [ADR 0094](../../architecture/decisions/adr-0094-explicit-cohesive-runtime-release-tuples.md); [ADR 0095](../../architecture/decisions/adr-0095-content-addressed-published-assets-with-cas-lifecycle-authority.md); [ADR 0096](../../architecture/decisions/adr-0096-attested-publication-gate-and-quarantined-failed-assets.md); [ADR 0098](../../architecture/decisions/adr-0098-request-bounded-generation-replay-and-explicit-regeneration.md); [ADR 0099](../../architecture/decisions/adr-0099-bounded-atomic-generation-with-staging-for-large-outputs.md); [ADR 0100](../../architecture/decisions/adr-0100-separate-generation-ingress-with-one-world-owned-engine.md); [ADR 0101](../../architecture/decisions/adr-0101-explicit-destructive-regeneration-with-previewed-scope.md); [ADR 0102](../../architecture/decisions/adr-0102-first-class-sparse-and-full-grid-world-topologies.md); [Entity selected-source contracts](../../architecture/microservices/entity-management-service/api-contracts.md); [Automation selected-source contracts](../../architecture/microservices/automation-scripting-service/api-contracts.md) | [RevisionServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImpl.java); [VersionPublishCommandServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImpl.java); [PublishGateServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImpl.java); [TemporalVersionPublishWorkflowImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/TemporalVersionPublishWorkflowImpl.java); [V9 publish attempt](../../../services/game-design-service/src/main/resources/db/migration/V9__publish_attempt_framework.sql); [V14 recorded digests](../../../services/game-design-service/src/main/resources/db/migration/V14__recorded_participant_digest.sql); [V35.1 canonical Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.1__canonical_version_identity.sql); [V35.2 canonical release Version identity](../../../services/game-design-service/src/main/resources/db/migration/V35.2__canonical_release_version_identity.sql); [V36 opaque bundle reference](../../../services/game-design-service/src/main/resources/db/migration/V36__persist_opaque_published_release_bundle_reference.sql); [V39 publication evidence text](../../../services/game-design-service/src/main/resources/db/migration/V39__publication_evidence_text_storage.sql); [PublishedReleaseBundleRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepository.java); [VersionRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/repository/VersionRepository.java) ; [CommandSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/CommandSourceRepository.java); [RealmPolicySourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicySourceRepository.java); [RealmPolicyPublicationGrpcService.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcService.java); [GameDesignPublicationOperationRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignPublicationOperationRepository.java); [GameDesignReviewedBaseRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/draft/GameDesignReviewedBaseRepository.java); [V50.1 Draft coordination](../../../services/game-design-service/src/main/resources/db/migration/V50.1__durable_draft_commit_coordination.sql); [V50.2 authored selection](../../../services/game-design-service/src/main/resources/db/migration/V50.2__authored_draft_publish_selection.sql); [V50.6 terminal seal](../../../services/game-design-service/src/main/resources/db/migration/V50.6__publication_operation_terminal_seal.sql); [V50.8 realm-policy source](../../../services/game-design-service/src/main/resources/db/migration/V50.8__immutable_realm_policy_source.sql); [V50.9 policy publication evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.9__sealed_realm_policy_publication_evidence.sql); [V50.10 command source](../../../services/game-design-service/src/main/resources/db/migration/V50.10__immutable_command_source.sql); [V50.11 reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V50.11__immutable_reviewed_draft_base.sql); [V50.12 policy head transitions](../../../services/game-design-service/src/main/resources/db/migration/V50.12__realm_policy_source_head_transition_guard.sql); [V50.13 stable publication release-row receipt evidence](../../../services/game-design-service/src/main/resources/db/migration/V50.13__stable_publication_release_row_evidence.sql); [V50.14 Draft visibility and realm-policy source-head guards](../../../services/game-design-service/src/main/resources/db/migration/V50.14__draft_visibility_and_realm_policy_source_insert_guards.sql) ; [V50.15 required-owner binding guards](../../../services/game-design-service/src/main/resources/db/migration/V50.15__draft_commit_required_owner_guards.sql); [V50.16 reviewed source-application guards](../../../services/game-design-service/src/main/resources/db/migration/V50.16__reviewed_source_application_guards.sql); [AssetSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/AssetSourceRepository.java); [GameDesignSourceRepository.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/publication/GameDesignSourceRepository.java); [V1003 ordinary asset source](../../../services/game-design-service/src/main/resources/db/migration/V1003__ordinary_asset_source.sql); [V1024 asset-bound reviewed base](../../../services/game-design-service/src/main/resources/db/migration/V1024__asset_bound_reviewed_draft_base.sql); [EntityEmptySelectedSourceIntakeService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java); [EntityEmptySelectedSourceIntakeTerminalReadService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java); [EntitySelectedEmptyPublicationDigestService.java](../../../services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java); [AutomationEmptySelectedSourceIntakeService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java); [AutomationEmptySelectedSourceIntakeTerminalReadService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java); [AutomationSelectedEmptyPublicationDigestService.java](../../../services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java) | [RevisionServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RevisionServiceImplTest.java); [PublishGateServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishGateServiceImplTest.java); [VersionPublishCommandServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/VersionPublishCommandServiceImplTest.java); [PublishedReleaseBundleServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/PublishedReleaseBundleServiceImplTest.java); [ControlPlaneDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/ControlPlaneDigestServiceImplTest.java); [RecordedParticipantDigestServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/RecordedParticipantDigestServiceImplTest.java); [TestDataSeederIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/data/TestDataSeederIntegrationTest.java); [PublishedReleaseBundleRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/PublishedReleaseBundleRepositoryTest.java); [LaunchDescriptorRepositoryTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/repository/LaunchDescriptorRepositoryTest.java) ; [RealmPolicyPublicationPostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationPostgresIntegrationTest.java); [RealmPolicySourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/RealmPolicySourcePostgresIntegrationTest.java); [GameDesignSourcePostgresIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/draft/GameDesignSourcePostgresIntegrationTest.java); [CommandSourceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/CommandSourceTest.java); [RealmPolicyPublicationGrpcServiceTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/publication/RealmPolicyPublicationGrpcServiceTest.java); [VersionAssetExportSnapshotIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/repository/VersionAssetExportSnapshotIntegrationTest.java); [EntityRetainedAuthoredActorCoreSourceServiceTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java); [AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java); [EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java); [AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java](../../../services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java); [EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java); [AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java](../../../services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java) | [world runtime](./world-runtime-and-movement.md); [gameplay](./gameplay-rules-entities-and-effects.md); [automation](./automation-and-scheduler-runtime.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [realm routing](./realm-routing-and-playable-state.md); [shared runtime](./shared-runtime-contracts-and-persistence.md) | Partial immutable command/realm-policy source, reviewed-base and terminal-seal capability with focused unit/static proof; Partial: fresh and PENDING full-version publication and legacy bundle creation fail closed; exact terminal replay and bundle readback seams exist. Participant tokens remain synthetic; World emits digest schema 3, and the full-Version gate requires schema 3. The bundle read projects optional manifest-schema and artifact-digest fields, but canonical target-commit provenance and actual-byte producer population remain unproved, so same-commit attestation convergence is not established. Historical revision/version lineage remains a retained-data deployment blocker requiring exact readback before migration cleanup or any completion claim. Complete digest/attestation tuples and the end-to-end publication-bound generation proof remain incomplete. | | `AR-2.1` Typed settings, defaults, scopes, and precedence | `partial` | `proven` for typed settings metadata/defaults, persisted overrides, effective resolution, and command-capability resolution seams; selected presets, operator bootstrap/runtime layers, safety caps, complete precedence proof, and all scoped consumers remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedEffectiveSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolver.java); [FiremudCommandCapabilitiesProperties.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/config/FiremudCommandCapabilitiesProperties.java); [platform settings publication](../../../config/settings/platform-settings-publication.json); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [platform operations](./platform-operations-and-delivery.md); [world runtime](./world-runtime-and-movement.md) | Partial: typed defaults, scopes, persisted overrides, and effective resolution exist, but selected presets, operator bootstrap/runtime layers, caps, and their precedence proof are not implemented. ADR 0012 is accepted and owns the target precedence and constraint contract. | | `AR-2.2` Feature, command, profile, and capability policy | `partial` | `proven` for command-capability resolution, feature-flag, published-command admission, and interpreter seams; complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [player command model](../../architecture/system-architecture-player-command-model.md); [feature flags](../../architecture/microservices/game-design-service/feature-flags.md); [game templates](../../architecture/microservices/game-design-service/game-templates.md); [ADR 0124](../../architecture/decisions/adr-0124-materialized-starter-profiles-with-conservative-draft-upgrades.md) | [EffectiveCommandCapabilitiesSettingsResolver.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolver.java); [FeatureFlagServiceImpl.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/service/impl/FeatureFlagServiceImpl.java); [AggregatingTextCommandRegistry.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistry.java); [AdmittedTextCommandRegistryResolver.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolver.java); [V23 published commands](../../../services/game-design-service/src/main/resources/db/migration/V23__published_command_definitions.sql) | [EffectiveCommandCapabilitiesSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/EffectiveCommandCapabilitiesSettingsResolverTest.java); [AggregatingTextCommandRegistryTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AggregatingTextCommandRegistryTest.java); [AdmittedTextCommandRegistryResolverTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/AdmittedTextCommandRegistryResolverTest.java); [TextCommandInterpreterCapabilityTest.java](../../../services/game-session-service/src/test/java/unit/net/firedevops/firemud/gamesession/command/text/TextCommandInterpreterCapabilityTest.java) | [player experience](./player-experience-commands-and-communication.md); [player access](./player-access-and-session.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [automation](./automation-and-scheduler-runtime.md); [platform operations](./platform-operations-and-delivery.md) | Partial: command capability resolution, feature flags, and published command admission exist, but the complete profile/capability catalog, starter-profile behavior, and full policy-consumer coverage are not implemented. ADR 0124 defines materialized starter-profile content and conservative Draft upgrades; implementation and focused proof remain incomplete. | | `AR-2.3` Tenant/game overrides, safety caps, validation, and effective configuration | `partial` | `proven` only for tenant/game settings persistence, validation, functional effective resolution/readback, and resolver seams; the current route authorization does not enforce tenant binding: the shared classifier accepts a tenant-scoped privileged role for any tenant and the controller accepts unbound tenant or session selectors, so cross-tenant effective-settings reads are currently possible. Cross-tenant denial proof is tracked separately and remains unproved. Safety caps, presets, complete hot-reload/invalidation, and all scoped consumers also remain unproved. | [Settings model](../../architecture/system-architecture-settings-model.md); [generated settings reference](../../architecture/generated/platform-settings-reference.md); [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md) | [SettingsAuthorityServiceImpl.java](../../../services/game-design-service/src/main/java/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImpl.java); [SharedSettingsAuthorityReader.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/SharedSettingsAuthorityReader.java); [GameDesignSettingsAuthorityClient.java](../../../services/common-platform-core/src/main/java/net/firedevops/firemud/common/settings/GameDesignSettingsAuthorityClient.java); [EffectiveSettingsController.java](../../../services/game-session-service/src/main/java/net/firedevops/firemud/gamesession/controller/EffectiveSettingsController.java); [V6 settings overrides](../../../services/game-design-service/src/main/resources/db/migration/V6__game_settings_overrides.sql) | [SettingsAuthorityServiceImplTest.java](../../../services/game-design-service/src/test/java/unit/net/firedevops/firemud/gamedesign/service/impl/SettingsAuthorityServiceImplTest.java); [SettingsAuthorityServiceIntegrationTest.java](../../../services/game-design-service/src/test/java/integration/net/firedevops/firemud/gamedesign/service/SettingsAuthorityServiceIntegrationTest.java); [SharedEffectiveSettingsResolverTest.java](../../../services/common-platform-core/src/test/java/net/firedevops/firemud/common/settings/SharedEffectiveSettingsResolverTest.java); [EffectiveSettingsControllerIntegrationTest.java](../../../services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/controller/EffectiveSettingsControllerIntegrationTest.java) | [shared runtime](./shared-runtime-contracts-and-persistence.md); [world runtime](./world-runtime-and-movement.md); [Game Session runtime](./game-session-runtime-and-tick-coordination.md); [platform operations](./platform-operations-and-delivery.md) | Partial: tenant/game persistence, validation, and functional effective readback/resolver seams exist, but route-aware authorization, scoped/global role binding, cross-tenant denial proof, safety caps, presets, complete hot-reload/invalidation, and all scoped consumers remain incomplete under accepted [ADR 0012](../../architecture/decisions/adr-0012-settings-value-precedence-and-constraints.md); implementation and proof gaps remain. | diff --git a/protos/automation-scripting/v1/automation_selected_source_intake_command.proto b/protos/automation-scripting/v1/automation_selected_source_intake_command.proto new file mode 100644 index 0000000000..2454b5a8b7 --- /dev/null +++ b/protos/automation-scripting/v1/automation_selected_source_intake_command.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package automation_scripting.v1; +option java_package = "net.firedevops.firemud.automationscripting.v1"; +option java_multiple_files = true; + +import "world-management/v1/world_selected_draft_publication_freeze_service.proto"; + +// Standalone and unregistered. Authenticated same-namespace Game Design may retain its exact +// Account-authorized selected-source intake after the exact World freeze has committed. +service AutomationSelectedSourceIntakeCommandService { + rpc RetainSelectedSource(RetainSelectedSourceRequest) + returns (RetainSelectedSourceResponse); +} + +message RetainSelectedSourceRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string transport_request_id = 3; + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; + world_management.v1.BeginVersionPublicationFreezeRequest freeze_request = 6; + world_management.v1.BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7; +} + +message RetainSelectedSourceResponse { + RetainSelectedSourceRequest request = 1; + bytes committed_empty_receipt = 2; + string receipt_digest = 3; +} diff --git a/protos/entity-management/v1/entity_selected_source_intake_command.proto b/protos/entity-management/v1/entity_selected_source_intake_command.proto new file mode 100644 index 0000000000..a29f838b30 --- /dev/null +++ b/protos/entity-management/v1/entity_selected_source_intake_command.proto @@ -0,0 +1,30 @@ +syntax = "proto3"; + +package entity_management.v1; +option java_package = "net.firedevops.firemud.entitymanagement.v1"; +option java_multiple_files = true; + +import "world-management/v1/world_selected_draft_publication_freeze_service.proto"; + +// Standalone and unregistered. Authenticated same-namespace Game Design may retain its exact +// Account-authorized selected Entity inputs after the exact World freeze has committed. +service EntitySelectedSourceIntakeCommandService { + rpc RetainSelectedEntitySource(RetainSelectedEntitySourceRequest) + returns (RetainSelectedEntitySourceResponse); +} + +message RetainSelectedEntitySourceRequest { + uint32 schema_version = 1; + string target_namespace = 2; + string transport_request_id = 3; + bytes original_intake_authorization_binding = 4; + string intake_authorization_digest = 5; + world_management.v1.BeginVersionPublicationFreezeRequest freeze_request = 6; + world_management.v1.BeginVersionPublicationFreezeResponse freeze_acknowledgement = 7; +} + +message RetainSelectedEntitySourceResponse { + RetainSelectedEntitySourceRequest request = 1; + bytes committed_empty_receipt = 2; + string receipt_digest = 3; +} diff --git a/services/automation-scripting-service/build.gradle.kts b/services/automation-scripting-service/build.gradle.kts index 50a061526d..1b98dd941d 100644 --- a/services/automation-scripting-service/build.gradle.kts +++ b/services/automation-scripting-service/build.gradle.kts @@ -9,4 +9,19 @@ plugins { dependencies { compileOnly(libs.spotbugs.annotations) + testImplementation(testFixtures(project(":common-test-support"))) +} + +// Export only owner classes for composed proofs; application and Flyway resources stay local. +val automationClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val automationClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(automationClassesProofJar) } diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java new file mode 100644 index 0000000000..720ceb6938 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeRepository.java @@ -0,0 +1,569 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered persistence boundary for immutable, freshly founded empty Automation receipts. + * + *

The source-family census is deliberately direct: absent associations never prove empty + * storage. This bounded schema only creates empty-source associations, so any row matching one of + * them is also a contradiction; rows without such a positive association are unqualified and deny a + * new founding. + */ +public final class AutomationEmptySelectedSourceIntakeRepository { + private static final String ASSOCIATION = "automation_empty_selected_source_association"; + private static final String RECEIPT = "automation_empty_selected_source_receipt"; + private static final String RESERVATION = "automation_empty_source_numeric_key_reservation"; + + private static final String READ_RECEIPT = + "SELECT a.target_namespace, a.operation_id, a.fence_id, a.intake_request_id, " + + "a.canonical_tenant_id, a.canonical_version_id, a.selected_commit_id, " + + "a.source_revision_id, a.source_revision_order, a.local_tenant_key, " + + "a.local_version_key, a.request_digest, a.authorization_binding_digest, " + + "a.receipt_digest, a.associated_at, r.request_digest, r.receipt_digest, " + + "r.receipt_bytes, r.retained_at FROM " + + ASSOCIATION + + " a LEFT JOIN " + + RECEIPT + + " r ON r.target_namespace = a.target_namespace " + + "AND r.intake_request_id = a.intake_request_id " + + "WHERE a.target_namespace = ? AND a.intake_request_id = ?"; + + private final DSLContext dsl; + + public AutomationEmptySelectedSourceIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** Reads only a committed receipt; absence is not interpreted as abort or terminal settlement. */ + public Optional read( + String targetNamespace, UUID intakeRequestId) { + requireNoAmbientOwnerSql("Automation source receipt read"); + requireReadKey(targetNamespace, intakeRequestId); + return readValidated(dsl, targetNamespace, intakeRequestId); + } + + /** + * Resolves the one immutable selected-empty receipt for a canonical tenant and Game Design + * Version row. Every association in the tenant prefix is fully read back before its retained + * original TargetProof is considered; owner-local numeric keys are not publication identity. + */ + public AutomationEmptySelectedSourceIntakeReceipt readPublicationScope( + String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + requireNoAmbientOwnerSql("Automation publication receipt read"); + requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId); + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var associations = + tx.fetch( + "SELECT canonical_version_id, intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "ORDER BY canonical_version_id", + targetNamespace, + canonicalTenantId); + if (associations.isEmpty()) { + throw new IllegalStateException( + "Automation selected-empty publication receipt is unavailable"); + } + + var matches = new ArrayList(); + for (Record association : associations) { + UUID associatedCanonicalVersionId = association.get(0, UUID.class); + UUID intakeRequestId = association.get(1, UUID.class); + if (associatedCanonicalVersionId == null || intakeRequestId == null) { + throw new CorruptReceiptException( + "Automation publication association identity is corrupt"); + } + AutomationEmptySelectedSourceIntakeReceipt receipt = + readValidated(tx, targetNamespace, intakeRequestId) + .orElseThrow( + () -> + new CorruptReceiptException( + "Automation publication association has no committed receipt")); + var target = receipt.authorizationBinding().selected().target(); + if (!canonicalTenantId.equals(receipt.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { + throw new CorruptReceiptException( + "Automation publication association differs from the retained selected target"); + } + if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { + matches.add(receipt); + } + } + if (matches.size() != 1) { + throw new IllegalStateException( + "Automation selected-empty publication scope is missing or ambiguous"); + } + return matches.get(0); + }); + } + + /** + * Reads the original committed receipt for an exact finalized Account authorization. A missing + * result remains absence; it is never converted into an abort or another terminal value. + */ + public Optional readCommittedTerminal( + SelectedOwnerIntakeAuthorizationBinding originalBinding) { + Objects.requireNonNull(originalBinding, "original Account authorization binding is required"); + if (originalBinding.owner() != Owner.AUTOMATION_SCRIPTING + || !"account-automation-intake-authorization/v1".equals(originalBinding.schema()) + || !"AUTOMATION_INTAKE_RETENTION".equals(originalBinding.purpose())) { + throw new IllegalArgumentException("Exact original Automation authorization is required"); + } + requireNoAmbientOwnerSql("Automation source terminal read"); + requireReadKey(originalBinding.targetNamespace(), originalBinding.intakeRequestId()); + var receipt = + readValidated(dsl, originalBinding.targetNamespace(), originalBinding.intakeRequestId()); + if (receipt.isPresent() + && !Arrays.equals( + originalBinding.canonicalBytes(), receipt.orElseThrow().authorizationBindingBytes())) { + throw new IntakeConflictException( + "Automation committed receipt differs from the complete original authorization"); + } + return receipt; + } + + /** + * Persists one fresh empty-source receipt in an independent local transaction, then reads it back + * after commit using a separate non-transactional owner read. + */ + public AutomationEmptySelectedSourceIntakeReceipt retainFresh( + SelectedOwnerEmptySourceInputs inputs, String requestDigest) { + Objects.requireNonNull(inputs, "validated selected empty-source inputs are required"); + SelectedOwnerIntakeAuthorizationBinding binding = inputs.authorizationBinding(); + String expectedDigest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), + binding, + inputs.worldInventoryReadEvidence().request().freezeEvidence()); + if (!expectedDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Automation source intake request digest differs"); + } + if (binding.owner() != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalArgumentException("Automation owner evidence is required"); + } + requireNoAmbientOwnerSql("Automation source intake transaction"); + + AutomationEmptySelectedSourceIntakeReceipt committed = + dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + lockAllocatorAndAssociations(tx); + lockSourceFamilies(tx); + + // This is the exact request/operation/scope phase of the lock order. A competing + // local founder has already completed its source census before these rows are read. + var previous = + readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); + if (previous.isPresent()) { + AutomationEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); + receipt.requireSameInputs(inputs); + return receipt; + } + requireNoPriorScopeOrOperation(tx, binding); + + Census census = censusAllSourceFamilies(tx); + census.requireFreshFoundingAllowed(); + + long maximumOccupiedKey = maximumOccupiedNumericKey(tx); + long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); + long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); + Census selectedScope = + censusSelectedNumericScope(tx, localTenantKey, localVersionKey); + selectedScope.requireSelectedScopeEmpty(); + + reserveCanonicalKey(tx, "TENANT", localTenantKey); + reserveCanonicalKey(tx, "VERSION", localVersionKey); + OffsetDateTime retainedAt = + requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) + .withOffsetSameInstant(ZoneOffset.UTC); + AutomationEmptySelectedSourceIntakeReceipt receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + localTenantKey, + localVersionKey, + requestDigest, + census.scriptsRows(), + census.eventBindingRows(), + census.patchBaseBindingRows(), + census.unqualifiedScriptsRows(), + census.unqualifiedEventBindingRows(), + census.unqualifiedPatchBaseBindingRows(), + census.emptyAssociatedScriptsRows(), + census.emptyAssociatedEventBindingRows(), + census.emptyAssociatedPatchBaseBindingRows(), + selectedScope.scriptsRows(), + selectedScope.eventBindingRows(), + selectedScope.patchBaseBindingRows(), + retainedAt); + + insertAssociation(tx, receipt, retainedAt); + insertReceipt(tx, receipt, retainedAt); + return receipt; + }); + + AutomationEmptySelectedSourceIntakeReceipt readBack = + read(committed.targetNamespace(), committed.intakeRequestId()) + .orElseThrow( + () -> + new CorruptReceiptException( + "Committed Automation source receipt is unavailable")); + if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes()) + || !committed.receiptDigest().equals(readBack.receiptDigest()) + || !committed.requestDigest().equals(readBack.requestDigest())) { + throw new CorruptReceiptException("Committed Automation source receipt readback differs"); + } + return readBack; + } + + private static void lockAllocatorAndAssociations(DSLContext tx) { + tx.execute( + "LOCK TABLE " + + RESERVATION + + ", " + + ASSOCIATION + + ", " + + RECEIPT + + " IN SHARE ROW EXCLUSIVE MODE"); + } + + private static void lockSourceFamilies(DSLContext tx) { + // Fixed order shared with the source-owner allocation protocol. + tx.execute( + "LOCK TABLE script_event_bindings, script_patch_base_bindings, scripts IN SHARE MODE"); + } + + private static void requireNoPriorScopeOrOperation( + DSLContext tx, SelectedOwnerIntakeAuthorizationBinding binding) { + Record prior = + tx.fetchOne( + "SELECT intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND ((canonical_tenant_id = ? " + + "AND canonical_version_id = ?) OR operation_id = ?) LIMIT 1", + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.operationId()); + if (prior != null) { + throw new IntakeConflictException( + "Automation canonical scope or owner operation is already associated"); + } + } + + private static Census censusAllSourceFamilies(DSLContext tx) { + long scripts = count(tx, "SELECT COUNT(*) FROM scripts"); + long eventBindings = count(tx, "SELECT COUNT(*) FROM script_event_bindings"); + long patchBaseBindings = count(tx, "SELECT COUNT(*) FROM script_patch_base_bindings"); + + long unqualifiedScripts = + count( + tx, + "SELECT COUNT(*) FROM scripts s WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = s.tenant_id " + + "AND a.local_version_key = s.base_version_id)"); + long unqualifiedEventBindings = + count( + tx, + "SELECT COUNT(*) FROM script_event_bindings b WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = b.tenant_id " + + "AND a.local_version_key = b.base_version_id)"); + long unqualifiedPatchBaseBindings = + count( + tx, + "SELECT COUNT(*) FROM script_patch_base_bindings b WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = " + + "automation_source_positive_numeric_key(b.tenant_id) " + + "AND a.local_version_key = b.base_version_id)"); + + return new Census( + scripts, + eventBindings, + patchBaseBindings, + unqualifiedScripts, + unqualifiedEventBindings, + unqualifiedPatchBaseBindings, + scripts - unqualifiedScripts, + eventBindings - unqualifiedEventBindings, + patchBaseBindings - unqualifiedPatchBaseBindings); + } + + private static Census censusSelectedNumericScope(DSLContext tx, long tenantKey, long versionKey) { + long scripts = + count( + tx, + "SELECT COUNT(*) FROM scripts WHERE tenant_id = ? OR base_version_id = ?", + tenantKey, + versionKey); + long eventBindings = + count( + tx, + "SELECT COUNT(*) FROM script_event_bindings WHERE tenant_id = ? " + + "OR base_version_id = ?", + tenantKey, + versionKey); + long patchBaseBindings = + count( + tx, + "SELECT COUNT(*) FROM script_patch_base_bindings WHERE " + + "automation_source_positive_numeric_key(tenant_id) = ? " + + "OR base_version_id = ?", + tenantKey, + versionKey); + return new Census(scripts, eventBindings, patchBaseBindings, 0L, 0L, 0L, 0L, 0L, 0L); + } + + private static long maximumOccupiedNumericKey(DSLContext tx) { + return requiredScalar( + tx, + "SELECT COALESCE(MAX(occupied_key), 0) FROM (" + + "SELECT numeric_key AS occupied_key FROM " + + RESERVATION + + " UNION ALL SELECT tenant_id FROM scripts" + + " UNION ALL SELECT base_version_id FROM scripts WHERE base_version_id IS NOT NULL" + + " UNION ALL SELECT tenant_id FROM script_event_bindings" + + " UNION ALL SELECT base_version_id FROM script_event_bindings " + + "WHERE base_version_id IS NOT NULL" + + " UNION ALL SELECT automation_source_positive_numeric_key(tenant_id) " + + "FROM script_patch_base_bindings" + + " UNION ALL SELECT base_version_id FROM script_patch_base_bindings" + + ") AS occupied", + Long.class); + } + + private static void reserveCanonicalKey(DSLContext tx, String kind, long key) { + int inserted = + tx.execute( + "INSERT INTO " + + RESERVATION + + " (key_kind, numeric_key, claim_kind) VALUES (?, ?, 'CANONICAL_EMPTY_SOURCE')", + kind, + key); + if (inserted != 1) { + throw new IntakeConflictException("Automation source numeric key was not reserved"); + } + } + + private static void insertAssociation( + DSLContext tx, + AutomationEmptySelectedSourceIntakeReceipt receipt, + OffsetDateTime retainedAt) { + int inserted = + tx.execute( + "INSERT INTO " + + ASSOCIATION + + " (target_namespace, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, " + + "local_version_key, request_digest, authorization_binding_digest, " + + "receipt_digest, associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.operationId(), + receipt.fenceId(), + receipt.intakeRequestId(), + receipt.canonicalTenantId(), + receipt.canonicalVersionId(), + receipt.selectedCommitId(), + receipt.sourceRevisionId(), + receipt.sourceRevisionOrder(), + receipt.localTenantKey(), + receipt.localVersionKey(), + receipt.requestDigest(), + receipt.authorizationBindingDigest(), + receipt.receiptDigest(), + retainedAt); + if (inserted != 1) { + throw new IntakeConflictException("Automation source scope association was not inserted"); + } + } + + private static void insertReceipt( + DSLContext tx, + AutomationEmptySelectedSourceIntakeReceipt receipt, + OffsetDateTime retainedAt) { + int inserted = + tx.execute( + "INSERT INTO " + + RECEIPT + + " (target_namespace, intake_request_id, request_digest, receipt_digest, " + + "receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.requestDigest(), + receipt.receiptDigest(), + receipt.canonicalBytes(), + retainedAt); + if (inserted != 1) { + throw new IntakeConflictException("Automation source receipt was not inserted"); + } + } + + private static Optional readValidated( + DSLContext context, String namespace, UUID requestId) { + Record record = context.fetchOne(READ_RECEIPT, namespace, requestId); + if (record == null) { + return Optional.empty(); + } + byte[] receiptBytes = record.get(17, byte[].class); + if (receiptBytes == null) { + throw new CorruptReceiptException("Automation source association has no retained receipt"); + } + final AutomationEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + } catch (RuntimeException malformed) { + throw new CorruptReceiptException("Automation stored source receipt is corrupt"); + } + if (!Objects.equals(record.get(0, String.class), receipt.targetNamespace()) + || !Objects.equals(record.get(1, UUID.class), receipt.operationId()) + || !Objects.equals(record.get(2, UUID.class), receipt.fenceId()) + || !Objects.equals(record.get(3, UUID.class), receipt.intakeRequestId()) + || !Objects.equals(record.get(4, UUID.class), receipt.canonicalTenantId()) + || !Objects.equals(record.get(5, UUID.class), receipt.canonicalVersionId()) + || !Objects.equals(record.get(6, UUID.class), receipt.selectedCommitId()) + || !Objects.equals(record.get(7, UUID.class), receipt.sourceRevisionId()) + || !Objects.equals(record.get(8, String.class), receipt.sourceRevisionOrder()) + || !Objects.equals(record.get(9, Long.class), receipt.localTenantKey()) + || !Objects.equals(record.get(10, Long.class), receipt.localVersionKey()) + || !Objects.equals(record.get(11, String.class), receipt.requestDigest()) + || !Objects.equals(record.get(12, String.class), receipt.authorizationBindingDigest()) + || !Objects.equals(record.get(13, String.class), receipt.receiptDigest()) + || !Objects.equals(record.get(15, String.class), receipt.requestDigest()) + || !Objects.equals(record.get(16, String.class), receipt.receiptDigest()) + || !sameInstant(record.get(18, OffsetDateTime.class), receipt.retainedAt()) + || !sameInstant(record.get(14, OffsetDateTime.class), receipt.retainedAt()) + || !Arrays.equals(receipt.canonicalBytes(), receiptBytes)) { + throw new CorruptReceiptException( + "Automation source receipt differs from its owner association"); + } + return Optional.of(receipt); + } + + private static long count(DSLContext context, String sql, Object... parameters) { + long value = requiredScalar(context, sql, Long.class, parameters); + if (value < 0L) { + throw new IllegalStateException("Automation source census returned an invalid count"); + } + return value; + } + + private static boolean sameInstant(OffsetDateTime actual, OffsetDateTime expected) { + return actual != null && expected != null && actual.toInstant().equals(expected.toInstant()); + } + + private static T requiredScalar( + DSLContext context, String sql, Class valueType, Object... parameters) { + Record record = context.fetchOne(sql, parameters); + if (record == null) { + throw new IllegalStateException("Automation owner query returned no row"); + } + T value = record.get(0, valueType); + if (value == null) { + throw new IllegalStateException("Automation owner query returned a null value"); + } + return value; + } + + private static void requireReadKey(String namespace, UUID requestId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace) || requestId == null) { + throw new IllegalArgumentException("Automation source receipt lookup identity is required"); + } + DraftAuthorizationFenceBinding.requireUuid(requestId); + } + + private static void requirePublicationScopeKey( + String namespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + if (!GrpcPeerIdentity.isValidNamespace(namespace) + || canonicalTenantId == null + || new UUID(0L, 0L).equals(canonicalTenantId) + || gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Automation publication scope identity is required"); + } + } + + private static void requireNoAmbientOwnerSql(String action) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException(action + " requires no ambient owner SQL"); + } + } + + private record Census( + long scriptsRows, + long eventBindingRows, + long patchBaseBindingRows, + long unqualifiedScriptsRows, + long unqualifiedEventBindingRows, + long unqualifiedPatchBaseBindingRows, + long emptyAssociatedScriptsRows, + long emptyAssociatedEventBindingRows, + long emptyAssociatedPatchBaseBindingRows) { + private void requireFreshFoundingAllowed() { + if (unqualifiedScriptsRows != 0L + || unqualifiedEventBindingRows != 0L + || unqualifiedPatchBaseBindingRows != 0L) { + throw new UnqualifiedSourceRowsException( + "Fresh Automation founding requires a positively owned empty source inventory"); + } + if (emptyAssociatedScriptsRows != 0L + || emptyAssociatedEventBindingRows != 0L + || emptyAssociatedPatchBaseBindingRows != 0L) { + throw new IntakeConflictException( + "An existing empty Automation association contains authored source rows"); + } + } + + private void requireSelectedScopeEmpty() { + if (scriptsRows != 0L || eventBindingRows != 0L || patchBaseBindingRows != 0L) { + throw new IntakeConflictException( + "Allocated Automation source scope is not empty across all source families"); + } + } + } + + public static class IntakeConflictException extends IllegalStateException { + public IntakeConflictException(String message) { + super(message); + } + } + + /** Indicates that retained receipt bytes or owner rows fail their immutable readback contract. */ + public static final class CorruptReceiptException extends IllegalStateException { + public CorruptReceiptException(String message) { + super(message); + } + } + + public static final class UnqualifiedSourceRowsException extends IntakeConflictException { + public UnqualifiedSourceRowsException(String message) { + super(message); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java new file mode 100644 index 0000000000..ede5a53395 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeService.java @@ -0,0 +1,175 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered preparation service for authenticated, freshly founded empty Automation scopes. + * + *

Account's HELD reads are point-in-time samples. They do not extend through Automation's local + * commit and do not settle the original Account source participation. + * + *

The shared selected-source value checks exact canonical bytes and typed snapshots for all six + * existing Game Design source families. Authenticated Account and World clients establish the + * remote read identities and HELD/inventory results; typed integrity alone does not authenticate + * either producer or establish continuous source-writer protection. + */ +public final class AutomationEmptySelectedSourceIntakeService { + private final AutomationEmptySelectedSourceIntakeRepository repository; + private final SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient; + private final SelectedOwnerWorldInventoryReadClient worldInventoryReadClient; + private final String namespace; + + public AutomationEmptySelectedSourceIntakeService( + AutomationEmptySelectedSourceIntakeRepository repository, + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient, + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient, + String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.authorizationReadClient = + Objects.requireNonNull(authorizationReadClient, "authorizationReadClient"); + this.worldInventoryReadClient = + Objects.requireNonNull(worldInventoryReadClient, "worldInventoryReadClient"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical namespace required"); + } + this.namespace = namespace; + } + + /** + * Returns an exact prior receipt for a lost-response retry, or prepares a fresh retention + * attempt. This operation does not create scripts, bindings, runtime markers, or activation + * state. + */ + public AutomationEmptySelectedSourceIntakeReceipt retain( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding originalBinding, + WorldSelectedDraftPublicationFreezeEvidence exactFreeze) { + requireAuthenticatedGameDesignCaller(); + if (!namespace.equals(targetNamespace)) { + throw new IllegalArgumentException( + "Automation intake target namespace differs from its configured namespace"); + } + requireNoAmbientOwnerSql(); + requireRequest(targetNamespace, originalBinding, exactFreeze); + String requestDigest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + targetNamespace, originalBinding, exactFreeze); + + // A committed receipt is authoritative for exact lost-response retries, even after Account's + // temporary HELD state has subsequently settled. It never implies that an unrecorded request + // was aborted. + var retained = repository.read(targetNamespace, originalBinding.intakeRequestId()); + if (retained.isPresent()) { + AutomationEmptySelectedSourceIntakeReceipt receipt = retained.orElseThrow(); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + SelectedOwnerIntakeAuthorizationReadEvidence.Request authorizationReadRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var authorizationEvidence = authorizationReadClient.read(authorizationReadRequest); + if (authorizationEvidence == null + || !authorizationReadRequest.equals(authorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the exact selected-owner read request"); + } + + SelectedOwnerWorldInventoryReadEvidence.Request worldReadRequest = + SelectedOwnerWorldInventoryReadEvidence.Request.create( + targetNamespace, originalBinding, exactFreeze); + var worldEvidence = worldInventoryReadClient.read(worldReadRequest); + if (worldEvidence == null || !worldReadRequest.equals(worldEvidence.request())) { + throw new IllegalStateException("World did not echo the exact selected-owner read request"); + } + + // This shared value validates only exact evidence integrity, complete supported inbound World + // closure, and the typed empty Automation declaration. The authenticated clients above—not + // the value itself—supply producer identity and HELD authorization. + SelectedOwnerEmptySourceInputs inputs = + new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence); + + // Re-sample HELD after the remote World read to reduce the gap before local commit. This is + // only a point-in-time observation: finalized pending Account source participation remains + // under its source-writer exclusion guards. This preparation neither extends nor settles or + // releases them. Account's separate exact Automation terminal settlement owns that release; + // this intake method does not invoke it, and unregistered construction is not activation proof. + SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationReadRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var finalAuthorizationEvidence = authorizationReadClient.read(finalAuthorizationReadRequest); + if (finalAuthorizationEvidence == null + || !finalAuthorizationReadRequest.equals(finalAuthorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the exact final HELD read request"); + } + + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(inputs, requestDigest); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + private void requireAuthenticatedGameDesignCaller() { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw new SecurityException("Authenticated same-namespace Game Design peer is required"); + } + if (AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null + || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null + || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null + || SessionContext.hasAuthenticatedCallerContext() + || !namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw new SecurityException( + "Selected Automation intake requires the exact same-namespace Game Design peer"); + } + } + + private static void requireRequest( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull(binding, "original Account authorization binding is required"); + Objects.requireNonNull(freezeEvidence, "exact World freeze is required"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.AUTOMATION_SCRIPTING + || !binding.schema().equals("account-automation-intake-authorization/v1") + || !binding.purpose().equals("AUTOMATION_INTAKE_RETENTION")) { + throw new IllegalArgumentException( + "Fresh Automation intake requires its exact finalized Account owner binding"); + } + var freeze = freezeEvidence.request(); + if (!targetNamespace.equals(freeze.targetNamespace()) + || !binding.tenantId().equals(freeze.canonicalTenantId()) + || !binding.versionId().equals(freeze.canonicalVersionId()) + || !binding + .selected() + .equals(freeze.accountBinding().input().selection().selectedCommit())) { + throw new IllegalArgumentException( + "Automation owner binding differs from the exact selected World freeze"); + } + } + + private static void requireNoAmbientOwnerSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account and World evidence reads must run outside Automation owner SQL"); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java new file mode 100644 index 0000000000..a1d9737a95 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeTerminalReadService.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Objects; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Standalone Account-only lookup over Automation's immutable selected-source receipt. */ +public final class AutomationEmptySelectedSourceIntakeTerminalReadService { + private final AutomationEmptySelectedSourceIntakeRepository repository; + private final String namespace; + + public AutomationEmptySelectedSourceIntakeTerminalReadService( + AutomationEmptySelectedSourceIntakeRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical namespace required"); + } + this.namespace = namespace; + } + + /** Called by the transport before request decoding so unauthorized peers never reach a lookup. */ + void requireAuthenticatedAccountCaller() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !"account-service".equals(peer.service()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } + + public AutomationSelectedSourceIntakeTerminalReadEvidence read( + AutomationSelectedSourceIntakeTerminalReadEvidence.Request request) { + requireAuthenticatedAccountCaller(); + Objects.requireNonNull(request, "terminal-read request is required"); + if (!namespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + + final AutomationEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = + repository + .readCommittedTerminal(request.binding()) + .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException()); + } catch (StatusRuntimeException denied) { + throw denied; + } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException changed) { + throw Status.ALREADY_EXISTS + .withDescription("Automation receipt differs from the complete original authorization") + .asRuntimeException(); + } catch (AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException corrupt) { + throw Status.DATA_LOSS + .withDescription("Automation committed receipt is invalid") + .asRuntimeException(); + } catch (DataAccessException | org.springframework.dao.DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Automation terminal receipt storage is unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException | IllegalStateException corrupt) { + throw Status.DATA_LOSS + .withDescription("Automation committed receipt is invalid") + .asRuntimeException(); + } + + try { + return new AutomationSelectedSourceIntakeTerminalReadEvidence(request, receipt); + } catch (IllegalArgumentException invalid) { + throw Status.DATA_LOSS + .withDescription("Automation receipt differs from its original order") + .asRuntimeException(); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java new file mode 100644 index 0000000000..ca2788778c --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiver.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.MeterRegistry; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest; +import net.firedevops.firemud.automationscripting.v1.AutomationScriptingServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Unregistered native receiver for the selected-empty Automation publication digest path. */ +public final class AutomationSelectedEmptyPublicationDigestGrpcReceiver + extends AutomationScriptingServiceGrpc.AutomationScriptingServiceImplBase { + private static final Logger LOGGER = + LoggerFactory.getLogger(AutomationSelectedEmptyPublicationDigestGrpcReceiver.class); + + private final AutomationSelectedEmptyPublicationDigestService digestService; + private final PublicationReadGuard publicationReadGuard; + private final MeterRegistry meterRegistry; + + public AutomationSelectedEmptyPublicationDigestGrpcReceiver( + AutomationSelectedEmptyPublicationDigestService digestService, + String configuredNamespace, + MeterRegistry meterRegistry) { + this.digestService = Objects.requireNonNull(digestService, "digestService"); + this.publicationReadGuard = PublicationReadGuard.configured(configuredNamespace); + this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry"); + } + + @Override + public void getDraftDesignDigest( + GetDraftDesignDigestRequest request, + StreamObserver responseObserver) { + try { + requirePublicationRead(); + if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) { + responseObserver.onNext( + error( + "UNSUPPORTED_SCOPE", + "Automation selected-empty publication supports version_id scope only")); + responseObserver.onCompleted(); + return; + } + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, + request.getTenantId(), + request.getVersionId(), + request.getBaseVersionId(), + request.getScriptPatchVersion(), + request.getPublishRequestId()); + binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); + + ScriptDraftDesignDigest digest = digestService.getDraftDesignDigest(binding); + binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setAppliedCommitId(digest.appliedCommitId()) + .setContentDigest(digest.contentDigest()) + .setDigestSchemaVersion(digest.digestSchemaVersion()) + .build()); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException denied) { + responseObserver.onNext(error("PERMISSION_DENIED", denied.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalArgumentException invalid) { + responseObserver.onNext(error("INVALID_ARGUMENT", invalid.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalStateException unavailable) { + responseObserver.onNext(error("FAILED_PRECONDITION", unavailable.getMessage())); + responseObserver.onCompleted(); + } catch (RuntimeException failure) { + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setError( + GrpcAppErrors.internal(meterRegistry, LOGGER, "GetDraftDesignDigest", failure)) + .build()); + responseObserver.onCompleted(); + } + } + + private void requirePublicationRead() { + if (publicationReadGuard == null) { + throw new AdminAuthorizationException("Publication read authorization is not configured"); + } + publicationReadGuard.requirePublicationRead( + PublicationReadGuard.AUTOMATION_SCRIPTING_DIGEST_METHOD); + } + + private GetDraftDesignDigestResponse error(String code, String message) { + return GetDraftDesignDigestResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, LOGGER, "GetDraftDesignDigest", code, message)) + .build(); + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java new file mode 100644 index 0000000000..0fef87d57d --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestService.java @@ -0,0 +1,130 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedEmptyPublicationDigestSupport; + +/** + * Unregistered selected-empty full-version digest reader over Automation's retained owner receipt. + */ +public final class AutomationSelectedEmptyPublicationDigestService { + public static final int DIGEST_SCHEMA_VERSION = 6; + private static final String DIGEST_DOMAIN = "automation-selected-empty-publication-digest/v1"; + + private final String configuredNamespace; + private final AutomationEmptySelectedSourceIntakeRepository repository; + + public AutomationSelectedEmptyPublicationDigestService( + String configuredNamespace, AutomationEmptySelectedSourceIntakeRepository repository) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Automation namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.repository = Objects.requireNonNull(repository, "repository"); + } + + /** Returns a selected-empty digest only for one exact canonical tenant and GD Version row. */ + public ScriptDraftDesignDigest getDraftDesignDigest( + PublicationDigestRequestBinding publicationRequest) { + Objects.requireNonNull(publicationRequest, "publication request is required"); + if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException( + "Automation selected-empty publication supports full versions only"); + } + UUID canonicalTenantId = + SelectedEmptyPublicationDigestSupport.canonicalUuid( + publicationRequest.tenantId(), "tenantId"); + long gameDesignVersionRowId = + SelectedEmptyPublicationDigestSupport.canonicalPositiveLong( + publicationRequest.versionId(), "versionId"); + + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.readPublicationScope( + configuredNamespace, canonicalTenantId, gameDesignVersionRowId); + var target = receipt.authorizationBinding().selected().target(); + if (!configuredNamespace.equals(receipt.targetNamespace()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || target.gameDesignVersionRowId() != gameDesignVersionRowId + || !receipt.canonicalVersionId().equals(target.canonicalVersionId())) { + throw new IllegalStateException( + "Automation selected-empty receipt differs from publication scope"); + } + SelectedEmptyPublicationDigestSupport.requireOriginalPublicationRequest( + publicationRequest, + canonicalTenantId, + gameDesignVersionRowId, + receipt.canonicalVersionId(), + receipt.selectedCommitId(), + receipt.worldInventoryReadEvidence().request().freezeEvidence(), + "Automation"); + if (receipt.authorizationBinding().owner() != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalStateException("Automation receipt contains a different owner declaration"); + } + requireEmptyReceipt(receipt); + + SelectedOwnerEmptySourceInputs inputs = + new SelectedOwnerEmptySourceInputs( + receipt.authorizationBinding(), receipt.worldInventoryReadEvidence()); + if (inputs.ownerSourceInventoryDeclaration().owner() != Owner.AUTOMATION_SCRIPTING) { + throw new IllegalStateException( + "Automation receipt has no exact owner inventory declaration"); + } + String inventoryJson = inputs.ownerSourceInventoryDeclaration().inventory().canonicalJson(); + String contentDigest = + contentDigest( + canonicalTenantId, gameDesignVersionRowId, receipt.canonicalVersionId(), inventoryJson); + return new ScriptDraftDesignDigest( + publicationRequest.tenantId(), + publicationRequest.versionId(), + 0L, + receipt.selectedCommitId().toString(), + contentDigest, + DIGEST_SCHEMA_VERSION); + } + + static String contentDigest( + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + if (gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Game Design Version row must be positive"); + } + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(canonicalInventoryJson, "canonicalInventoryJson"); + return SelectedEmptyPublicationDigestSupport.framedSha256( + DIGEST_DOMAIN, + DIGEST_SCHEMA_VERSION, + canonicalTenantId.toString(), + Long.toString(gameDesignVersionRowId), + canonicalVersionId.toString(), + canonicalInventoryJson); + } + + private static void requireEmptyReceipt(AutomationEmptySelectedSourceIntakeReceipt receipt) { + if (!"COMMITTED_EMPTY".equals(receipt.outcome()) + || receipt.scriptsRowCount() != 0L + || receipt.eventBindingsRowCount() != 0L + || receipt.patchBaseBindingsRowCount() != 0L + || receipt.unqualifiedScriptsRowCount() != 0L + || receipt.unqualifiedEventBindingsRowCount() != 0L + || receipt.unqualifiedPatchBaseBindingsRowCount() != 0L + || receipt.emptyAssociatedScriptsRowCount() != 0L + || receipt.emptyAssociatedEventBindingsRowCount() != 0L + || receipt.emptyAssociatedPatchBaseBindingsRowCount() != 0L + || receipt.selectedScopeScriptsRowCount() != 0L + || receipt.selectedScopeEventBindingsRowCount() != 0L + || receipt.selectedScopePatchBaseBindingsRowCount() != 0L) { + throw new IllegalStateException( + "Automation selected-empty receipt is incomplete or nonempty"); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java new file mode 100644 index 0000000000..9619d292be --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcService.java @@ -0,0 +1,106 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Design command boundary for retaining exact selected Automation inputs. */ +public final class AutomationSelectedSourceIntakeCommandGrpcService + extends AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceImplBase { + private final AutomationEmptySelectedSourceIntakeService owner; + private final String namespace; + + public AutomationSelectedSourceIntakeCommandGrpcService( + AutomationEmptySelectedSourceIntakeService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-source intake owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("configured namespace is invalid"); + } + this.namespace = namespace; + } + + @Override + public void retainSelectedSource( + RetainSelectedSourceRequest request, StreamObserver observer) { + try { + requireAuthenticatedGameDesignCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + + final AutomationSelectedSourceIntakeCommandEvidence.Request decoded; + try { + decoded = AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var receipt = + owner.retain( + decoded.targetNamespace(), + decoded.originalAuthorizationBinding(), + decoded.freezeEvidence()); + var evidence = new AutomationSelectedSourceIntakeCommandEvidence(decoded, receipt); + observer.onNext(AutomationSelectedSourceIntakeCommandGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(Status.fromCode(denied.getStatus().getCode()).asRuntimeException()); + } catch (SecurityException denied) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + } catch (AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException conflict) { + observer.onError(Status.ALREADY_EXISTS.asRuntimeException()); + } catch (AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException corrupt) { + observer.onError(Status.DATA_LOSS.asRuntimeException()); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + /** Authenticate the exact same-namespace workload and reject user context before decoding. */ + private void requireAuthenticatedGameDesignCaller() { + if (SessionContext.hasAuthenticatedCallerContext() + || AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null + || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null + || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java new file mode 100644 index 0000000000..a723e72dc9 --- /dev/null +++ b/services/automation-scripting-service/src/main/java/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadGrpcService.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcCodec; + +/** No automatic registration; authenticate Account before parsing caller-carried evidence. */ +public final class AutomationSelectedSourceIntakeTerminalReadGrpcService + extends AutomationSelectedSourceIntakeTerminalReadServiceGrpc + .AutomationSelectedSourceIntakeTerminalReadServiceImplBase { + private final AutomationEmptySelectedSourceIntakeTerminalReadService owner; + + public AutomationSelectedSourceIntakeTerminalReadGrpcService( + AutomationEmptySelectedSourceIntakeTerminalReadService owner) { + this.owner = Objects.requireNonNull(owner, "terminal-read owner is required"); + } + + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + try { + owner.requireAuthenticatedAccountCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final net.firedevops.firemud.common.automation.sourceintake + .AutomationSelectedSourceIntakeTerminalReadEvidence.Request + decoded; + try { + decoded = AutomationSelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var evidence = owner.read(decoded); + observer.onNext(AutomationSelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + } catch (RuntimeException invalid) { + observer.onError(Status.DATA_LOSS.asRuntimeException()); + } + } +} diff --git a/services/automation-scripting-service/src/main/resources/db/migration/V1003__selected_empty_source_intake.sql b/services/automation-scripting-service/src/main/resources/db/migration/V1003__selected_empty_source_intake.sql new file mode 100644 index 0000000000..e43eb6aa7a --- /dev/null +++ b/services/automation-scripting-service/src/main/resources/db/migration/V1003__selected_empty_source_intake.sql @@ -0,0 +1,334 @@ +-- This migration installs only the storage and writer guards for a fresh, explicitly empty +-- Automation source scope. Existing rows remain legacy/unqualified; no numeric ID is adopted. +CREATE TABLE automation_empty_source_numeric_key_reservation ( + key_kind VARCHAR(16) NOT NULL, + numeric_key BIGINT NOT NULL, + claim_kind VARCHAR(32) NOT NULL, + CONSTRAINT pk_automation_empty_source_numeric_key_reservation + PRIMARY KEY (key_kind, numeric_key), + CONSTRAINT uq_automation_empty_source_numeric_key_kind_value + UNIQUE (numeric_key, key_kind), + CONSTRAINT uq_automation_empty_source_numeric_key_claim + UNIQUE (numeric_key, key_kind, claim_kind), + CONSTRAINT ck_automation_empty_source_numeric_key_kind + CHECK (key_kind IN ('TENANT', 'VERSION')), + CONSTRAINT ck_automation_empty_source_numeric_key_positive + CHECK (numeric_key > 0), + CONSTRAINT ck_automation_empty_source_numeric_key_claim + CHECK (claim_kind IN ('LEGACY_NUMERIC', 'CANONICAL_EMPTY_SOURCE')) +); + +CREATE TABLE automation_empty_selected_source_association ( + target_namespace VARCHAR(63) NOT NULL, + operation_id UUID NOT NULL, + fence_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + source_revision_order VARCHAR(32) NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_tenant_key_kind VARCHAR(16) NOT NULL DEFAULT 'TENANT', + local_tenant_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + local_version_key BIGINT NOT NULL, + local_version_key_kind VARCHAR(16) NOT NULL DEFAULT 'VERSION', + local_version_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + request_digest VARCHAR(71) NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + associated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_automation_empty_selected_source_association + PRIMARY KEY (target_namespace, canonical_tenant_id, canonical_version_id), + CONSTRAINT uq_automation_empty_selected_source_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_automation_empty_selected_source_operation + UNIQUE (target_namespace, operation_id), + CONSTRAINT uq_automation_empty_selected_source_local_tenant + UNIQUE (local_tenant_key), + CONSTRAINT uq_automation_empty_selected_source_local_version + UNIQUE (local_version_key), + CONSTRAINT ck_automation_empty_selected_source_namespace + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT ck_automation_empty_selected_source_ids_nonzero + CHECK ( + operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_revision_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_automation_empty_selected_source_local_keys + CHECK ( + local_tenant_key > 0 + AND local_version_key > 0 + AND local_tenant_key <> local_version_key + AND local_tenant_key_kind = 'TENANT' + AND local_tenant_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + AND local_version_key_kind = 'VERSION' + AND local_version_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + ), + CONSTRAINT ck_automation_empty_selected_source_revision_order + CHECK (source_revision_order ~ '^(0|[1-9][0-9]*)$'), + CONSTRAINT ck_automation_empty_selected_source_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT fk_automation_empty_selected_source_tenant_key + FOREIGN KEY (local_tenant_key, local_tenant_key_kind, local_tenant_key_claim_kind) + REFERENCES automation_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind), + CONSTRAINT fk_automation_empty_selected_source_version_key + FOREIGN KEY (local_version_key, local_version_key_kind, local_version_key_claim_kind) + REFERENCES automation_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind) +); + +CREATE TABLE automation_empty_selected_source_receipt ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + receipt_bytes BYTEA NOT NULL, + retained_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_automation_empty_selected_source_receipt + PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_automation_empty_selected_source_receipt_association + FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES automation_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_automation_empty_selected_source_receipt_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(receipt_bytes) BETWEEN 1 AND 58736640 + ) +); + +CREATE INDEX idx_automation_empty_source_key_claim_kind + ON automation_empty_source_numeric_key_reservation (claim_kind, key_kind, numeric_key); + +/* [jooq ignore start] */ +CREATE FUNCTION automation_source_positive_numeric_key(value_text TEXT) +RETURNS BIGINT +LANGUAGE plpgsql +IMMUTABLE +STRICT +SET search_path = pg_catalog +AS $$ +DECLARE + parsed_value NUMERIC; +BEGIN + IF value_text !~ '^[0-9]+$' THEN + RETURN NULL; + END IF; + parsed_value := value_text::NUMERIC; + IF parsed_value <= 0 OR parsed_value > 9223372036854775807 THEN + RETURN NULL; + END IF; + RETURN parsed_value::BIGINT; +END; +$$; +/* [jooq ignore stop] */ + +-- Lock allocator/association rows before source families, matching the owner allocation order. +-- Old writers can finish before the family locks and are included in this seed; later writes see +-- the reservation triggers installed below. +/* [jooq ignore start] */ +LOCK TABLE automation_empty_source_numeric_key_reservation, + automation_empty_selected_source_association, + automation_empty_selected_source_receipt IN SHARE ROW EXCLUSIVE MODE; +LOCK TABLE script_event_bindings, script_patch_base_bindings, scripts IN SHARE MODE; +/* [jooq ignore stop] */ + +-- Data-only PostgreSQL seeding uses the procedural parser above and ON CONFLICT; the jOOQ H2 +-- simulator cannot execute that seed. All table definitions remain in generation scope. +/* [jooq ignore start] */ +INSERT INTO automation_empty_source_numeric_key_reservation (key_kind, numeric_key, claim_kind) +SELECT DISTINCT key_kind, numeric_key, 'LEGACY_NUMERIC' +FROM ( + SELECT 'TENANT'::VARCHAR(16) AS key_kind, tenant_id AS numeric_key + FROM scripts WHERE tenant_id > 0 + UNION ALL + SELECT 'TENANT', tenant_id + FROM script_event_bindings WHERE tenant_id > 0 + UNION ALL + SELECT 'TENANT', automation_source_positive_numeric_key(tenant_id) + FROM script_patch_base_bindings + WHERE automation_source_positive_numeric_key(tenant_id) IS NOT NULL + UNION ALL + SELECT 'VERSION', base_version_id + FROM scripts WHERE base_version_id > 0 + UNION ALL + SELECT 'VERSION', base_version_id + FROM script_event_bindings WHERE base_version_id > 0 + UNION ALL + SELECT 'VERSION', base_version_id + FROM script_patch_base_bindings WHERE base_version_id > 0 +) AS existing_source_keys +ON CONFLICT (key_kind, numeric_key) DO NOTHING; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +DO $automation_empty_source_functions$ +DECLARE + owner_schema TEXT := current_schema(); +BEGIN + IF owner_schema IS NULL THEN + RAISE EXCEPTION 'Automation empty-source functions require an explicit installation schema'; + END IF; + + EXECUTE format($function$ + CREATE FUNCTION %I.automation_require_source_numeric_key_unreserved( + requested_kind TEXT, requested_key BIGINT + ) RETURNS VOID + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + retained_claim TEXT; + BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Automation authored-source row writes require READ COMMITTED isolation'; + END IF; + IF requested_key IS NULL OR requested_key <= 0 THEN + RETURN; + END IF; + SELECT claim_kind INTO retained_claim + FROM %I.automation_empty_source_numeric_key_reservation + WHERE key_kind = requested_kind AND numeric_key = requested_key; + IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN + RAISE EXCEPTION 'Automation numeric source key is reserved by an immutable empty-source receipt'; + END IF; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.automation_guard_authored_source_row() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_value JSONB; + new_value JSONB; + old_tenant_key BIGINT; + new_tenant_key BIGINT; + old_version_key BIGINT; + new_version_key BIGINT; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_value := to_jsonb(OLD); + old_tenant_key := automation_source_positive_numeric_key(old_value->>'tenant_id'); + old_version_key := automation_source_positive_numeric_key(old_value->>'base_version_id'); + PERFORM automation_require_source_numeric_key_unreserved('TENANT', old_tenant_key); + PERFORM automation_require_source_numeric_key_unreserved('VERSION', old_version_key); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_value := to_jsonb(NEW); + new_tenant_key := automation_source_positive_numeric_key(new_value->>'tenant_id'); + new_version_key := automation_source_positive_numeric_key(new_value->>'base_version_id'); + -- Do not mutate the allocator table from a source-row trigger. PostgreSQL has already + -- acquired the source table's ROW EXCLUSIVE lock before firing this trigger, while the + -- founding path intentionally locks allocator tables first. A read-only reservation + -- check keeps that global lock order acyclic; new allocations also census every source + -- family while holding the source locks, so unreserved legacy keys cannot be missed. + PERFORM automation_require_source_numeric_key_unreserved('TENANT', new_tenant_key); + PERFORM automation_require_source_numeric_key_unreserved('VERSION', new_version_key); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.automation_reject_authored_source_truncate() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Automation authored-source TRUNCATE requires READ COMMITTED isolation'; + END IF; + IF EXISTS ( + SELECT 1 FROM %I.automation_empty_source_numeric_key_reservation + WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE' + ) THEN + RAISE EXCEPTION 'Automation authored source TRUNCATE is forbidden after canonical intake'; + END IF; + RETURN NULL; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.automation_reject_empty_source_intake_mutation() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + RAISE EXCEPTION 'Automation empty-source intake records are immutable'; + END; + $body$ + $function$, owner_schema, owner_schema); +END; +$automation_empty_source_functions$; + +REVOKE ALL ON FUNCTION automation_require_source_numeric_key_unreserved(TEXT, BIGINT) FROM PUBLIC; +REVOKE ALL ON FUNCTION automation_guard_authored_source_row() FROM PUBLIC; +REVOKE ALL ON FUNCTION automation_reject_authored_source_truncate() FROM PUBLIC; +REVOKE ALL ON FUNCTION automation_reject_empty_source_intake_mutation() FROM PUBLIC; + +CREATE TRIGGER trg_automation_scripts_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON scripts + FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row(); +CREATE TRIGGER trg_automation_event_bindings_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON script_event_bindings + FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row(); +CREATE TRIGGER trg_automation_patch_base_bindings_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON script_patch_base_bindings + FOR EACH ROW EXECUTE FUNCTION automation_guard_authored_source_row(); + +CREATE TRIGGER trg_automation_scripts_source_no_truncate + BEFORE TRUNCATE ON scripts + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate(); +CREATE TRIGGER trg_automation_event_bindings_source_no_truncate + BEFORE TRUNCATE ON script_event_bindings + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate(); +CREATE TRIGGER trg_automation_patch_base_bindings_source_no_truncate + BEFORE TRUNCATE ON script_patch_base_bindings + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_authored_source_truncate(); + +CREATE TRIGGER trg_automation_empty_source_key_reservation_immutable + BEFORE UPDATE OR DELETE ON automation_empty_source_numeric_key_reservation + FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_key_reservation_no_truncate + BEFORE TRUNCATE ON automation_empty_source_numeric_key_reservation + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_association_immutable + BEFORE UPDATE OR DELETE ON automation_empty_selected_source_association + FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_association_no_truncate + BEFORE TRUNCATE ON automation_empty_selected_source_association + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_receipt_immutable + BEFORE UPDATE OR DELETE ON automation_empty_selected_source_receipt + FOR EACH ROW EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +CREATE TRIGGER trg_automation_empty_source_receipt_no_truncate + BEFORE TRUNCATE ON automation_empty_selected_source_receipt + FOR EACH STATEMENT EXECUTE FUNCTION automation_reject_empty_source_intake_mutation(); +/* [jooq ignore stop] */ diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java new file mode 100644 index 0000000000..e193216ed5 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresFixture.java @@ -0,0 +1,463 @@ +package net.firedevops.firemud.automationscripting.repository; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.automation.AutomationAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +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.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +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.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; + +/** + * Test-only synthetic inputs built through the same typed Common decoders as the shared fixture. + * They are not authenticated Account or World producer evidence or physical owner proof. + */ +final class AutomationEmptySelectedSourceIntakePostgresFixture { + static final String NAMESPACE = "test"; + static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); + private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + private static final String TEMPLATE_CONFIG = + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"; + + private AutomationEmptySelectedSourceIntakePostgresFixture() {} + + static Fixture create(String sourceEpoch) { + DraftCommitBinding selected = selected(); + var scope = + new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( + Owner.AUTOMATION_SCRIPTING, + NAMESPACE, + OPERATION, + FENCE, + INTAKE_REQUEST, + ACTOR, + selected); + TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); + SelectedOwnerIntakeAuthorizationBinding authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(scope, templateSnapshot), accountSources()); + WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freeze); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + return new Fixture( + authorization, + freeze, + worldEvidence, + new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + static Fixture withFreshWorldReadCorrelation(Fixture original) { + var request = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, original.authorization(), original.freezeEvidence()); + var evidence = + new SelectedOwnerWorldInventoryReadEvidence(request, original.worldEvidence().inventory()); + return new Fixture( + original.authorization(), + original.freezeEvidence(), + evidence, + new SelectedOwnerEmptySourceInputs(original.authorization(), evidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, String sourceEpoch) { + var declaration = + AutomationAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"automation-authored-source-inventory/v1\",\"families\":{" + + "\"SCRIPT_DEFINITIONS\":[],\"EVENT_BINDINGS\":[]," + + "\"SCRIPT_PATCH_SOURCES\":[]}}"); + String declarationPayload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.AUTOMATION_SCRIPTING, declaration); + DraftCommitBinding authored = authoredBinding(declarationPayload); + TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, + sourceEpoch, + authored.commitId(), + GENESIS_RECEIPT, + List.of(), + List.of(ownerDeclaration)); + } + + private static DraftCommitBinding authoredBinding(String payload) { + return DraftCommitBinding.create( + target(), + id("51515151-5151-4151-8151-515151515151"), + id("52525252-5252-4252-8252-525252525252"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("53535353-5353-4353-8353-535353535353"), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, + TemplateConfigSourceSnapshot templateSnapshot) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> + new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + GENESIS_RECEIPT.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family); + }; + } + + private static List accountSources() { + return List.of( + source(SourceKind.TENANT, TENANT.toString(), "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + target(), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static TargetProof target() { + return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence worldEvidence, + SelectedOwnerEmptySourceInputs inputs) {} +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java new file mode 100644 index 0000000000..a3758eb256 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakePostgresIntegrationTest.java @@ -0,0 +1,411 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class AutomationEmptySelectedSourceIntakePostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + + @BeforeAll + void migrateWithRetainedLegacyAuthoredRows() { + schema = "automation_empty_source_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target("1002") + .load() + .migrate(); + + DSLContext upgradeDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + upgradeDsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition, base_version_id) " + + "VALUES (101, 'retained-script', 'legacy-patch', '{}', 201)"); + upgradeDsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (102, 'legacy-patch', 'legacy-event', 'v1', 'retained-script', " + + "'TENANT', 'legacy', 202)"); + upgradeDsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('103', 'legacy-patch', 203)"); + + upgradeDsl.execute( + "INSERT INTO script_work_items (tenant_id, game_instance_id, region_id, region_epoch, entity_id, script_id, event_type, event_schema_version, script_patch_version, script_event_id, source_service, trigger_mode, failure_generation, next_eligible_at) VALUES ('retained-tenant', 'retained-instance', 'region', 1, 'entity', 'script', 'event', 'v1', 'retained-patch', 'retained-event', 'test-only', 'EXTERNAL', 7, NULL)"); + upgradeDsl.execute( + "INSERT INTO saga_instance (saga_name, state) VALUES ('retained-automation-source', 'PENDING')"); + upgradeDsl.execute( + "INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-automation-source'"); + var parentRows = retainedParentRows(upgradeDsl); + var parentHistory = migrationHistory(upgradeDsl); + assertThat( + upgradeDsl + .fetch( + "SELECT version FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class)) + .containsExactly("1", "2", "3", "3.1", "3.2", "4", "1000", "1001", "1002"); + + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + assertThat(retainedParentRows(dsl)).isEqualTo(parentRows); + assertThat(migrationHistory(dsl).subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1003"); + } + + /** Synthetic retained SQL state only; no genuine script or runtime admission authority. */ + private static Map> retainedParentRows(DSLContext source) { + Map> rows = new java.util.LinkedHashMap<>(); + for (String table : + List.of( + "scripts", + "script_event_bindings", + "script_patch_base_bindings", + "script_work_items", + "saga_instance", + "saga_step")) { + rows.put( + table, + source + .fetch( + "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + + " t ORDER BY to_jsonb(t)::TEXT") + .getValues(0, String.class)); + } + return rows; + } + + private static List migrationHistory(DSLContext source) { + return source + .fetch( + "SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank") + .getValues(0, String.class); + } + + @AfterAll + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void migrationSeedsLegacyKeysAndGuardsAllThreeAuthoredSourceFamilies() { + assertThat( + dsl.fetchValue( + "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'LEGACY_NUMERIC'", + Long.class)) + .isEqualTo(6L); + assertThat( + dsl.fetchValue( + "SELECT claim_kind FROM automation_empty_source_numeric_key_reservation " + + "WHERE key_kind = 'TENANT' AND numeric_key = 101", + String.class)) + .isEqualTo("LEGACY_NUMERIC"); + + reserveCanonicalScope(9001L, 9002L); + + // NEW-side guards deny writes that target either locally reserved numeric dimension. + assertRejected( + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (9001, 'blocked-script', 'v1', '{}')"); + assertRejected( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (400, 'blocked-patch', 'blocked-event', 'v1', 'blocked-script', " + + "'TENANT', 'one', 9002)"); + assertRejected( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('9001', 'blocked-patch', 400)"); + + // UPDATE checks both sides: legacy rows cannot be moved into a canonical scope. + upgradeLegacyRowsForUpdate(); + assertRejected("UPDATE scripts SET tenant_id = 9001 WHERE name = 'update-script'"); + assertRejected( + "UPDATE script_event_bindings SET base_version_id = 9002 " + + "WHERE script_patch_version = 'update-patch'"); + assertRejected( + "UPDATE script_patch_base_bindings SET tenant_id = '9001' " + + "WHERE script_patch_version = 'update-patch'"); + + // Fixture-only trigger bypass seeds rows already inside the protected scope so OLD-side + // UPDATE/DELETE rejection is exercised independently of the NEW-side checks above. + seedCanonicalRowsForOldSideChecks(); + assertRejected("DELETE FROM scripts WHERE name = 'old-side-script'"); + assertRejected("UPDATE scripts SET tenant_id = 9101 WHERE name = 'old-side-script'"); + assertRejected( + "DELETE FROM script_event_bindings WHERE script_patch_version = 'old-side-patch'"); + assertRejected( + "UPDATE script_event_bindings SET base_version_id = 9102 " + + "WHERE script_patch_version = 'old-side-patch'"); + assertRejected( + "DELETE FROM script_patch_base_bindings WHERE script_patch_version = 'old-side-patch'"); + assertRejected( + "UPDATE script_patch_base_bindings SET tenant_id = '9103' " + + "WHERE script_patch_version = 'old-side-patch'"); + + assertRejected("TRUNCATE TABLE scripts"); + assertRejected("TRUNCATE TABLE script_event_bindings"); + assertRejected("TRUNCATE TABLE script_patch_base_bindings"); + } + + @Test + void securityDefinerFunctionsUseTheExactInstalledSchemaInTheirFixedSearchPath() { + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM pg_proc AS p " + + "JOIN pg_namespace AS n ON n.oid = p.pronamespace " + + "WHERE n.nspname = ? " + + "AND p.proname IN (" + + "'automation_require_source_numeric_key_unreserved', " + + "'automation_guard_authored_source_row', " + + "'automation_reject_authored_source_truncate', " + + "'automation_reject_empty_source_intake_mutation') " + + "AND p.prosecdef " + + "AND p.proconfig @> ARRAY[format('search_path=pg_catalog, %I', ?)]", + schema, schema) + .get(0, Integer.class)) + .isEqualTo(4); + } + + @Test + void repeatableReadWritersFailWhenReservationRequiresReadCommittedIsolation() + throws SQLException { + try (Connection staleRowWriter = repeatableReadSnapshot()) { + commitCanonicalEmptySourceFixture(9301L, 9302L); + try { + assertThatThrownBy( + () -> + execute( + staleRowWriter, + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (9301, 'stale-snapshot-script', 'v1', '{}')")) + .isInstanceOf(SQLException.class) + .hasMessageContaining( + "Automation authored-source row writes require READ COMMITTED isolation"); + } finally { + staleRowWriter.rollback(); + } + } + + try (Connection staleTruncator = repeatableReadSnapshot()) { + commitCanonicalEmptySourceFixture(9401L, 9402L); + try { + assertThatThrownBy(() -> execute(staleTruncator, "TRUNCATE TABLE scripts")) + .isInstanceOf(SQLException.class) + .hasMessageContaining( + "Automation authored-source TRUNCATE requires READ COMMITTED isolation"); + } finally { + staleTruncator.rollback(); + } + } + } + + private void reserveCanonicalScope(long tenantKey, long versionKey) { + dsl.execute( + "INSERT INTO automation_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')", + tenantKey, + versionKey); + } + + private void upgradeLegacyRowsForUpdate() { + dsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (410, 'update-script', 'v1', '{}')"); + dsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (411, 'update-patch', 'update-event', 'v1', 'update-script', " + + "'TENANT', 'one', 412)"); + dsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('413', 'update-patch', 414)"); + } + + private void seedCanonicalRowsForOldSideChecks() { + dsl.execute("ALTER TABLE scripts DISABLE TRIGGER trg_automation_scripts_source_reservation"); + dsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition) " + + "VALUES (9001, 'old-side-script', 'v1', '{}')"); + dsl.execute("ALTER TABLE scripts ENABLE TRIGGER trg_automation_scripts_source_reservation"); + + dsl.execute( + "ALTER TABLE script_event_bindings " + + "DISABLE TRIGGER trg_automation_event_bindings_source_reservation"); + dsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id, base_version_id) " + + "VALUES (420, 'old-side-patch', 'old-side-event', 'v1', 'old-side-script', " + + "'TENANT', 'one', 9002)"); + dsl.execute( + "ALTER TABLE script_event_bindings " + + "ENABLE TRIGGER trg_automation_event_bindings_source_reservation"); + + dsl.execute( + "ALTER TABLE script_patch_base_bindings " + + "DISABLE TRIGGER trg_automation_patch_base_bindings_source_reservation"); + dsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES ('9001', 'old-side-patch', 420)"); + dsl.execute( + "ALTER TABLE script_patch_base_bindings " + + "ENABLE TRIGGER trg_automation_patch_base_bindings_source_reservation"); + } + + private void assertRejected(String sql) { + assertThatThrownBy(() -> dsl.execute(sql)).isInstanceOf(DataAccessException.class); + } + + private Connection repeatableReadSnapshot() throws SQLException { + Connection connection = dataSource(schema).getConnection(); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement + .executeQuery("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation") + .close(); + } + return connection; + } + + private void commitCanonicalEmptySourceFixture(long tenantKey, long versionKey) + throws SQLException { + // Synthetic SQL-only rows exercise the database fence; they do not authenticate Account or + // World producers and are not proof of the physical owner path. + try (Connection founder = dataSource(schema).getConnection()) { + founder.setAutoCommit(false); + try (PreparedStatement reservation = + founder.prepareStatement( + "INSERT INTO automation_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')")) { + reservation.setLong(1, tenantKey); + reservation.setLong(2, versionKey); + reservation.executeUpdate(); + } + + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID canonicalTenantId = UUID.randomUUID(); + UUID canonicalVersionId = UUID.randomUUID(); + UUID selectedCommitId = UUID.randomUUID(); + UUID sourceRevisionId = UUID.randomUUID(); + String digest = "sha256:" + "c".repeat(64); + try (var association = + founder.prepareStatement( + "INSERT INTO automation_empty_selected_source_association " + + "(target_namespace, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, " + + "local_tenant_key_kind, local_tenant_key_claim_kind, local_version_key, " + + "local_version_key_kind, local_version_key_claim_kind, request_digest, " + + "authorization_binding_digest, receipt_digest, associated_at) " + + "VALUES ('example', ?, ?, ?, ?, ?, ?, ?, '1', ?, 'TENANT', " + + "'CANONICAL_EMPTY_SOURCE', ?, 'VERSION', 'CANONICAL_EMPTY_SOURCE', " + + "?, ?, ?, CURRENT_TIMESTAMP)")) { + association.setObject(1, operationId); + association.setObject(2, fenceId); + association.setObject(3, intakeRequestId); + association.setObject(4, canonicalTenantId); + association.setObject(5, canonicalVersionId); + association.setObject(6, selectedCommitId); + association.setObject(7, sourceRevisionId); + association.setLong(8, tenantKey); + association.setLong(9, versionKey); + association.setString(10, digest); + association.setString(11, digest); + association.setString(12, digest); + association.executeUpdate(); + } + try (var receipt = + founder.prepareStatement( + "INSERT INTO automation_empty_selected_source_receipt " + + "(target_namespace, intake_request_id, request_digest, receipt_digest, " + + "receipt_bytes, retained_at) VALUES ('example', ?, ?, ?, decode('01', 'hex'), " + + "CURRENT_TIMESTAMP)")) { + receipt.setObject(1, intakeRequestId); + receipt.setString(2, digest); + receipt.setString(3, digest); + receipt.executeUpdate(); + } + founder.commit(); + } + } + + private static void execute(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..4eaf8de2f1 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -0,0 +1,639 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.Locale; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedEmptyPublicationDigestService; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.ExecuteContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Real PostgreSQL proof of Automation's bounded local repository persistence and census path. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AutomationEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + private AutomationEmptySelectedSourceIntakeRepository repository; + + @BeforeEach + void migrateFreshIsolatedSchema() { + schema = "automation_empty_source_repo_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target("1002") + .load() + .migrate(); + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new AutomationEmptySelectedSourceIntakeRepository(dsl); + } + + @AfterEach + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void retainsCanonicalEmptyCensusAndExactReadbackAcrossCorrelationIndependentRetry() { + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture = + AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + var inputs = fixture.inputs(); + String requestDigest = requestDigest(fixture); + + // This validates typed synthetic Common inputs; it does not authenticate either producer. + assertThat(inputs.authorizationBinding().targetNamespace()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE); + assertThat(inputs.authorizationBinding().tenantId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.TENANT); + assertThat(inputs.authorizationBinding().versionId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.VERSION); + assertThat(inputs.ownerSourceInventoryDeclaration().owner()) + .isEqualTo( + net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + assertThat( + inputs + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .sourceModel() + .inboundSourceClosure() + .familyCounts()) + .allSatisfy(count -> assertThat(count.count()).isZero()); + + AutomationEmptySelectedSourceIntakeReceipt first = + repository.retainFresh(inputs, requestDigest); + + assertThat(first.targetNamespace()).isEqualTo(inputs.authorizationBinding().targetNamespace()); + assertThat(first.canonicalTenantId()).isEqualTo(inputs.authorizationBinding().tenantId()); + assertThat(first.canonicalVersionId()).isEqualTo(inputs.authorizationBinding().versionId()); + assertThat(first.selectedCommitId()) + .isEqualTo(inputs.authorizationBinding().selected().commitId()); + assertThat(first.sourceRevisionId()) + .isEqualTo(inputs.ownerSourceInventoryDeclaration().revisionId()); + assertThat(first.sourceRevisionOrder()) + .isEqualTo(inputs.ownerSourceInventoryDeclaration().revisionOrder()); + assertThat(first.localTenantKey()).isPositive(); + assertThat(first.localVersionKey()).isPositive().isNotEqualTo(first.localTenantKey()); + assertThat(first.outcome()).isEqualTo("COMMITTED_EMPTY"); + assertThat(first.scriptsRowCount()).isZero(); + assertThat(first.eventBindingsRowCount()).isZero(); + assertThat(first.patchBaseBindingsRowCount()).isZero(); + assertThat(first.unqualifiedScriptsRowCount()).isZero(); + assertThat(first.unqualifiedEventBindingsRowCount()).isZero(); + assertThat(first.unqualifiedPatchBaseBindingsRowCount()).isZero(); + assertThat(first.emptyAssociatedScriptsRowCount()).isZero(); + assertThat(first.emptyAssociatedEventBindingsRowCount()).isZero(); + assertThat(first.emptyAssociatedPatchBaseBindingsRowCount()).isZero(); + assertThat(first.selectedScopeScriptsRowCount()).isZero(); + assertThat(first.selectedScopeEventBindingsRowCount()).isZero(); + assertThat(first.selectedScopePatchBaseBindingsRowCount()).isZero(); + assertThat(first.authorizationBindingBytes()) + .containsExactly(inputs.authorizationBinding().canonicalBytes()); + assertThat(first.worldInventoryBytes()) + .containsExactly(inputs.worldInventoryReadEvidence().inventory().canonicalBytes()); + assertThat(first.worldReadRequestId()) + .isEqualTo(inputs.worldInventoryReadEvidence().request().readRequestId()); + + assertThat(rowCount("SELECT COUNT(*) FROM scripts")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_event_bindings")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_patch_base_bindings")).isZero(); + assertThat( + rowCount( + "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'")) + .isEqualTo(2L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isEqualTo(1L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")) + .isEqualTo(1L); + + Record storedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes, receipt_digest, request_digest FROM " + + "automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.targetNamespace(), + first.intakeRequestId()); + assertThat(storedReceipt).isNotNull(); + assertThat(storedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes()); + assertThat(storedReceipt.get(1, String.class)).isEqualTo(first.receiptDigest()); + assertThat(storedReceipt.get(2, String.class)).isEqualTo(first.requestDigest()); + + Record storedAssociation = + dsl.fetchOne( + "SELECT canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, " + + "request_digest, authorization_binding_digest, receipt_digest " + + "FROM automation_empty_selected_source_association " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.targetNamespace(), + first.intakeRequestId()); + assertThat(storedAssociation).isNotNull(); + assertThat(storedAssociation.get(0, UUID.class)).isEqualTo(first.canonicalTenantId()); + assertThat(storedAssociation.get(1, UUID.class)).isEqualTo(first.canonicalVersionId()); + assertThat(storedAssociation.get(2, UUID.class)).isEqualTo(first.selectedCommitId()); + assertThat(storedAssociation.get(3, UUID.class)).isEqualTo(first.sourceRevisionId()); + assertThat(storedAssociation.get(4, String.class)).isEqualTo(first.sourceRevisionOrder()); + assertThat(storedAssociation.get(5, Long.class)).isEqualTo(first.localTenantKey()); + assertThat(storedAssociation.get(6, Long.class)).isEqualTo(first.localVersionKey()); + assertThat(storedAssociation.get(7, String.class)).isEqualTo(first.requestDigest()); + assertThat(storedAssociation.get(8, String.class)) + .isEqualTo(first.authorizationBindingDigest()); + assertThat(storedAssociation.get(9, String.class)).isEqualTo(first.receiptDigest()); + + var readBack = repository.read(first.targetNamespace(), first.intakeRequestId()).orElseThrow(); + assertThat(readBack.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest()); + var terminalRead = repository.readCommittedTerminal(fixture.authorization()).orElseThrow(); + assertThat(terminalRead.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(terminalRead.authorizationBindingBytes()) + .containsExactly(fixture.authorization().canonicalBytes()); + + var retry = + AutomationEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture); + assertThat(retry.worldEvidence().request().readRequestId()) + .isNotEqualTo(fixture.worldEvidence().request().readRequestId()); + String retryDigest = requestDigest(retry); + assertThat(retryDigest).isEqualTo(requestDigest); + var retryReceipt = repository.retainFresh(retry.inputs(), retryDigest); + assertThat(retryReceipt.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(retryReceipt.worldReadRequestId()).isEqualTo(first.worldReadRequestId()); + + var altered = AutomationEmptySelectedSourceIntakePostgresFixture.create("2"); + assertThat(altered.authorization().intakeRequestId()) + .isEqualTo(fixture.authorization().intakeRequestId()); + assertThat(altered.authorization().canonicalBytes()) + .isNotEqualTo(fixture.authorization().canonicalBytes()); + assertThatThrownBy(() -> repository.readCommittedTerminal(altered.authorization())) + .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException.class) + .hasMessageContaining("complete original authorization"); + String alteredDigest = requestDigest(altered); + assertThat(alteredDigest).isNotEqualTo(requestDigest); + assertThatThrownBy(() -> repository.retainFresh(altered.inputs(), alteredDigest)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("already records different selected evidence"); + + assertThat( + rowCount( + "SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'")) + .isEqualTo(2L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isEqualTo(1L); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")) + .isEqualTo(1L); + Record unchangedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.targetNamespace(), + first.intakeRequestId()); + assertThat(unchangedReceipt).isNotNull(); + assertThat(unchangedReceipt.get(0, byte[].class)).containsExactly(first.canonicalBytes()); + + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? " + + "WHERE target_namespace = ? AND intake_request_id = ?", + first.canonicalBytes(), + first.targetNamespace(), + first.intakeRequestId())) + .rootCause() + .hasMessageContaining("Automation empty-source intake records are immutable"); + + byte[] corruptBytes = first.canonicalBytes(); + corruptBytes[0] ^= 1; + // The isolated test owner bypasses only V1003's immutable receipt-row trigger to model + // corruption. + dsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "DISABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + try { + assertThat( + dsl.execute( + "UPDATE automation_empty_selected_source_receipt SET receipt_bytes = ? " + + "WHERE target_namespace = ? AND intake_request_id = ?", + corruptBytes, + first.targetNamespace(), + first.intakeRequestId())) + .isEqualTo(1); + } finally { + dsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "ENABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + } + assertThatThrownBy(() -> repository.readCommittedTerminal(fixture.authorization())) + .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); + assertThatThrownBy( + () -> + repository.readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + fixture.authorization().selected().target().gameDesignVersionRowId())) + .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); + } + + @Test + void priorScopeUniquenessUsesTenantAndVersionTogether() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + UUID otherVersion = UUID.fromString("33333333-3333-4333-8333-333333333333"); + seedAssociation( + UUID.fromString("44444444-4444-4444-8444-444444444444"), + UUID.fromString("55555555-5555-4555-8555-555555555555"), + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + otherVersion, + UUID.fromString("66666666-6666-4666-8666-666666666666"), + 90001L, + 90002L); + + var secondVersion = repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + + assertThat(secondVersion.canonicalTenantId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.TENANT); + assertThat(secondVersion.canonicalVersionId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.VERSION); + assertThat( + rowCount( + "SELECT COUNT(*) FROM automation_empty_selected_source_association " + + "WHERE target_namespace = ? AND canonical_tenant_id = ?", + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT)) + .isEqualTo(2L); + } + + @Test + void priorCanonicalScopeStillProducesTheIntakeConflict() { + var conflictingFixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("2"); + seedAssociation( + UUID.fromString("77777777-7777-4777-8777-777777777778"), + UUID.fromString("88888888-8888-4888-8888-888888888888"), + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + AutomationEmptySelectedSourceIntakePostgresFixture.VERSION, + UUID.fromString("99999999-9999-4999-8999-999999999998"), + 90003L, + 90004L); + + assertThatThrownBy( + () -> + repository.retainFresh( + conflictingFixture.inputs(), requestDigest(conflictingFixture))) + .isInstanceOf(AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException.class) + .hasMessage("Automation canonical scope or owner operation is already associated"); + } + + @Test + void selectedEmptyPublicationReaderUsesTheRetainedTargetProofAndReturnsSchemaSixDigest() { + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture = + AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + long gameDesignVersionRowId = + fixture.authorization().selected().target().gameDesignVersionRowId(); + + assertThat( + repository + .readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId) + .canonicalBytes()) + .containsExactly(receipt.canonicalBytes()); + assertThatThrownBy( + () -> + repository.readPublicationScope( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId + 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing or ambiguous"); + + var digest = + new AutomationSelectedEmptyPublicationDigestService( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + fixture.freezeEvidence().request().publicationRequestId())); + assertThat(digest.tenantId()) + .isEqualTo(AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString()); + assertThat(digest.scopeValue()).isEqualTo(Long.toString(gameDesignVersionRowId)); + assertThat(digest.baseVersionId()).isZero(); + assertThat(digest.appliedCommitId()).isEqualTo(receipt.selectedCommitId().toString()); + String canonicalInventoryJson = + fixture.inputs().ownerSourceInventoryDeclaration().inventory().canonicalJson(); + assertThat(digest.contentDigest()) + .isEqualTo( + expectedSelectedEmptyDigest( + "automation-selected-empty-publication-digest/v1", + "6", + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId, + receipt.canonicalVersionId(), + canonicalInventoryJson)); + assertThat(digest.digestSchemaVersion()) + .isEqualTo(AutomationSelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION); + + String rowBeforeMismatchedPublicationRead = + dsl.fetchSingle( + "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text " + + "FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()) + .get(0, String.class); + assertThatThrownBy( + () -> + new AutomationSelectedEmptyPublicationDigestService( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + AutomationEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-2"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("original retained World freeze"); + String rowAfterMismatchedPublicationRead = + dsl.fetchSingle( + "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text " + + "FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()) + .get(0, String.class); + assertThat(rowAfterMismatchedPublicationRead).isEqualTo(rowBeforeMismatchedPublicationRead); + } + + @Test + void publicationScopeScanAndReceiptReadbackUseOneRepeatableReadSnapshot() { + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture = + AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + AutomationEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + byte[] concurrentlyCorruptedBytes = receipt.canonicalBytes(); + concurrentlyCorruptedBytes[0] ^= 1; + AtomicBoolean concurrentMutationApplied = new AtomicBoolean(); + dsl.configuration() + .set( + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql == null + || !sql.toLowerCase(Locale.ROOT) + .contains("from automation_empty_selected_source_association") + || !concurrentMutationApplied.compareAndSet(false, true)) { + return; + } + DSLContext concurrentDsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES); + concurrentDsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "DISABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + try { + assertThat( + concurrentDsl.execute( + "UPDATE automation_empty_selected_source_receipt " + + "SET receipt_bytes = ? WHERE target_namespace = ? " + + "AND intake_request_id = ?", + concurrentlyCorruptedBytes, + receipt.targetNamespace(), + receipt.intakeRequestId())) + .isEqualTo(1); + } finally { + concurrentDsl.execute( + "ALTER TABLE automation_empty_selected_source_receipt " + + "ENABLE TRIGGER trg_automation_empty_source_receipt_immutable"); + } + } + })); + + AutomationEmptySelectedSourceIntakeReceipt read = + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId()); + + assertThat(read.canonicalBytes()).containsExactly(receipt.canonicalBytes()); + assertThat(concurrentMutationApplied).isTrue(); + Record storedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + assertThat(storedReceipt).isNotNull(); + assertThat(storedReceipt.get(0, byte[].class)).containsExactly(concurrentlyCorruptedBytes); + } + + @Test + void deniesUnqualifiedRowsInEachAuthoredFamilyWithoutCreatingOwnerRecords() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + String requestDigest = requestDigest(fixture); + + dsl.execute( + "INSERT INTO scripts (tenant_id, name, version, definition) VALUES (?, ?, ?, ?)", + 501L, + "unqualified-script", + "legacy-patch", + "{}"); + assertUnqualifiedDenial(fixture, requestDigest); + dsl.execute("DELETE FROM scripts WHERE name = ?", "unqualified-script"); + + dsl.execute( + "INSERT INTO script_event_bindings (tenant_id, script_patch_version, event_type, " + + "event_schema_version, script_id, target_scope_type, target_scope_id) " + + "VALUES (?, ?, ?, ?, ?, ?, ?)", + 502L, + "unqualified-event-patch", + "unqualified-event", + "v1", + "unqualified-script", + "TENANT", + "test"); + assertUnqualifiedDenial(fixture, requestDigest); + dsl.execute( + "DELETE FROM script_event_bindings WHERE script_patch_version = ?", + "unqualified-event-patch"); + + dsl.execute( + "INSERT INTO script_patch_base_bindings (tenant_id, script_patch_version, base_version_id) " + + "VALUES (?, ?, ?)", + "unqualified-tenant-key", + "unqualified-patch", + 503L); + assertUnqualifiedDenial(fixture, requestDigest); + dsl.execute( + "DELETE FROM script_patch_base_bindings WHERE script_patch_version = ?", + "unqualified-patch"); + + assertThat(rowCount("SELECT COUNT(*) FROM scripts")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_event_bindings")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM script_patch_base_bindings")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isZero(); + } + + private void assertUnqualifiedDenial( + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture, String requestDigest) { + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest)) + .isInstanceOf( + AutomationEmptySelectedSourceIntakeRepository.UnqualifiedSourceRowsException.class); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_source_numeric_key_reservation")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isZero(); + } + + private static String requestDigest( + AutomationEmptySelectedSourceIntakePostgresFixture.Fixture fixture) { + return AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + fixture.authorization(), + fixture.freezeEvidence()); + } + + private static String expectedSelectedEmptyDigest( + String domain, + String schemaVersion, + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendDigestSegment(preimage, domain); + appendDigestSegment(preimage, schemaVersion); + appendDigestSegment(preimage, canonicalTenantId.toString()); + appendDigestSegment(preimage, Long.toString(gameDesignVersionRowId)); + appendDigestSegment(preimage, canonicalVersionId.toString()); + appendDigestSegment(preimage, canonicalInventoryJson); + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private static void appendDigestSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private void seedAssociation( + UUID operationId, + UUID fenceId, + UUID tenantId, + UUID versionId, + UUID intakeRequestId, + long localTenantKey, + long localVersionKey) { + dsl.execute( + "INSERT INTO automation_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')", + localTenantKey, + localVersionKey); + String digest = "sha256:" + "a".repeat(64); + dsl.execute( + "INSERT INTO automation_empty_selected_source_association " + + "(target_namespace, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, " + + "request_digest, authorization_binding_digest, receipt_digest, associated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, '0', ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)", + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + operationId, + fenceId, + intakeRequestId, + tenantId, + versionId, + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + localTenantKey, + localVersionKey, + digest, + digest, + digest); + } + + private long rowCount(String sql, Object... parameters) { + Record record = dsl.fetchOne(sql, parameters); + assertThat(record).isNotNull(); + Long value = record.get(0, Long.class); + assertThat(value).isNotNull(); + return value; + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java new file mode 100644 index 0000000000..cf01ece9cb --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationEmptySelectedSourceIntakeServiceIntegrationTest.java @@ -0,0 +1,326 @@ +package net.firedevops.firemud.automationscripting.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +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 io.grpc.Context; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Mocked service ordering proof using exact typed, synthetic Common owner-input fixtures. + * Collaborator echoes here are not authenticated producer or physical owner proof. + */ +class AutomationEmptySelectedSourceIntakeServiceIntegrationTest { + private static final String NAMESPACE = + AutomationEmptySelectedSourceIntakePostgresFixture.NAMESPACE; + + @BeforeEach + void clearPriorContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void freshTypedInputsReachRepositoryOnlyAfterTwoAccountEchoesAndWorldEcho() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + var inputs = fixture.inputs(); + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class); + var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class); + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(repository.read(NAMESPACE, inputs.authorizationBinding().intakeRequestId())) + .thenReturn(Optional.empty()); + when(repository.retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString())) + .thenReturn(receipt); + when(accountClient.read(any())) + .thenAnswer( + invocation -> + new SelectedOwnerIntakeAuthorizationReadEvidence(invocation.getArgument(0))); + when(worldClient.read(any())) + .thenAnswer( + invocation -> + new SelectedOwnerWorldInventoryReadEvidence( + invocation.getArgument(0), fixture.worldEvidence().inventory())); + + var service = + new AutomationEmptySelectedSourceIntakeService( + repository, accountClient, worldClient, NAMESPACE); + String requestDigest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, fixture.authorization(), fixture.freezeEvidence()); + + AutomationEmptySelectedSourceIntakeReceipt returned = + withGameDesignPeer( + () -> service.retain(NAMESPACE, fixture.authorization(), fixture.freezeEvidence())); + + assertThat(returned).isSameAs(receipt); + ArgumentCaptor accountRequests = + ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationReadEvidence.Request.class); + ArgumentCaptor worldRequests = + ArgumentCaptor.forClass(SelectedOwnerWorldInventoryReadEvidence.Request.class); + ArgumentCaptor retainedInputs = + ArgumentCaptor.forClass(SelectedOwnerEmptySourceInputs.class); + InOrder order = inOrder(repository, accountClient, worldClient, receipt); + order.verify(repository).read(NAMESPACE, inputs.authorizationBinding().intakeRequestId()); + order.verify(accountClient).read(accountRequests.capture()); + order.verify(worldClient).read(worldRequests.capture()); + order.verify(accountClient).read(accountRequests.capture()); + order.verify(repository).retainFresh(retainedInputs.capture(), eq(requestDigest)); + order + .verify(receipt) + .requireSameRequest(NAMESPACE, fixture.authorization(), fixture.freezeEvidence()); + + assertThat(accountRequests.getAllValues()).hasSize(2); + assertThat(accountRequests.getAllValues().get(0).binding()).isEqualTo(fixture.authorization()); + assertThat(accountRequests.getAllValues().get(1).binding()).isEqualTo(fixture.authorization()); + assertThat(accountRequests.getAllValues().get(0).readRequestId()) + .isNotEqualTo(accountRequests.getAllValues().get(1).readRequestId()); + assertThat(worldRequests.getValue().authorizationBinding()).isEqualTo(fixture.authorization()); + assertThat(worldRequests.getValue().freezeEvidence()).isEqualTo(fixture.freezeEvidence()); + + SelectedOwnerEmptySourceInputs actualInputs = retainedInputs.getValue(); + assertThat(actualInputs.authorizationBinding().canonicalBytes()) + .containsExactly(fixture.authorization().canonicalBytes()); + assertThat(actualInputs.authorizationBinding().digest()) + .isEqualTo(fixture.authorization().digest()); + assertThat(actualInputs.sourceContent().canonicalBytes()) + .containsExactly(fixture.authorization().content().canonicalBytes()); + assertThat(actualInputs.sourceContent().digest()) + .isEqualTo(fixture.authorization().content().digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + assertThat(actualInputs.sourceContent().snapshotBytes(family)) + .containsExactly(fixture.authorization().content().snapshotBytes(family)); + } + var actualDeclaration = actualInputs.ownerSourceInventoryDeclaration(); + var expectedDeclaration = inputs.ownerSourceInventoryDeclaration(); + assertThat(actualDeclaration.owner()).isEqualTo(expectedDeclaration.owner()); + assertThat(actualDeclaration.inventory().canonicalJson()) + .isEqualTo(expectedDeclaration.inventory().canonicalJson()); + assertThat(actualDeclaration.sourceBinding().canonicalBytes()) + .containsExactly(expectedDeclaration.sourceBinding().canonicalBytes()); + assertThat(actualDeclaration.revisionOrder()).isEqualTo(expectedDeclaration.revisionOrder()); + assertThat(actualDeclaration.revisionId()).isEqualTo(expectedDeclaration.revisionId()); + assertThat(actualInputs.worldInventoryReadEvidence().request()) + .isEqualTo(worldRequests.getValue()); + assertThat(actualInputs.worldInventoryReadEvidence().inventory().canonicalBytes()) + .containsExactly(fixture.worldEvidence().inventory().canonicalBytes()); + assertThat(actualInputs.worldInventoryReadEvidence().inventory().digest()) + .isEqualTo(fixture.worldEvidence().inventory().digest()); + } + + @Test + void unavailableOrMismatchedAccountAndWorldEchoesNeverReachFreshRetention() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + for (ReadFailure failure : ReadFailure.values()) { + var inputs = fixture.inputs(); + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class); + var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class); + when(repository.read(NAMESPACE, inputs.authorizationBinding().intakeRequestId())) + .thenReturn(Optional.empty()); + + AtomicInteger accountReads = new AtomicInteger(); + when(accountClient.read(any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, SelectedOwnerIntakeAuthorizationReadEvidence.Request.class); + int call = accountReads.incrementAndGet(); + if (failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE && call == 1 + || failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE && call == 2) { + return null; + } + if (failure == ReadFailure.FIRST_ACCOUNT_MISMATCH && call == 1 + || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH && call == 2) { + request = mismatched(request); + } + return new SelectedOwnerIntakeAuthorizationReadEvidence(request); + }); + + AtomicInteger worldReads = new AtomicInteger(); + when(worldClient.read(any())) + .thenAnswer( + invocation -> { + var request = + invocation.getArgument( + 0, SelectedOwnerWorldInventoryReadEvidence.Request.class); + worldReads.incrementAndGet(); + if (failure == ReadFailure.WORLD_UNAVAILABLE) return null; + if (failure == ReadFailure.WORLD_MISMATCH) request = mismatched(request); + return new SelectedOwnerWorldInventoryReadEvidence( + request, fixture.worldEvidence().inventory()); + }); + + var service = + new AutomationEmptySelectedSourceIntakeService( + repository, accountClient, worldClient, NAMESPACE); + assertThatThrownBy( + () -> + withGameDesignPeer( + () -> + service.retain( + NAMESPACE, fixture.authorization(), fixture.freezeEvidence()))) + .as(failure.name()) + .isInstanceOf(IllegalStateException.class); + + verify(repository).read(NAMESPACE, inputs.authorizationBinding().intakeRequestId()); + verify(repository, never()) + .retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString()); + int expectedAccountReads = + failure == ReadFailure.FINAL_ACCOUNT_UNAVAILABLE + || failure == ReadFailure.FINAL_ACCOUNT_MISMATCH + ? 2 + : 1; + int expectedWorldReads = + failure == ReadFailure.FIRST_ACCOUNT_UNAVAILABLE + || failure == ReadFailure.FIRST_ACCOUNT_MISMATCH + ? 0 + : 1; + assertThat(accountReads.get()).isEqualTo(expectedAccountReads); + assertThat(worldReads.get()).isEqualTo(expectedWorldReads); + } + } + + @Test + void exactStoredRetryReturnsBeforeRemoteOwnerReads() { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var accountClient = mock(SelectedOwnerIntakeAuthorizationReadClient.class); + var worldClient = mock(SelectedOwnerWorldInventoryReadClient.class); + var retained = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId())) + .thenReturn(Optional.of(retained)); + var service = + new AutomationEmptySelectedSourceIntakeService( + repository, accountClient, worldClient, NAMESPACE); + + var returned = + withGameDesignPeer( + () -> service.retain(NAMESPACE, fixture.authorization(), fixture.freezeEvidence())); + + assertThat(returned).isSameAs(retained); + verify(repository).read(NAMESPACE, fixture.authorization().intakeRequestId()); + verify(retained) + .requireSameRequest(NAMESPACE, fixture.authorization(), fixture.freezeEvidence()); + verify(repository, never()).retainFresh(any(SelectedOwnerEmptySourceInputs.class), anyString()); + verifyNoInteractions(accountClient, worldClient); + } + + private static SelectedOwnerIntakeAuthorizationReadEvidence.Request mismatched( + SelectedOwnerIntakeAuthorizationReadEvidence.Request request) { + UUID differentId = + differentReadId( + request.readRequestId(), + request.binding().operationId(), + request.binding().fenceId(), + request.binding().intakeRequestId()); + return new SelectedOwnerIntakeAuthorizationReadEvidence.Request( + request.schemaVersion(), request.targetNamespace(), differentId, request.binding()); + } + + private static SelectedOwnerWorldInventoryReadEvidence.Request mismatched( + SelectedOwnerWorldInventoryReadEvidence.Request request) { + var binding = request.authorizationBinding(); + var accountBinding = request.freezeEvidence().request().accountBinding(); + var acknowledgement = request.freezeEvidence().acknowledgement(); + UUID differentId = + differentReadId( + request.readRequestId(), + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + accountBinding.operationId(), + accountBinding.fenceId(), + acknowledgement.intakeRequestId(), + acknowledgement.publicationFence()); + return new SelectedOwnerWorldInventoryReadEvidence.Request( + request.schemaVersion(), + request.targetNamespace(), + differentId, + binding, + request.freezeEvidence()); + } + + private static UUID differentReadId(UUID original, UUID... reserved) { + UUID candidate; + do { + candidate = UUID.randomUUID(); + } while (candidate.equals(original) || contains(reserved, candidate)); + return candidate; + } + + private static boolean contains(UUID[] values, UUID candidate) { + for (UUID value : values) { + if (candidate.equals(value)) return true; + } + return false; + } + + private static T withGameDesignPeer(Supplier action) { + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + NAMESPACE + "/sa/game-design-service", + NAMESPACE, + "game-design-service"); + Context context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = context.attach(); + try { + return action.get(); + } finally { + context.detach(previous); + } + } + + private enum ReadFailure { + FIRST_ACCOUNT_UNAVAILABLE, + FIRST_ACCOUNT_MISMATCH, + WORLD_UNAVAILABLE, + WORLD_MISMATCH, + FINAL_ACCOUNT_UNAVAILABLE, + FINAL_ACCOUNT_MISMATCH + } +} diff --git a/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java new file mode 100644 index 0000000000..b626b27d1e --- /dev/null +++ b/services/automation-scripting-service/src/test/java/integration/net/firedevops/firemud/automationscripting/repository/AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest.java @@ -0,0 +1,244 @@ +package net.firedevops.firemud.automationscripting.repository; + +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 io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeTerminalReadService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeTerminalReadGrpcService; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadClient; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** + * Native Account mTLS proof for Automation's owner edge; upstream fixture evidence stays synthetic. + */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class AutomationSelectedSourceIntakeTerminalReadMtlsPostgresIntegrationTest { + private static final String NS = "test"; + private static final String ACCOUNT = "spiffe://firemud/ns/test/sa/account-service"; + private static final String AUTOMATION = + "spiffe://firemud/ns/test/sa/automation-scripting-service"; + private static final String WRONG_ACCOUNT = "spiffe://firemud/ns/other/sa/account-service"; + private static final String MIGRATIONS = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @TempDir static Path temp; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private static LoopbackMtlsTestPki.Pki pki; + private static LoopbackMtlsTestPki.Identity serverIdentity; + private static LoopbackMtlsTestPki.Identity accountIdentity; + private static LoopbackMtlsTestPki.Identity wrongIdentity; + + private String schema; + private DSLContext dsl; + private AutomationEmptySelectedSourceIntakeRepository repository; + private Server server; + private AutomationSelectedSourceIntakeTerminalReadClient client; + + @BeforeAll + static void issueCertificates() throws Exception { + pki = + LoopbackMtlsTestPki.create( + temp, + "FireMUD test CA", + new LoopbackMtlsTestPki.IdentitySpec("automation", AUTOMATION, true), + new LoopbackMtlsTestPki.IdentitySpec("account", ACCOUNT, false), + new LoopbackMtlsTestPki.IdentitySpec("wrong-account", WRONG_ACCOUNT, false)); + serverIdentity = pki.identity("automation"); + accountIdentity = pki.identity("account"); + wrongIdentity = pki.identity("wrong-account"); + } + + @BeforeEach + void migrateIsolatedSchema() { + schema = "automation_terminal_read_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource ds = dataSource(schema); + Flyway.configure() + .dataSource(ds) + .locations(MIGRATIONS, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target("1002") + .load() + .migrate(); + Flyway.configure() + .dataSource(ds) + .locations(MIGRATIONS, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .load() + .migrate(); + dsl = DSL.using(ds, SQLDialect.POSTGRES); + repository = new AutomationEmptySelectedSourceIntakeRepository(dsl); + } + + @AfterEach + void cleanup() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + if (schema != null) { + String safeSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + safeSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void readsStoredCommittedEmptyReceiptOverAccountMtlsAndRejectsWrongNamespace() throws Exception { + var fixture = AutomationEmptySelectedSourceIntakePostgresFixture.create("1"); + String digest = + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NS, fixture.authorization(), fixture.freezeEvidence()); + + // These typed Common inputs are synthetic; proof covers only Automation's owner edge. + var committed = repository.retainFresh(fixture.inputs(), digest); + assertThat(committed.outcome()).isEqualTo("COMMITTED_EMPTY"); + Record stored = + dsl.fetchSingle( + "SELECT receipt_bytes, receipt_digest FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + committed.targetNamespace(), + committed.intakeRequestId()); + assertThat(stored).isNotNull(); + assertThat(stored.get(0, byte[].class)).containsExactly(committed.canonicalBytes()); + assertThat(stored.get(1, String.class)).isEqualTo(committed.receiptDigest()); + + startReceiver(); + client = newClient(accountIdentity); + client.init(); + var request = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + NS, fixture.authorization()); + var first = client.read(request); + assertThat(first.receipt().canonicalBytes()).containsExactly(stored.get(0, byte[].class)); + assertThat(first.receipt().receiptDigest()).isEqualTo(stored.get(1, String.class)); + assertThat(first.receipt().outcome()).isEqualTo("COMMITTED_EMPTY"); + + var replayRequest = + AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create( + NS, fixture.authorization()); + assertThat(replayRequest.readRequestId()).isNotEqualTo(request.readRequestId()); + var replay = client.read(replayRequest); + assertThat(replay.request()).isEqualTo(replayRequest); + assertThat(replay.receipt().canonicalBytes()).containsExactly(first.receipt().canonicalBytes()); + assertThat(replay.receipt().receiptDigest()).isEqualTo(first.receipt().receiptDigest()); + + var wrongClient = newClient(wrongIdentity); + try { + wrongClient.init(); + assertThatThrownBy(() -> wrongClient.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + e -> + assertThat(Status.fromThrowable(e).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + wrongClient.close(); + } + assertThat(count("SELECT COUNT(*) FROM automation_empty_selected_source_association")) + .isEqualTo(1); + assertThat(count("SELECT COUNT(*) FROM automation_empty_selected_source_receipt")).isEqualTo(1); + Record unchanged = + dsl.fetchSingle( + "SELECT receipt_bytes, receipt_digest FROM automation_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + committed.targetNamespace(), + committed.intakeRequestId()); + assertThat(unchanged).isNotNull(); + assertThat(unchanged.get(0, byte[].class)).containsExactly(first.receipt().canonicalBytes()); + assertThat(unchanged.get(1, String.class)).isEqualTo(first.receipt().receiptDigest()); + } + + private void startReceiver() throws Exception { + var owner = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NS); + var service = new AutomationSelectedSourceIntakeTerminalReadGrpcService(owner); + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + net.firedevops.firemud.common.automation.sourceintake + .AutomationSelectedSourceIntakeTerminalReadGrpcCodec.MAX_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer( + serverIdentity.privateKey(), serverIdentity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService(ServerInterceptors.intercept(service, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private AutomationSelectedSourceIntakeTerminalReadClient newClient( + LoopbackMtlsTestPki.Identity identity) throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAutomationScriptingService("127.0.0.1:" + server.getPort()); + return new AutomationSelectedSourceIntakeTerminalReadClient( + endpoints, pki.clientProperties(temp, identity), new GrpcChannelFactory(), NS); + } + + private DriverManagerDataSource dataSource(String schemaName) { + var ds = new DriverManagerDataSource(); + ds.setDriverClassName(postgres.getDriverClassName()); + String base = postgres.getJdbcUrl(); + ds.setUrl( + schemaName == null + ? base + : base + (base.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + ds.setUsername(postgres.getUsername()); + ds.setPassword(postgres.getPassword()); + return ds; + } + + private long count(String sql) { + return dsl.fetchSingle(sql).get(0, Long.class); + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java new file mode 100644 index 0000000000..39549fb158 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationEmptySelectedSourceIntakeValueTest.java @@ -0,0 +1,325 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +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.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import java.time.OffsetDateTime; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.authoring.DraftCommitBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +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.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.MockedStatic; +import org.springframework.stereotype.Component; +import org.springframework.stereotype.Repository; +import org.springframework.stereotype.Service; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +class AutomationEmptySelectedSourceIntakeValueTest { + @BeforeEach + void clearCallerContext() { + SessionContext.clear(); + } + + @AfterEach + void clearCallerAndTransactionContext() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void storedReceiptDecoderRejectsMalformedValues() { + assertThatThrownBy(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(null)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(new byte[0])) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(new byte[] {1, 2, 3})) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void intakePreparationTypesAreNotLiveSpringComponents() { + assertThat( + AutomationEmptySelectedSourceIntakeRepository.class.isAnnotationPresent( + Component.class)) + .isFalse(); + assertThat( + AutomationEmptySelectedSourceIntakeRepository.class.isAnnotationPresent( + Repository.class)) + .isFalse(); + assertThat( + AutomationEmptySelectedSourceIntakeService.class.isAnnotationPresent(Component.class)) + .isFalse(); + assertThat(AutomationEmptySelectedSourceIntakeService.class.isAnnotationPresent(Service.class)) + .isFalse(); + } + + @Test + void retainRejectsMissingAndWrongSameNamespaceWorkloadPeersBeforeInputOrOwnerRead() { + AutomationEmptySelectedSourceIntakeRepository repository = + mock(AutomationEmptySelectedSourceIntakeRepository.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + AutomationEmptySelectedSourceIntakeService service = + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient, "example"); + + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("Game Design peer"); + + GrpcPeerIdentity wrongPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/account-service", "example", "account-service"); + Context wrongPeerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + Context previous = wrongPeerContext.attach(); + try { + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("same-namespace Game Design peer"); + } finally { + wrongPeerContext.detach(previous); + } + GrpcPeerIdentity correctPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service"); + Context correctPeerContext = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, correctPeer); + previous = correctPeerContext.attach(); + try { + SessionContext.setContext("1001", java.util.List.of(), java.util.Map.of()); + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("same-namespace Game Design peer"); + } finally { + SessionContext.clear(); + correctPeerContext.detach(previous); + } + verifyNoInteractions(repository, authorizationReadClient, worldInventoryReadClient); + } + + @Test + void configuredNamespaceRejectsMismatchedTargetBeforeAnyOwnerRead() { + AutomationEmptySelectedSourceIntakeRepository repository = + mock(AutomationEmptySelectedSourceIntakeRepository.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + assertThatThrownBy( + () -> + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient, "bad namespace")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Canonical namespace"); + + AutomationEmptySelectedSourceIntakeService service = + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient, "example"); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service"); + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = peerContext.attach(); + try { + assertThatThrownBy(() -> service.retain("other", null, null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured namespace"); + } finally { + peerContext.detach(previous); + } + verifyNoInteractions(repository, authorizationReadClient, worldInventoryReadClient); + } + + @Test + void retainRejectsAmbientOwnerSqlBeforeReadingAnyOwnerEvidence() { + AutomationEmptySelectedSourceIntakeRepository repository = + mock(AutomationEmptySelectedSourceIntakeRepository.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + AutomationEmptySelectedSourceIntakeService service = + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient, "example"); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service"); + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = peerContext.attach(); + TransactionSynchronizationManager.setActualTransactionActive(true); + try { + assertThatThrownBy(() -> service.retain("example", null, null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("outside Automation owner SQL"); + } finally { + peerContext.detach(previous); + } + verifyNoInteractions(repository, authorizationReadClient, worldInventoryReadClient); + } + + @Test + void exactCommittedRequestRetryReturnsReceiptBeforeConsultingSettledAuthority() { + String namespace = "example"; + UUID requestId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + String requestDigest = "sha256:" + "b".repeat(64); + SelectedOwnerIntakeAuthorizationBinding binding = + mock(SelectedOwnerIntakeAuthorizationBinding.class); + DraftCommitBinding selectedCommit = mock(DraftCommitBinding.class); + when(binding.targetNamespace()).thenReturn(namespace); + when(binding.owner()).thenReturn(Owner.AUTOMATION_SCRIPTING); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.intakeRequestId()).thenReturn(requestId); + when(binding.tenantId()).thenReturn(tenantId); + when(binding.versionId()).thenReturn(versionId); + when(binding.selected()).thenReturn(selectedCommit); + + WorldSelectedDraftPublicationFreezeEvidence freeze = + mock(WorldSelectedDraftPublicationFreezeEvidence.class); + WorldSelectedDraftPublicationFreezeEvidence.Request freezeRequest = + mock(WorldSelectedDraftPublicationFreezeEvidence.Request.class); + AccountPublicationAuthorizationBinding publicationBinding = + mock(AccountPublicationAuthorizationBinding.class); + AccountPublicationAuthorizationBinding.PreallocationInput publicationInput = + mock(AccountPublicationAuthorizationBinding.PreallocationInput.class); + AuthoredDraftPublishSelectionBinding selection = + mock(AuthoredDraftPublishSelectionBinding.class); + when(freeze.request()).thenReturn(freezeRequest); + when(freezeRequest.targetNamespace()).thenReturn(namespace); + when(freezeRequest.canonicalTenantId()).thenReturn(tenantId); + when(freezeRequest.canonicalVersionId()).thenReturn(versionId); + when(freezeRequest.accountBinding()).thenReturn(publicationBinding); + when(publicationBinding.input()).thenReturn(publicationInput); + when(publicationInput.selection()).thenReturn(selection); + when(selection.selectedCommit()).thenReturn(selectedCommit); + + AutomationEmptySelectedSourceIntakeRepository repository = + mock(AutomationEmptySelectedSourceIntakeRepository.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + AutomationEmptySelectedSourceIntakeReceipt receipt = + mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(repository.read(namespace, requestId)).thenReturn(java.util.Optional.of(receipt)); + AutomationEmptySelectedSourceIntakeService service = + new AutomationEmptySelectedSourceIntakeService( + repository, authorizationReadClient, worldInventoryReadClient, namespace); + GrpcPeerIdentity peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", "example", "game-design-service"); + Context peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + Context previous = peerContext.attach(); + try (MockedStatic receiptStatic = + mockStatic(AutomationEmptySelectedSourceIntakeReceipt.class)) { + receiptStatic + .when( + () -> + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + namespace, binding, freeze)) + .thenReturn(requestDigest); + assertThat(service.retain(namespace, binding, freeze)).isSameAs(receipt); + } finally { + peerContext.detach(previous); + } + verify(repository).read(namespace, requestId); + verify(receipt).requireSameRequest(namespace, binding, freeze); + verifyNoInteractions(authorizationReadClient, worldInventoryReadClient); + } + + @Test + void committedReceiptLookupReturnsTheExactStoredReceiptBytes() { + DSLContext dsl = mock(DSLContext.class); + Record record = mock(Record.class); + String namespace = "example"; + UUID operationId = UUID.randomUUID(); + UUID fenceId = UUID.randomUUID(); + UUID intakeRequestId = UUID.randomUUID(); + UUID tenantId = UUID.randomUUID(); + UUID versionId = UUID.randomUUID(); + UUID selectedCommitId = UUID.randomUUID(); + UUID sourceRevisionId = UUID.randomUUID(); + String digest = "sha256:" + "a".repeat(64); + OffsetDateTime retainedAt = OffsetDateTime.parse("2026-10-10T00:00:00Z"); + byte[] canonicalBytes = new byte[] {1, 2, 3}; + AutomationEmptySelectedSourceIntakeReceipt receipt = + mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(receipt.targetNamespace()).thenReturn(namespace); + when(receipt.operationId()).thenReturn(operationId); + when(receipt.fenceId()).thenReturn(fenceId); + when(receipt.intakeRequestId()).thenReturn(intakeRequestId); + when(receipt.canonicalTenantId()).thenReturn(tenantId); + when(receipt.canonicalVersionId()).thenReturn(versionId); + when(receipt.selectedCommitId()).thenReturn(selectedCommitId); + when(receipt.sourceRevisionId()).thenReturn(sourceRevisionId); + when(receipt.sourceRevisionOrder()).thenReturn("7"); + when(receipt.localTenantKey()).thenReturn(9001L); + when(receipt.localVersionKey()).thenReturn(9002L); + when(receipt.requestDigest()).thenReturn(digest); + when(receipt.authorizationBindingDigest()).thenReturn(digest); + when(receipt.receiptDigest()).thenReturn(digest); + when(receipt.retainedAt()).thenReturn(retainedAt); + when(receipt.canonicalBytes()).thenReturn(canonicalBytes); + + when(record.get(0, String.class)).thenReturn(namespace); + when(record.get(1, UUID.class)).thenReturn(operationId); + when(record.get(2, UUID.class)).thenReturn(fenceId); + when(record.get(3, UUID.class)).thenReturn(intakeRequestId); + when(record.get(4, UUID.class)).thenReturn(tenantId); + when(record.get(5, UUID.class)).thenReturn(versionId); + when(record.get(6, UUID.class)).thenReturn(selectedCommitId); + when(record.get(7, UUID.class)).thenReturn(sourceRevisionId); + when(record.get(8, String.class)).thenReturn("7"); + when(record.get(9, Long.class)).thenReturn(9001L); + when(record.get(10, Long.class)).thenReturn(9002L); + when(record.get(11, String.class)).thenReturn(digest); + when(record.get(12, String.class)).thenReturn(digest); + when(record.get(13, String.class)).thenReturn(digest); + when(record.get(14, OffsetDateTime.class)).thenReturn(retainedAt); + when(record.get(15, String.class)).thenReturn(digest); + when(record.get(16, String.class)).thenReturn(digest); + when(record.get(17, byte[].class)).thenReturn(canonicalBytes); + when(record.get(18, OffsetDateTime.class)).thenReturn(retainedAt); + when(dsl.fetchOne(anyString(), any(Object[].class))).thenReturn(record); + + try (MockedStatic decoder = + mockStatic(AutomationEmptySelectedSourceIntakeReceipt.class)) { + decoder + .when(() -> AutomationEmptySelectedSourceIntakeReceipt.fromStored(canonicalBytes)) + .thenReturn(receipt); + var result = + new AutomationEmptySelectedSourceIntakeRepository(dsl).read(namespace, intakeRequestId); + assertThat(result).isPresent(); + assertThat(result.orElseThrow()).isSameAs(receipt); + } + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java new file mode 100644 index 0000000000..bed367ea99 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedEmptyPublicationDigestGrpcReceiverTest.java @@ -0,0 +1,173 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.service.ScriptDesignDigestService.ScriptDraftDesignDigest; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.automationscripting.v1.GetDraftDesignDigestResponse; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.SessionContext; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class AutomationSelectedEmptyPublicationDigestGrpcReceiverTest { + private static final String NAMESPACE = "test"; + private static final String TENANT = "11111111-1111-4111-8111-111111111111"; + private static final String VERSION_ROW = "23"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void exactGameDesignPeerWithoutSessionContextCanReadValidatedFullVersionBinding() { + SessionContext.clear(); + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"); + Mockito.when(digestService.getDraftDesignDigest(any(PublicationDigestRequestBinding.class))) + .thenReturn( + new ScriptDraftDesignDigest( + TENANT, VERSION_ROW, 0L, "selected-commit", "b".repeat(64), 6)); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request(binding)); + + assertEquals("", response.getError().getCode()); + assertEquals(TENANT, response.getTenantId()); + assertEquals(VERSION_ROW, response.getVersionId()); + assertEquals("", response.getBaseVersionId()); + assertEquals("selected-commit", response.getAppliedCommitId()); + assertEquals("b".repeat(64), response.getContentDigest()); + assertEquals(6, response.getDigestSchemaVersion()); + verify(digestService).getDraftDesignDigest(any(PublicationDigestRequestBinding.class)); + } + + @Test + void accountOrGlobalOrScopedRoleContextDeniesEvenTheExactGameDesignPeer() { + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + List deniedContexts = + List.of( + () -> SessionContext.setContext("user-1", List.of("player"), Map.of()), + () -> SessionContext.setContext(null, List.of("platformAdmin"), Map.of()), + () -> + SessionContext.setContext( + null, List.of(), Map.of("tenant-1", List.of("designer")))); + for (Runnable setDeniedContext : deniedContexts) { + SessionContext.clear(); + setDeniedContext.run(); + GetDraftDesignDigestResponse response = + invokeAsGameDesign( + receiver, + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"))); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + } + verifyNoInteractions(digestService); + } + + @Test + void changedCompleteRequestBindingIsRejectedBeforeReceiptLookup() { + SessionContext.clear(); + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + GetDraftDesignDigestRequest changedRequest = + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")).toBuilder() + .setRequestDigest("0".repeat(64)) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, changedRequest); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + verifyNoInteractions(digestService); + } + + @Test + void patchScopeIsUnsupportedAndDoesNotReadTheSelectedEmptyReceipt() { + SessionContext.clear(); + AutomationSelectedEmptyPublicationDigestService digestService = + Mockito.mock(AutomationSelectedEmptyPublicationDigestService.class); + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver = + new AutomationSelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch(TENANT, VERSION_ROW, "patch-1", "request-7"); + GetDraftDesignDigestRequest request = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setBaseVersionId(binding.baseVersionId()) + .setScriptPatchVersion(binding.scriptPatchVersion()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request); + + assertEquals("UNSUPPORTED_SCOPE", response.getError().getCode()); + verifyNoInteractions(digestService); + } + + private static GetDraftDesignDigestRequest request(PublicationDigestRequestBinding binding) { + return GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + } + + private static GetDraftDesignDigestResponse invokeAsGameDesign( + AutomationSelectedEmptyPublicationDigestGrpcReceiver receiver, + GetDraftDesignDigestRequest request) { + AtomicReference response = new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")) + .run( + () -> + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError(error); + } + + @Override + public void onCompleted() {} + })); + return response.get(); + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java new file mode 100644 index 0000000000..9928759c37 --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeCommandGrpcServiceTest.java @@ -0,0 +1,208 @@ +package unit.net.firedevops.firemud.automationscripting.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +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 java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationEmptySelectedSourceIntakeService; +import net.firedevops.firemud.automationscripting.sourceintake.AutomationSelectedSourceIntakeCommandGrpcService; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Receiver gate tests use mocked owner storage and do not claim physical mTLS or PostgreSQL proof. + */ +class AutomationSelectedSourceIntakeCommandGrpcServiceTest { + private static final String NAMESPACE = "example"; + private static final String GAME_DESIGN_URI = + "spiffe://firemud/ns/example/sa/game-design-service"; + + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void rejectsMissingOrWrongPeerBeforeRequestDecodeOrOwnerInvocation() { + var owner = mock(AutomationEmptySelectedSourceIntakeService.class); + var service = new AutomationSelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var response = new CapturingObserver(); + + service.retainSelectedSource(RetainSelectedSourceRequest.getDefaultInstance(), response); + + assertThat(Status.fromThrowable(response.failure()).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(owner); + + var wrongPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/account-service", NAMESPACE, "account-service"); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + var previous = context.attach(); + try { + var denied = new CapturingObserver(); + service.retainSelectedSource(RetainSelectedSourceRequest.getDefaultInstance(), denied); + assertThat(Status.fromThrowable(denied.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } finally { + context.detach(previous); + } + + var wrongNamespacePeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/other/sa/game-design-service", "other", "game-design-service"); + var wrongNamespaceContext = + Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongNamespacePeer); + previous = wrongNamespaceContext.attach(); + try { + var denied = new CapturingObserver(); + service.retainSelectedSource( + RetainSelectedSourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build(), denied); + assertThat(Status.fromThrowable(denied.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } finally { + wrongNamespaceContext.detach(previous); + } + } + + @Test + void rejectsEndUserAndAmbientSqlBeforeMalformedEvidenceCanBeDecoded() { + var owner = mock(AutomationEmptySelectedSourceIntakeService.class); + var service = new AutomationSelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var peer = new GrpcPeerIdentity(GAME_DESIGN_URI, NAMESPACE, "game-design-service"); + var context = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var malformedRequest = + RetainSelectedSourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build(); + var previous = context.attach(); + try { + SessionContext.setContext("101", List.of(), Map.of()); + var userDenied = new CapturingObserver(); + service.retainSelectedSource(malformedRequest, userDenied); + assertThat(Status.fromThrowable(userDenied.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + var sqlDenied = new CapturingObserver(); + service.retainSelectedSource(malformedRequest, sqlDenied); + assertThat(Status.fromThrowable(sqlDenied.failure()).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clear(); + + var malformed = new CapturingObserver(); + service.retainSelectedSource(malformedRequest, malformed); + assertThat(Status.fromThrowable(malformed.failure()).getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + + var mismatchedTarget = new CapturingObserver(); + service.retainSelectedSource( + RetainSelectedSourceRequest.newBuilder().setTargetNamespace("other").build(), + mismatchedTarget); + assertThat(Status.fromThrowable(mismatchedTarget.failure()).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + verifyNoInteractions(owner); + } finally { + context.detach(previous); + } + } + + @Test + void mapsStorageCorruptionOutagesAndRemoteEchoFailuresToSanitizedStatuses() { + var fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + String namespace = fixture.wrongOwnerAuthorization().targetNamespace(); + var command = + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + namespace, fixture.wrongOwnerAuthorization(), freeze); + var wire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(command); + var peer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/" + namespace + "/sa/game-design-service", + namespace, + "game-design-service"); + var peerContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, peer); + var previous = peerContext.attach(); + try { + assertFailure(new DataAccessException("private jOOQ details"), wire, Status.Code.UNAVAILABLE); + assertFailure( + new DataAccessResourceFailureException("private Spring details"), + wire, + Status.Code.UNAVAILABLE); + assertFailure( + new AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException( + "private receipt details"), + wire, + Status.Code.DATA_LOSS); + assertFailure( + new IllegalStateException("private Account or World echo details"), + wire, + Status.Code.FAILED_PRECONDITION); + } finally { + peerContext.detach(previous); + } + } + + private static void assertFailure( + RuntimeException failure, RetainSelectedSourceRequest request, Status.Code expectedCode) { + var owner = mock(AutomationEmptySelectedSourceIntakeService.class); + doThrow(failure).when(owner).retain(any(), any(), any()); + var service = + new AutomationSelectedSourceIntakeCommandGrpcService(owner, request.getTargetNamespace()); + var observer = new CapturingObserver(); + service.retainSelectedSource(request, observer); + + assertThat(observer.failure()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(observer.failure()).getCode()).isEqualTo(expectedCode); + var status = (StatusRuntimeException) observer.failure(); + assertThat(status.getStatus().getDescription()).isNull(); + assertThat(status.getCause()).isNull(); + assertThat(status.getTrailers()).isNull(); + } + + private static final class CapturingObserver + implements StreamObserver { + private final AtomicReference failure = new AtomicReference<>(); + + @Override + public void onNext(RetainSelectedSourceResponse value) { + throw new AssertionError("Malformed or unauthorized request unexpectedly returned evidence"); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() { + throw new AssertionError("Malformed or unauthorized request unexpectedly completed"); + } + + Throwable failure() { + return failure.get(); + } + } +} diff --git a/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java new file mode 100644 index 0000000000..3600495cce --- /dev/null +++ b/services/automation-scripting-service/src/test/java/unit/net/firedevops/firemud/automationscripting/sourceintake/AutomationSelectedSourceIntakeTerminalReadServiceTest.java @@ -0,0 +1,300 @@ +package net.firedevops.firemud.automationscripting.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.automationscripting.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked owner-storage and peer tests do not establish physical Automation owner proof. */ +class AutomationSelectedSourceIntakeTerminalReadServiceTest { + private static final String NAMESPACE = "example"; + private static final String ACCOUNT_URI = "spiffe://firemud/ns/example/sa/account-service"; + private static final byte[] BINDING_BYTES = {1, 2, 3, 4}; + + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.setActualTransactionActive(false); + if (TransactionSynchronizationManager.isSynchronizationActive()) { + TransactionSynchronizationManager.clearSynchronization(); + } + } + + @Test + void exactRetriesReturnOnlyTheOriginalCommittedEmptyReceipt() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + var receipt = receipt(BINDING_BYTES); + when(repository.readCommittedTerminal(binding)).thenReturn(Optional.of(receipt)); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(); + var previous = accountContext.attach(); + try { + var first = service.read(request(binding)); + var retry = service.read(request(binding)); + + assertThat(first.receipt()).isSameAs(receipt); + assertThat(retry.receipt()).isSameAs(receipt); + assertThat(first.request().readRequestId()).isNotEqualTo(retry.request().readRequestId()); + verify(repository, org.mockito.Mockito.times(2)).readCommittedTerminal(binding); + } finally { + accountContext.detach(previous); + } + } + + @Test + void missingReceiptIsNotConvertedToTerminalEvidence() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + when(repository.readCommittedTerminal(binding)).thenReturn(Optional.empty()); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(); + var previous = accountContext.attach(); + try { + assertThatThrownBy(() -> service.read(request(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.NOT_FOUND)); + } finally { + accountContext.detach(previous); + } + } + + @Test + void rejectsChangedTupleAndCorruptStoredReceipt() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + when(repository.readCommittedTerminal(binding)) + .thenThrow( + new AutomationEmptySelectedSourceIntakeRepository.IntakeConflictException( + "changed exact authorization")); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(); + var previous = accountContext.attach(); + try { + assertThatThrownBy(() -> service.read(request(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.ALREADY_EXISTS)); + + doThrow( + new AutomationEmptySelectedSourceIntakeRepository.CorruptReceiptException( + "corrupt canonical receipt")) + .when(repository) + .readCommittedTerminal(binding); + assertThatThrownBy(() -> service.read(request(binding))) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.DATA_LOSS)); + } finally { + accountContext.detach(previous); + } + } + + @Test + void databaseOutagesAreSanitizedAsUnavailable() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + var receipt = receipt(BINDING_BYTES); + var terminalRequest = request(binding); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(); + var previous = accountContext.attach(); + try { + for (RuntimeException outage : + List.of( + new DataAccessException("private jOOQ database detail"), + new DataAccessResourceFailureException("private Spring database detail"))) { + doThrow(outage) + .doReturn(Optional.of(receipt)) + .when(repository) + .readCommittedTerminal(binding); + + assertThatThrownBy(() -> service.read(terminalRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Automation terminal receipt storage is unavailable"); + assertThat(status.getDescription()) + .doesNotContain("private jOOQ", "private Spring"); + assertThat(((StatusRuntimeException) error).getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); + + var recovered = service.read(terminalRequest); + assertThat(recovered.request()).isSameAs(terminalRequest); + assertThat(recovered.receipt()).isSameAs(receipt); + assertThat(recovered.receipt().canonicalBytes()).isEqualTo(receipt.canonicalBytes()); + } + } finally { + accountContext.detach(previous); + } + } + + @Test + void rejectsWrongPeerEndUserAndAmbientSqlBeforeRepositoryLookup() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var binding = binding(); + var request = request(binding); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + + var wrongPeer = + new GrpcPeerIdentity( + "spiffe://firemud/ns/example/sa/game-design-service", NAMESPACE, "game-design-service"); + var wrongContext = Context.current().withValue(GrpcPeerIdentity.CONTEXT_KEY, wrongPeer); + var previous = wrongContext.attach(); + try { + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + } finally { + wrongContext.detach(previous); + } + + var accountContext = accountPeer(); + previous = accountContext.attach(); + try { + SessionContext.setContext("1001", List.of(), Map.of()); + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED)); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> service.read(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> + assertThat(Status.fromThrowable(error).getCode()) + .isEqualTo(Status.Code.FAILED_PRECONDITION)); + TransactionSynchronizationManager.clearSynchronization(); + } finally { + accountContext.detach(previous); + } + verifyNoInteractions(repository); + } + + @Test + void transportAuthenticatesBeforeDecodingOrLookup() { + var repository = mock(AutomationEmptySelectedSourceIntakeRepository.class); + var service = new AutomationEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var grpc = new AutomationSelectedSourceIntakeTerminalReadGrpcService(service); + var observedError = new AtomicReference(); + StreamObserver observer = + new StreamObserver<>() { + @Override + public void onNext(ReadSelectedSourceIntakeTerminalResponse value) { + throw new AssertionError("Unauthenticated caller received a response"); + } + + @Override + public void onError(Throwable error) { + observedError.set(error); + } + + @Override + public void onCompleted() { + throw new AssertionError("Unauthenticated caller completed a response"); + } + }; + + grpc.readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance(), observer); + + assertThat(observedError.get()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(observedError.get()).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + verifyNoInteractions(repository); + } + + private static SelectedOwnerIntakeAuthorizationBinding binding() { + var binding = mock(SelectedOwnerIntakeAuthorizationBinding.class); + when(binding.owner()) + .thenReturn( + net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner.AUTOMATION_SCRIPTING); + when(binding.targetNamespace()).thenReturn(NAMESPACE); + when(binding.schema()).thenReturn("account-automation-intake-authorization/v1"); + when(binding.purpose()).thenReturn("AUTOMATION_INTAKE_RETENTION"); + when(binding.canonicalBytes()).thenReturn(BINDING_BYTES.clone()); + when(binding.operationId()).thenReturn(UUID.randomUUID()); + when(binding.fenceId()).thenReturn(UUID.randomUUID()); + when(binding.intakeRequestId()).thenReturn(UUID.randomUUID()); + return binding; + } + + private static AutomationSelectedSourceIntakeTerminalReadEvidence.Request request( + SelectedOwnerIntakeAuthorizationBinding binding) { + return AutomationSelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding); + } + + private static AutomationEmptySelectedSourceIntakeReceipt receipt(byte[] bindingBytes) { + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + when(receipt.targetNamespace()).thenReturn(NAMESPACE); + when(receipt.authorizationBindingBytes()).thenReturn(bindingBytes.clone()); + when(receipt.outcome()).thenReturn("COMMITTED_EMPTY"); + return receipt; + } + + private static Context accountPeer() { + return Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity(ACCOUNT_URI, NAMESPACE, "account-service")); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeCommandRequestSupport.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeCommandRequestSupport.java new file mode 100644 index 0000000000..54b6614f32 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/account/sourceintake/SelectedOwnerIntakeCommandRequestSupport.java @@ -0,0 +1,151 @@ +package net.firedevops.firemud.common.account.sourceintake; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; + +/** Shared mechanics for owner-specific selected-source command request records. */ +public final class SelectedOwnerIntakeCommandRequestSupport { + private static final UUID NIL_UUID = new UUID(0L, 0L); + + private SelectedOwnerIntakeCommandRequestSupport() {} + + public static void requireValidRequest( + int schemaVersion, + int expectedSchemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + Owner expectedOwner, + String expectedSchema, + String expectedPurpose, + String invalidRequestMessage) { + Objects.requireNonNull( + originalAuthorizationBinding, "original Account authorization is required"); + Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required"); + if (schemaVersion != expectedSchemaVersion + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(originalAuthorizationBinding.targetNamespace()) + || originalAuthorizationBinding.canonicalBytes().length == 0 + || originalAuthorizationBinding.canonicalBytes().length + > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + || originalAuthorizationBinding.owner() != expectedOwner + || !expectedSchema.equals(originalAuthorizationBinding.schema()) + || !expectedPurpose.equals(originalAuthorizationBinding.purpose()) + || !targetNamespace.equals(freezeEvidence.request().targetNamespace()) + || !originalAuthorizationBinding + .tenantId() + .equals(freezeEvidence.request().canonicalTenantId()) + || !originalAuthorizationBinding + .versionId() + .equals(freezeEvidence.request().canonicalVersionId()) + || !originalAuthorizationBinding + .selected() + .equals(freezeEvidence.request().accountBinding().input().selection().selectedCommit()) + || !originalAuthorizationBinding + .selected() + .commitId() + .toString() + .equals(freezeEvidence.acknowledgement().appliedCommitId())) { + throw invalid(invalidRequestMessage); + } + DraftAuthorizationFenceBinding.requireUuid(transportRequestId); + if (NIL_UUID.equals(transportRequestId) + || collidesWithRetainedIdentity( + transportRequestId, originalAuthorizationBinding, freezeEvidence)) { + throw invalid(invalidRequestMessage); + } + } + + public static UUID newTransportRequestId( + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + UUID correlation; + do { + correlation = UUID.randomUUID(); + } while (collidesWithRetainedIdentity( + correlation, originalAuthorizationBinding, freezeEvidence)); + return correlation; + } + + public static boolean sameRequest( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + int otherSchemaVersion, + String otherTargetNamespace, + UUID otherTransportRequestId, + SelectedOwnerIntakeAuthorizationBinding otherOriginalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence otherFreezeEvidence) { + return schemaVersion == otherSchemaVersion + && targetNamespace.equals(otherTargetNamespace) + && transportRequestId.equals(otherTransportRequestId) + && Arrays.equals( + originalAuthorizationBinding.canonicalBytes(), + otherOriginalAuthorizationBinding.canonicalBytes()) + && originalAuthorizationBinding.digest().equals(otherOriginalAuthorizationBinding.digest()) + && freezeEvidence.equals(otherFreezeEvidence); + } + + public static int hashCodeFor( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + return Objects.hash( + schemaVersion, + targetNamespace, + transportRequestId, + Arrays.hashCode(originalAuthorizationBinding.canonicalBytes()), + originalAuthorizationBinding.digest(), + freezeEvidence); + } + + private static boolean collidesWithRetainedIdentity( + UUID candidate, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freeze) { + if (candidate.equals(binding.operationId()) + || candidate.equals(binding.fenceId()) + || candidate.equals(binding.intakeRequestId()) + || candidate.equals(binding.selected().requestId()) + || candidate.equals(binding.selected().commitId())) { + return true; + } + var account = freeze.request().accountBinding(); + var selection = account.input().selection(); + List freezeIds = + new ArrayList<>( + List.of( + account.operationId(), + account.fenceId(), + selection.fenceRequestId(), + selection.fenceCommitId(), + selection.selectedCommit().requestId(), + selection.selectedCommit().commitId(), + freeze.acknowledgement().intakeRequestId(), + freeze.acknowledgement().publicationFence())); + if (freezeIds.contains(candidate)) return true; + try { + UUID publicationRequestId = UUID.fromString(freeze.request().publicationRequestId()); + return publicationRequestId.toString().equals(freeze.request().publicationRequestId()) + && publicationRequestId.equals(candidate); + } catch (IllegalArgumentException notUuid) { + return false; + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java new file mode 100644 index 0000000000..13e153f01b --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandEvidence.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeCommandRequestSupport; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; + +/** Exact Game Design command correlation and the immutable Automation receipt. */ +public record AutomationSelectedSourceIntakeCommandEvidence( + Request request, AutomationEmptySelectedSourceIntakeReceipt receipt) { + public AutomationSelectedSourceIntakeCommandEvidence { + Objects.requireNonNull(request, "selected-source command request is required"); + Objects.requireNonNull(receipt, "committed Automation receipt is required"); + try { + receipt.requireSameRequest( + request.targetNamespace(), + request.originalAuthorizationBinding(), + request.freezeEvidence()); + } catch (RuntimeException mismatch) { + throw new IllegalArgumentException( + "Automation receipt differs from the complete selected-source command", mismatch); + } + if (!Arrays.equals( + request.originalIntakeAuthorizationBinding(), receipt.authorizationBindingBytes()) + || !request.intakeAuthorizationDigest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Automation receipt differs from the original Account authorization bytes"); + } + } + + /** Caller-generated transport correlation; all retained inputs remain the original values. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + public static final int SCHEMA_VERSION = 1; + + public Request { + SelectedOwnerIntakeCommandRequestSupport.requireValidRequest( + schemaVersion, + SCHEMA_VERSION, + targetNamespace, + transportRequestId, + originalAuthorizationBinding, + freezeEvidence, + Owner.AUTOMATION_SCRIPTING, + "account-automation-intake-authorization/v1", + "AUTOMATION_INTAKE_RETENTION", + "Invalid Automation selected-source command request"); + } + + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull( + originalAuthorizationBinding, "original Account authorization is required"); + Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required"); + return new Request( + SCHEMA_VERSION, + namespace, + SelectedOwnerIntakeCommandRequestSupport.newTransportRequestId( + originalAuthorizationBinding, freezeEvidence), + originalAuthorizationBinding, + freezeEvidence); + } + + public byte[] originalIntakeAuthorizationBinding() { + return originalAuthorizationBinding.canonicalBytes(); + } + + public String intakeAuthorizationDigest() { + return originalAuthorizationBinding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && SelectedOwnerIntakeCommandRequestSupport.sameRequest( + schemaVersion, + targetNamespace, + transportRequestId, + originalAuthorizationBinding, + freezeEvidence, + other.schemaVersion, + other.targetNamespace, + other.transportRequestId, + other.originalAuthorizationBinding, + other.freezeEvidence); + } + + @Override + public int hashCode() { + return SelectedOwnerIntakeCommandRequestSupport.hashCodeFor( + schemaVersion, + targetNamespace, + transportRequestId, + originalAuthorizationBinding, + freezeEvidence); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java new file mode 100644 index 0000000000..56a8f17a24 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/automation/sourceintake/AutomationSelectedSourceIntakeCommandGrpcCodec.java @@ -0,0 +1,187 @@ +package net.firedevops.firemud.common.automation.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; + +/** Closed mapping for selected-source retention with exact Account and World evidence echoes. */ +public final class AutomationSelectedSourceIntakeCommandGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Authorization plus complete freeze request and acknowledgement Account bindings. */ + public static final int MAX_REQUEST_WIRE_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + 2 * WorldSelectedDraftPublicationFreezeEvidence.Request.MAX_ACCOUNT_BINDING_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + /** Complete receipt, complete echoed request, and bounded outer response framing. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES + + MAX_REQUEST_WIRE_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + private AutomationSelectedSourceIntakeCommandGrpcCodec() {} + + public static RetainSelectedSourceRequest toRequest(Request request) { + Objects.requireNonNull(request, "selected-source command request is required"); + byte[] authorizationBytes = request.originalIntakeAuthorizationBinding(); + if (authorizationBytes.length == 0 + || authorizationBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization exceeds its 16 MiB limit"); + } + var freeze = request.freezeEvidence(); + var wire = + RetainSelectedSourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorizationBytes)) + .setIntakeAuthorizationDigest(request.intakeAuthorizationDigest()) + .setFreezeRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())) + .setFreezeAcknowledgement( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())) + .build(); + requireWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + return wire; + } + + /** Decode after the receiver authenticates the exact same-namespace Game Design peer. */ + public static Request fromRequest(RetainSelectedSourceRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + if (!wire.hasFreezeRequest() || !wire.hasFreezeAcknowledgement()) { + throw invalid("Complete original World freeze request and acknowledgement are required"); + } + UUID transportRequestId = canonicalUuid(wire.getTransportRequestId()); + int authorizationSize = wire.getOriginalIntakeAuthorizationBinding().size(); + if (authorizationSize == 0 + || authorizationSize > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization size is invalid"); + } + byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + SelectedOwnerIntakeAuthorizationBinding authorization; + try { + authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes); + } catch (RuntimeException malformed) { + throw invalid("Original Account authorization is invalid", malformed); + } + if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Account authorization digest differs"); + } + final WorldSelectedDraftPublicationFreezeEvidence freezeEvidence; + try { + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest()); + freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, wire.getFreezeAcknowledgement()); + } catch (RuntimeException malformed) { + throw invalid("Complete original World freeze evidence is invalid", malformed); + } + final Request request; + try { + request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + transportRequestId, + authorization, + freezeEvidence); + } catch (RuntimeException malformed) { + throw invalid("Automation selected-source command binding is invalid", malformed); + } + if (!toRequest(request).equals(wire)) { + throw invalid("Selected-source command request is not an exact canonical echo"); + } + return request; + } + + public static RetainSelectedSourceResponse toResponse( + AutomationSelectedSourceIntakeCommandEvidence evidence) { + Objects.requireNonNull(evidence, "selected-source command evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Automation receipt size is invalid"); + } + var response = + RetainSelectedSourceResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + return response; + } + + /** Requires the exact complete request echo and verifies the canonical retained receipt. */ + public static AutomationSelectedSourceIntakeCommandEvidence fromResponse( + Request expected, RetainSelectedSourceResponse response) { + Objects.requireNonNull(expected, "selected-source command request is required"); + requireKnownAndWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + if (!response.hasRequest()) { + throw invalid("Exact selected-source command request echo is required"); + } + RetainSelectedSourceRequest expectedWire = toRequest(expected); + if (!response.getRequest().equals(expectedWire)) { + throw invalid("Automation changed the exact selected-source command request"); + } + int receiptSize = response.getCommittedEmptyReceipt().size(); + if (receiptSize == 0 || receiptSize > AutomationEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Automation receipt"); + } + byte[] receiptBytes = response.getCommittedEmptyReceipt().toByteArray(); + AutomationEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = AutomationEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + } catch (RuntimeException malformed) { + throw invalid("Committed Automation receipt is invalid", malformed); + } + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Automation receipt digest differs"); + } + return new AutomationSelectedSourceIntakeCommandEvidence(expected, receipt); + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw invalid("Canonical nonzero transport request UUID required"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid("Canonical nonzero transport request UUID required", malformed); + } + } + + private static void requireKnownAndWithinBudget(Message message, int budget, String label) { + if (message == null || message.getSerializedSize() > budget) { + throw invalid("Automation selected-source command " + label + " exceeds its wire budget"); + } + if (!message.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Automation selected-source command " + label + " fields"); + } + } + + private static void requireWithinBudget(Message message, int budget, String label) { + if (message.getSerializedSize() > budget) { + throw invalid("Automation selected-source command " + label + " exceeds its wire budget"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java new file mode 100644 index 0000000000..a310188da3 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandEvidence.java @@ -0,0 +1,107 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeCommandRequestSupport; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; + +/** Exact Game Design command correlation and the immutable Entity receipt. */ +public record EntitySelectedSourceIntakeCommandEvidence( + Request request, EntityEmptySelectedSourceIntakeReceipt receipt) { + public EntitySelectedSourceIntakeCommandEvidence { + Objects.requireNonNull(request, "selected-source command request is required"); + Objects.requireNonNull(receipt, "committed Entity receipt is required"); + try { + receipt.requireSameRequest( + request.targetNamespace(), + request.originalAuthorizationBinding(), + request.freezeEvidence()); + } catch (RuntimeException mismatch) { + throw new IllegalArgumentException( + "Entity receipt differs from the complete selected-source command", mismatch); + } + if (!Arrays.equals( + request.originalIntakeAuthorizationBinding(), receipt.authorizationBindingBytes()) + || !request.intakeAuthorizationDigest().equals(receipt.authorizationBindingDigest())) { + throw new IllegalArgumentException( + "Entity receipt differs from the original Account authorization bytes"); + } + } + + /** Caller-generated transport correlation; all retained inputs remain the original values. */ + public record Request( + int schemaVersion, + String targetNamespace, + UUID transportRequestId, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + public static final int SCHEMA_VERSION = 1; + + public Request { + SelectedOwnerIntakeCommandRequestSupport.requireValidRequest( + schemaVersion, + SCHEMA_VERSION, + targetNamespace, + transportRequestId, + originalAuthorizationBinding, + freezeEvidence, + Owner.ENTITY_MANAGEMENT, + "account-entity-intake-authorization/v1", + "ENTITY_INTAKE_RETENTION", + "Invalid Entity selected-source command request"); + } + + public static Request create( + String namespace, + SelectedOwnerIntakeAuthorizationBinding originalAuthorizationBinding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull( + originalAuthorizationBinding, "original Account authorization is required"); + Objects.requireNonNull(freezeEvidence, "complete World freeze evidence is required"); + return new Request( + SCHEMA_VERSION, + namespace, + SelectedOwnerIntakeCommandRequestSupport.newTransportRequestId( + originalAuthorizationBinding, freezeEvidence), + originalAuthorizationBinding, + freezeEvidence); + } + + public byte[] originalIntakeAuthorizationBinding() { + return originalAuthorizationBinding.canonicalBytes(); + } + + public String intakeAuthorizationDigest() { + return originalAuthorizationBinding.digest(); + } + + @Override + public boolean equals(Object value) { + return value instanceof Request other + && SelectedOwnerIntakeCommandRequestSupport.sameRequest( + schemaVersion, + targetNamespace, + transportRequestId, + originalAuthorizationBinding, + freezeEvidence, + other.schemaVersion, + other.targetNamespace, + other.transportRequestId, + other.originalAuthorizationBinding, + other.freezeEvidence); + } + + @Override + public int hashCode() { + return SelectedOwnerIntakeCommandRequestSupport.hashCodeFor( + schemaVersion, + targetNamespace, + transportRequestId, + originalAuthorizationBinding, + freezeEvidence); + } + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java new file mode 100644 index 0000000000..47e71734fc --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodec.java @@ -0,0 +1,193 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import com.google.protobuf.ByteString; +import com.google.protobuf.Message; +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; + +/** Closed Entity mapping with complete original Account/World evidence and exact receipt echo. */ +public final class EntitySelectedSourceIntakeCommandGrpcCodec { + private static final int MAX_REQUEST_FRAMING_BYTES = 64 * 1024; + + /** Original authorization, complete freeze request and acknowledgement, and outer framing. */ + public static final int MAX_REQUEST_WIRE_BYTES = + SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES + + 2 * WorldSelectedDraftPublicationFreezeEvidence.Request.MAX_ACCOUNT_BINDING_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + /** Full Entity receipt, full echoed request and bounded response framing. */ + public static final int MAX_RESPONSE_WIRE_BYTES = + EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES + + MAX_REQUEST_WIRE_BYTES + + MAX_REQUEST_FRAMING_BYTES; + + private EntitySelectedSourceIntakeCommandGrpcCodec() {} + + public static RetainSelectedEntitySourceRequest toRequest(Request request) { + Objects.requireNonNull(request, "selected-source command request is required"); + byte[] authorizationBytes = request.originalIntakeAuthorizationBinding(); + if (authorizationBytes.length == 0 + || authorizationBytes.length > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization exceeds its 16 MiB limit"); + } + var freeze = request.freezeEvidence(); + var wire = + RetainSelectedEntitySourceRequest.newBuilder() + .setSchemaVersion(request.schemaVersion()) + .setTargetNamespace(request.targetNamespace()) + .setTransportRequestId(request.transportRequestId().toString()) + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(authorizationBytes)) + .setIntakeAuthorizationDigest(request.intakeAuthorizationDigest()) + .setFreezeRequest( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())) + .setFreezeAcknowledgement( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())) + .build(); + requireWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + return wire; + } + + /** Decode only after the receiver authenticates the exact same-namespace Game Design peer. */ + public static Request fromRequest(RetainSelectedEntitySourceRequest wire) { + requireKnownAndWithinBudget(wire, MAX_REQUEST_WIRE_BYTES, "request"); + if (!wire.hasFreezeRequest() || !wire.hasFreezeAcknowledgement()) { + throw invalid("Complete original World freeze request and acknowledgement are required"); + } + UUID transportRequestId = canonicalUuid(wire.getTransportRequestId()); + int authorizationSize = wire.getOriginalIntakeAuthorizationBinding().size(); + if (authorizationSize == 0 + || authorizationSize > SelectedOwnerIntakeAuthorizationBinding.MAX_BYTES) { + throw invalid("Original Account authorization size is invalid"); + } + byte[] authorizationBytes = wire.getOriginalIntakeAuthorizationBinding().toByteArray(); + final SelectedOwnerIntakeAuthorizationBinding authorization; + try { + authorization = SelectedOwnerIntakeAuthorizationBinding.fromStored(authorizationBytes); + } catch (RuntimeException malformed) { + throw invalid("Original Account authorization is invalid", malformed); + } + if (!authorization.digest().equals(wire.getIntakeAuthorizationDigest())) { + throw invalid("Original Account authorization digest differs"); + } + final WorldSelectedDraftPublicationFreezeEvidence freezeEvidence; + try { + var freezeRequest = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromRequest(wire.getFreezeRequest()); + freezeEvidence = + WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + freezeRequest, wire.getFreezeAcknowledgement()); + } catch (RuntimeException malformed) { + throw invalid("Complete original World freeze evidence is invalid", malformed); + } + final Request request; + try { + request = + new Request( + wire.getSchemaVersion(), + wire.getTargetNamespace(), + transportRequestId, + authorization, + freezeEvidence); + } catch (RuntimeException malformed) { + throw invalid("Entity selected-source command binding is invalid", malformed); + } + if (!toRequest(request).equals(wire)) { + throw invalid("Selected-source command request is not an exact canonical echo"); + } + return request; + } + + public static RetainSelectedEntitySourceResponse toResponse( + EntitySelectedSourceIntakeCommandEvidence evidence) { + Objects.requireNonNull(evidence, "selected-source command evidence is required"); + byte[] receiptBytes = evidence.receipt().canonicalBytes(); + if (receiptBytes.length == 0 + || receiptBytes.length > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Committed Entity receipt size is invalid"); + } + var response = + RetainSelectedEntitySourceResponse.newBuilder() + .setRequest(toRequest(evidence.request())) + .setCommittedEmptyReceipt(ByteString.copyFrom(receiptBytes)) + .setReceiptDigest(evidence.receipt().receiptDigest()) + .build(); + requireWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + return response; + } + + /** + * Requires the exact complete request echo and verifies the canonical retained Entity receipt. + */ + public static EntitySelectedSourceIntakeCommandEvidence fromResponse( + Request expected, RetainSelectedEntitySourceResponse response) { + Objects.requireNonNull(expected, "selected-source command request is required"); + requireKnownAndWithinBudget(response, MAX_RESPONSE_WIRE_BYTES, "response"); + if (!response.hasRequest()) { + throw invalid("Exact selected-source command request echo is required"); + } + if (!response.getRequest().equals(toRequest(expected))) { + throw invalid("Entity changed the exact selected-source command request"); + } + int receiptSize = response.getCommittedEmptyReceipt().size(); + if (receiptSize == 0 || receiptSize > EntityEmptySelectedSourceIntakeReceipt.MAX_BYTES) { + throw invalid("Missing or oversized committed Entity receipt"); + } + final EntityEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = + EntityEmptySelectedSourceIntakeReceipt.fromStored( + response.getCommittedEmptyReceipt().toByteArray()); + } catch (RuntimeException malformed) { + throw invalid("Committed Entity receipt is invalid", malformed); + } + if (!receipt.receiptDigest().equals(response.getReceiptDigest())) { + throw invalid("Entity receipt digest differs"); + } + try { + return new EntitySelectedSourceIntakeCommandEvidence(expected, receipt); + } catch (RuntimeException mismatch) { + throw invalid("Entity receipt differs from the complete original command", mismatch); + } + } + + private static UUID canonicalUuid(String value) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || parsed.equals(new UUID(0L, 0L))) { + throw invalid("Canonical nonzero transport request UUID required"); + } + return parsed; + } catch (IllegalArgumentException malformed) { + throw invalid("Canonical nonzero transport request UUID required", malformed); + } + } + + private static void requireKnownAndWithinBudget(Message wire, int budget, String label) { + if (wire == null || wire.getSerializedSize() > budget) { + throw invalid("Entity selected-source command " + label + " exceeds its wire budget"); + } + if (!wire.getUnknownFields().asMap().isEmpty()) { + throw invalid("Unknown Entity selected-source command " + label + " fields"); + } + } + + private static void requireWithinBudget(Message wire, int budget, String label) { + if (wire.getSerializedSize() > budget) { + throw invalid("Entity selected-source command " + label + " exceeds its wire budget"); + } + } + + private static IllegalArgumentException invalid(String message) { + return new IllegalArgumentException(message); + } + + private static IllegalArgumentException invalid(String message, Throwable cause) { + return new IllegalArgumentException(message, cause); + } +} diff --git a/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupport.java b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupport.java new file mode 100644 index 0000000000..7105b1c333 --- /dev/null +++ b/services/common-platform-core/src/main/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupport.java @@ -0,0 +1,104 @@ +package net.firedevops.firemud.common.publication; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.UUID; + +/** + * Shared framing, identity parsing, and retained World-freeze checks for selected-empty digests. + */ +public final class SelectedEmptyPublicationDigestSupport { + private SelectedEmptyPublicationDigestSupport() {} + + /** Hashes ordered UTF-8 segments using the publication digest's byte-length framing. */ + public static String framedSha256(String domain, int schemaVersion, String... segments) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendSegment(preimage, domain); + appendSegment(preimage, Integer.toString(schemaVersion)); + for (String segment : segments) { + appendSegment(preimage, segment); + } + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new IllegalStateException("SHA-256 is unavailable", impossible); + } + } + + /** Parses a canonical, nonzero UUID while retaining the caller's field-specific error text. */ + public static UUID canonicalUuid(String value, String field) { + try { + UUID parsed = UUID.fromString(value); + if (!parsed.toString().equals(value) || new UUID(0L, 0L).equals(parsed)) { + throw new IllegalArgumentException(field + " must be a canonical nonzero UUID"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException(field + " must be a canonical nonzero UUID", malformed); + } + } + + /** Parses a canonical positive decimal long while retaining the caller's field-specific text. */ + public static long canonicalPositiveLong(String value, String field) { + try { + long parsed = Long.parseLong(value); + if (parsed <= 0L || !Long.toString(parsed).equals(value)) { + throw new IllegalArgumentException(field + " must be a canonical positive decimal"); + } + return parsed; + } catch (RuntimeException malformed) { + throw new IllegalArgumentException( + field + " must be a canonical positive decimal", malformed); + } + } + + /** Requires the original publication request identity retained in the selected World freeze. */ + public static void requireOriginalPublicationRequest( + PublicationDigestRequestBinding requested, + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + UUID selectedCommitId, + WorldSelectedDraftPublicationFreezeEvidence retainedFreeze, + String ownerLabel) { + var freezeRequest = retainedFreeze.request(); + var retainedSelection = freezeRequest.accountBinding().input().selection(); + long retainedGameDesignVersionRowId = + retainedSelection.selectedCommit().target().gameDesignVersionRowId(); + if (gameDesignVersionRowId != retainedGameDesignVersionRowId) { + throw new IllegalStateException( + ownerLabel + " publication version row differs from the original retained World freeze"); + } + var retainedPublicationRequest = + PublicationDigestRequestBinding.full( + freezeRequest.canonicalTenantId().toString(), + Long.toString(retainedGameDesignVersionRowId), + freezeRequest.publicationRequestId()); + if (!canonicalTenantId.equals(freezeRequest.canonicalTenantId()) + || !canonicalVersionId.equals(freezeRequest.canonicalVersionId()) + || !selectedCommitId.equals(retainedSelection.selectedCommit().commitId()) + || !selectedCommitId.toString().equals(retainedFreeze.acknowledgement().appliedCommitId()) + || requested.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION + || !requested.tenantId().equals(retainedPublicationRequest.tenantId()) + || !requested.versionId().equals(retainedPublicationRequest.versionId()) + || !requested.publishRequestId().equals(retainedPublicationRequest.publishRequestId()) + || !requested + .derivedWorkflowIdentity() + .equals(retainedPublicationRequest.derivedWorkflowIdentity()) + || !requested.requestDigest().equals(retainedPublicationRequest.requestDigest())) { + throw new IllegalStateException( + ownerLabel + " publication request differs from the original retained World freeze"); + } + } + + private static void appendSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java new file mode 100644 index 0000000000..1061b90c2c --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/entity/sourceintake/EntitySelectedSourceIntakeCommandGrpcCodecTest.java @@ -0,0 +1,213 @@ +package net.firedevops.firemud.common.entity.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import com.google.protobuf.ByteString; +import com.google.protobuf.UnknownFieldSet; +import java.util.UUID; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** Synthetic fixture codec proof does not establish Entity producer or physical census proof. */ +class EntitySelectedSourceIntakeCommandGrpcCodecTest { + private static final String NAMESPACE = "test"; + private static Fixture fixture; + + @BeforeAll + static void createSyntheticEntityInputs() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @Test + void roundTripsCompleteOriginalAuthorizationFreezeAndCanonicalReceiptOnDistinctCorrelations() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var binding = fixture.authorization(); + var first = Request.create(NAMESPACE, binding, freeze); + var retry = Request.create(NAMESPACE, binding, freeze); + + var firstWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(first); + var retryWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(retry); + assertThat(first.transportRequestId()).isNotEqualTo(retry.transportRequestId()); + assertThat(first.transportRequestId()) + .isNotIn( + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.selected().requestId(), + binding.selected().commitId(), + freeze.acknowledgement().intakeRequestId(), + freeze.acknowledgement().publicationFence()); + assertThat(EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(firstWire)).isEqualTo(first); + assertThat(EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(retryWire)).isEqualTo(retry); + assertThat(firstWire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(firstWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(firstWire.getFreezeRequest()) + .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())); + assertThat(firstWire.getFreezeAcknowledgement()) + .isEqualTo( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())); + assertThat(firstWire.getSerializedSize()) + .isLessThanOrEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES); + + var evidence = new EntitySelectedSourceIntakeCommandEvidence(first, fixture.receipt()); + RetainSelectedEntitySourceResponse response = + EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(evidence); + assertThat(response.getRequest()).isEqualTo(firstWire); + assertThat(response.getCommittedEmptyReceipt().toByteArray()) + .isEqualTo(fixture.receipt().canonicalBytes()); + assertThat(response.getReceiptDigest()).isEqualTo(fixture.receipt().receiptDigest()); + assertThat(response.getSerializedSize()) + .isLessThanOrEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES); + var decoded = EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(first, response); + assertThat(decoded.request()).isEqualTo(first); + assertThat(decoded.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + assertThat(decoded.receipt().authorizationBindingBytes()).isEqualTo(binding.canonicalBytes()); + } + + @Test + void rejectsWrongOwnerNamespaceAndChangedOriginalBindingOrFreeze() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + assertThatThrownBy(() -> Request.create(NAMESPACE, fixture.wrongOwnerAuthorization(), freeze)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> Request.create("other", fixture.authorization(), freeze)) + .isInstanceOf(IllegalArgumentException.class); + + var request = Request.create(NAMESPACE, fixture.authorization(), freeze); + var wire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + + byte[] changedBinding = fixture.authorization().canonicalBytes(); + changedBinding[changedBinding.length - 1] ^= 1; + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalIntakeAuthorizationBinding(ByteString.copyFrom(changedBinding)) + .build())) + .isInstanceOf(IllegalArgumentException.class); + + var changedFreezeRequest = + wire.getFreezeRequest().toBuilder().setRequestDigest("0".repeat(64)).build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setFreezeRequest(changedFreezeRequest).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("freeze"); + var changedFreezeAck = + wire.getFreezeAcknowledgement().toBuilder().setAppliedCommitId("0".repeat(36)).build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setFreezeAcknowledgement(changedFreezeAck).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("freeze"); + } + + @Test + void rejectsUnknownFieldsOversizedWireAndChangedFullResponseEchoOrDigest() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = Request.create(NAMESPACE, fixture.authorization(), freeze); + var requestWire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + requestWire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + requestWire.toBuilder() + .setFreezeAcknowledgement( + requestWire.getFreezeAcknowledgement().toBuilder() + .setUnknownFields(unknown) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + RetainSelectedEntitySourceRequest.newBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte + [EntitySelectedSourceIntakeCommandGrpcCodec + .MAX_REQUEST_WIRE_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire budget"); + + var response = + EntitySelectedSourceIntakeCommandGrpcCodec.toResponse( + new EntitySelectedSourceIntakeCommandEvidence(request, fixture.receipt())); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setTransportRequestId(UUID.randomUUID().toString()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, response.toBuilder().setReceiptDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, response.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + + var changedRequest = Request.create(NAMESPACE, fixture.authorization(), freeze); + assertThatThrownBy( + () -> EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(changedRequest, response)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + } + + @Test + void transportCorrelationMustBeCanonicalNonzeroAndNotReuseRetainedIdentity() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var binding = fixture.authorization(); + assertThatThrownBy( + () -> + new Request( + Request.SCHEMA_VERSION, NAMESPACE, binding.operationId(), binding, freeze)) + .isInstanceOf(IllegalArgumentException.class); + var valid = Request.create(NAMESPACE, binding, freeze); + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest( + EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(valid).toBuilder() + .setTransportRequestId("00000000-0000-0000-0000-000000000000") + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("UUID"); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java new file mode 100644 index 0000000000..8b3007c481 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/AutomationSelectedSourceIntakeCommandGrpcCodecTest.java @@ -0,0 +1,279 @@ +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.when; + +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.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.Owner; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceTestFixtures; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.OwnerFreezePhase; +import net.firedevops.firemud.worldmanagement.v1.BeginVersionPublicationFreezeResponse; +import org.junit.jupiter.api.Test; + +class AutomationSelectedSourceIntakeCommandGrpcCodecTest { + private static final UUID ACTOR = id("dddddddd-dddd-4ddd-8ddd-dddddddddddd"); + + @Test + void roundTripsOriginalAutomationAuthorizationAndCompleteWorldFreezeOnDistinctCorrelations() { + var freeze = freeze(); + var binding = + authorization(freeze.request().accountBinding().input().selection().selectedCommit()); + var first = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + var retry = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + + var firstWire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(first); + var retryWire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(retry); + + assertThat(first.transportRequestId()).isNotEqualTo(retry.transportRequestId()); + assertThat(first.transportRequestId()) + .isNotIn( + binding.operationId(), + binding.fenceId(), + binding.intakeRequestId(), + binding.selected().requestId(), + binding.selected().commitId(), + freeze.acknowledgement().intakeRequestId(), + freeze.acknowledgement().publicationFence()); + assertThat(AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(firstWire)) + .isEqualTo(first); + assertThat(AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(retryWire)) + .isEqualTo(retry); + assertThat(firstWire.getOriginalIntakeAuthorizationBinding().toByteArray()) + .isEqualTo(binding.canonicalBytes()); + assertThat(firstWire.getIntakeAuthorizationDigest()).isEqualTo(binding.digest()); + assertThat(firstWire.getFreezeRequest()) + .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())); + assertThat(firstWire.getFreezeAcknowledgement()) + .isEqualTo( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())); + assertThat(firstWire.getSerializedSize()) + .isLessThanOrEqualTo(AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES); + } + + @Test + void rejectsUnknownFieldsOversizedWireAndChangedFreezeOrAuthorizationScope() { + var freeze = freeze(); + var binding = + authorization(freeze.request().accountBinding().input().selection().selectedCommit()); + var request = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + var wire = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var unknown = + UnknownFieldSet.newBuilder() + .addField(99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build(); + + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setUnknownFields(unknown).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder().setIntakeAuthorizationDigest("0".repeat(64)).build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("digest"); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setFreezeRequest( + wire.getFreezeRequest().toBuilder().setUnknownFields(unknown).build()) + .build())) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest( + wire.toBuilder() + .setOriginalIntakeAuthorizationBinding( + ByteString.copyFrom( + new byte + [AutomationSelectedSourceIntakeCommandGrpcCodec + .MAX_REQUEST_WIRE_BYTES + + 1])) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("wire budget"); + + var otherNamespaceFreeze = freeze("other"); + assertThatThrownBy( + () -> + new AutomationSelectedSourceIntakeCommandEvidence.Request( + AutomationSelectedSourceIntakeCommandEvidence.Request.SCHEMA_VERSION, + "test", + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + binding, + otherNamespaceFreeze)) + .isInstanceOf(IllegalArgumentException.class); + var wrongOwner = + authorization( + freeze.request().accountBinding().input().selection().selectedCommit(), + Owner.ENTITY_MANAGEMENT); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + "test", wrongOwner, freeze)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void responseRequiresExactFullRequestEchoAndEncodesReceiptBytesAndDigest() { + var freeze = freeze(); + var binding = + authorization(freeze.request().accountBinding().input().selection().selectedCommit()); + var request = + AutomationSelectedSourceIntakeCommandEvidence.Request.create("test", binding, freeze); + var receipt = mock(AutomationEmptySelectedSourceIntakeReceipt.class); + byte[] storedReceipt = {1, 2, 3}; + when(receipt.canonicalBytes()).thenReturn(storedReceipt); + when(receipt.receiptDigest()).thenReturn("a".repeat(64)); + when(receipt.authorizationBindingBytes()).thenReturn(binding.canonicalBytes()); + when(receipt.authorizationBindingDigest()).thenReturn(binding.digest()); + var evidence = new AutomationSelectedSourceIntakeCommandEvidence(request, receipt); + var response = AutomationSelectedSourceIntakeCommandGrpcCodec.toResponse(evidence); + + assertThat(response.getRequest()) + .isEqualTo(AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request)); + assertThat(response.getCommittedEmptyReceipt().toByteArray()).isEqualTo(storedReceipt); + assertThat(response.getReceiptDigest()).isEqualTo("a".repeat(64)); + + var changedFreeze = + response.toBuilder() + .setRequest( + response.getRequest().toBuilder() + .setFreezeAcknowledgement( + response.getRequest().getFreezeAcknowledgement().toBuilder() + .setContentDigest("b".repeat(64))) + .build()) + .build(); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, changedFreeze)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("changed"); + assertThatThrownBy( + () -> + AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse( + request, + response.toBuilder() + .setUnknownFields( + UnknownFieldSet.newBuilder() + .addField( + 99, UnknownFieldSet.Field.newBuilder().addVarint(1).build()) + .build()) + .build())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Unknown"); + } + + private static SelectedOwnerIntakeAuthorizationBinding authorization( + DraftCommitBinding selected) { + return authorization(selected, Owner.AUTOMATION_SCRIPTING); + } + + private static SelectedOwnerIntakeAuthorizationBinding authorization( + DraftCommitBinding selected, Owner owner) { + var scope = + new SelectedOwnerIntakeSourceReadScope( + owner, + "test", + id("66666666-6666-4666-8666-666666666666"), + id("77777777-7777-4777-8777-777777777777"), + id("88888888-8888-4888-8888-888888888888"), + ACTOR, + selected); + var contentBytes = new ByteArrayOutputStream(); + frame(contentBytes, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(contentBytes, scope.canonicalBytes()); + frame(contentBytes, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = SelectedOwnerIntakeSourceTestFixtures.snapshot(family, selected); + frame(contentBytes, family); + frame(contentBytes, snapshot); + frame(contentBytes, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] canonicalContent = contentBytes.toByteArray(); + var content = + SelectedOwnerIntakeSourceContent.fromStored( + canonicalContent, scope, DraftAuthorizationFenceBinding.digest(canonicalContent)); + return new SelectedOwnerIntakeAuthorizationBinding( + content, + List.of( + source(SourceKind.ACCOUNT, ACTOR.toString()), + source(SourceKind.TENANT, selected.target().canonicalTenantId().toString()), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + selected.target().canonicalTenantId()))); + } + + private static SourceEvidence source(SourceKind kind, String scope) { + return new SourceEvidence(kind, scope, null, "1", null, null, new byte[] {1}); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freeze() { + return freeze("test"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freeze(String namespace) { + var original = WorldSelectedDraftPublicationFreezeGrpcCodecTest.request(); + if (!namespace.equals(original.targetNamespace())) { + // The fixture's Account publication binding is namespace-independent; rebuild only its + // request tuple through the same constructor used by the production value. + original = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + namespace, + original.canonicalTenantId(), + original.canonicalVersionId(), + original.publicationRequestId(), + original.expectedVersionStateEpoch(), + original.requestDigest(), + original.accountBinding()); + } + var acknowledgement = + new Acknowledgement( + original, + id("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"), + original.expectedVersionStateEpoch(), + id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"), + OwnerFreezePhase.FROZEN, + original.accountBinding().input().selection().selectedCommit().commitId().toString(), + "a".repeat(64), + 3); + BeginVersionPublicationFreezeResponse response = + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse(original, response); + } + + private static void frame(ByteArrayOutputStream output, String value) { + DraftAuthorizationFenceBinding.frame(output, value); + } + + private static void frame(ByteArrayOutputStream output, byte[] value) { + DraftAuthorizationFenceBinding.frame(output, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } +} diff --git a/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupportTest.java b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupportTest.java new file mode 100644 index 0000000000..71fcba0630 --- /dev/null +++ b/services/common-platform-core/src/test/java/net/firedevops/firemud/common/publication/SelectedEmptyPublicationDigestSupportTest.java @@ -0,0 +1,63 @@ +package net.firedevops.firemud.common.publication; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; + +import java.util.UUID; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import org.junit.jupiter.api.Test; + +class SelectedEmptyPublicationDigestSupportTest { + @Test + void framingMatchesFixedAdr0047Utf8ByteLengthVector() { + // Fixed UTF-8 preimage: "17:digest-fixture/v11:62:é0:1::". + // Includes a multibyte value, an empty segment and a literal framing delimiter. + assertThat( + SelectedEmptyPublicationDigestSupport.framedSha256( + "digest-fixture/v1", 6, "é", "", ":")) + .isEqualTo("c10b89e19d156f8d0bd570229e67d913b3b3eefc094def4646b5a7650beee247"); + } + + @Test + void publicationVersionRowMustMatchTheRetainedSelectedTarget() { + var fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var retainedSelection = freeze.request().accountBinding().input().selection(); + long retainedVersionRowId = + retainedSelection.selectedCommit().target().gameDesignVersionRowId(); + UUID tenantId = freeze.request().canonicalTenantId(); + UUID versionId = freeze.request().canonicalVersionId(); + UUID selectedCommitId = retainedSelection.selectedCommit().commitId(); + String publishRequestId = freeze.request().publicationRequestId(); + + var matchingRequest = + PublicationDigestRequestBinding.full( + tenantId.toString(), Long.toString(retainedVersionRowId), publishRequestId); + SelectedEmptyPublicationDigestSupport.requireOriginalPublicationRequest( + matchingRequest, + tenantId, + retainedVersionRowId, + versionId, + selectedCommitId, + freeze, + "Entity"); + + var mismatchedRequest = + PublicationDigestRequestBinding.full( + tenantId.toString(), Long.toString(retainedVersionRowId + 1L), publishRequestId); + + assertThatIllegalStateException() + .isThrownBy( + () -> + SelectedEmptyPublicationDigestSupport.requireOriginalPublicationRequest( + mismatchedRequest, + tenantId, + retainedVersionRowId + 1L, + versionId, + selectedCommitId, + freeze, + "Entity")) + .withMessageContaining( + "publication version row differs from the original retained World freeze"); + } +} diff --git a/services/common-security/build.gradle.kts b/services/common-security/build.gradle.kts index ae0af42f53..d81fe85929 100644 --- a/services/common-security/build.gradle.kts +++ b/services/common-security/build.gradle.kts @@ -19,4 +19,5 @@ dependencies { testImplementation(libs.spring.boot.starter.test) testImplementation(testFixtures(project(":common-platform-core"))) + testImplementation(testFixtures(project(":common-test-support"))) } diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java new file mode 100644 index 0000000000..5da5d0653c --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClient.java @@ -0,0 +1,116 @@ +package net.firedevops.firemud.common.security.sourceintake; + +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.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence.Request; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +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; + +/** File-backed mTLS client for Automation's unregistered selected-source command. */ +public final class GrpcAutomationSelectedSourceIntakeCommandClient + extends AbstractReloadingBlockingGrpcClient< + AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + + public GrpcAutomationSelectedSourceIntakeCommandClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + SelectedSourceIntakeClientTls.requireFileBackedMtls( + tlsProperties, "Automation selected-source command"), + channelFactory, + GrpcAutomationSelectedSourceIntakeCommandClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + initOnce( + "Automation selected-source command client is closed", + "Automation selected-source command stub unavailable"); + } + + /** Returns only the exact immutable receipt echoed for this complete original request. */ + public AutomationSelectedSourceIntakeCommandEvidence retain(Request request) { + requireWorkloadOnlyContext(); + Objects.requireNonNull(request, "selected-source command request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Automation selected-source command must use the configured workload namespace"); + } + var wireRequest = AutomationSelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var current = + requireInitializedStub( + "Automation selected-source command client is not initialized and available"); + try { + var response = + current + .withMaxOutboundMessageSize( + AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .retainSelectedSource(wireRequest); + return AutomationSelectedSourceIntakeCommandGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException denied) { + throw Status.fromCode(denied.getStatus().getCode()).asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException( + "Automation returned invalid selected-source receipt evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getAutomationScriptingService(); + } + + @Override + protected String defaultTarget() { + return "automation-scripting-service:6565"; + } + + @Override + protected AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = automationServerPeerUri(workloadNamespace); + return AutomationSelectedSourceIntakeCommandServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withMaxOutboundMessageSize( + AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + private static void requireWorkloadOnlyContext() { + requireNoAmbientSql( + "Automation selected-source command requires no ambient SQL or synchronization"); + SelectedSourceIntakeClientTls.requireWorkloadOnlyContext("Automation selected-source command"); + } + + private static String automationServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/automation-scripting-service"; + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java new file mode 100644 index 0000000000..2e4cb07dbe --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClient.java @@ -0,0 +1,115 @@ +package net.firedevops.firemud.common.security.sourceintake; + +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.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.grpc.AbstractReloadingBlockingGrpcClient; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityCallCredentials; +import net.firedevops.firemud.common.grpc.GrpcServerPeerIdentityClientInterceptor; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc; + +/** File-backed mTLS client for Entity's unregistered selected-source command. */ +public final class GrpcEntitySelectedSourceIntakeCommandClient + extends AbstractReloadingBlockingGrpcClient< + EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceBlockingStub> { + private static final long CALL_DEADLINE_SECONDS = 5L; + + private final String workloadNamespace; + + public GrpcEntitySelectedSourceIntakeCommandClient( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tlsProperties, + GrpcChannelFactory channelFactory, + String workloadNamespace) { + super( + endpoints, + SelectedSourceIntakeClientTls.requireFileBackedMtls( + tlsProperties, "Entity selected-source command"), + channelFactory, + GrpcEntitySelectedSourceIntakeCommandClient.class); + if (!GrpcPeerIdentity.isValidNamespace(workloadNamespace)) { + throw new IllegalArgumentException("Canonical workload namespace required"); + } + this.workloadNamespace = workloadNamespace; + } + + public synchronized void init() throws SSLException, IOException { + initOnce( + "Entity selected-source command client is closed", + "Entity selected-source command stub unavailable"); + } + + /** Returns only the exact immutable Entity receipt echoed for this complete original request. */ + public EntitySelectedSourceIntakeCommandEvidence retain( + EntitySelectedSourceIntakeCommandEvidence.Request request) { + requireWorkloadOnlyContext(); + Objects.requireNonNull(request, "selected-source command request is required"); + if (!workloadNamespace.equals(request.targetNamespace())) { + throw new IllegalArgumentException( + "Entity selected-source command must use the configured workload namespace"); + } + var wireRequest = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request); + var current = + requireInitializedStub( + "Entity selected-source command client is not initialized and available"); + try { + var response = + current + .withMaxOutboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withDeadlineAfter(CALL_DEADLINE_SECONDS, TimeUnit.SECONDS) + .retainSelectedEntitySource(wireRequest); + return EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(request, response); + } catch (StatusRuntimeException denied) { + throw Status.fromCode(denied.getStatus().getCode()).asRuntimeException(); + } catch (IllegalArgumentException malformed) { + throw new IllegalStateException("Entity returned invalid selected-source receipt evidence"); + } + } + + @Override + protected String configuredTarget(ServiceEndpointsProperties endpoints) { + return endpoints.getEntityManagementService(); + } + + @Override + protected String defaultTarget() { + return "entity-management-service:6565"; + } + + @Override + protected EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceBlockingStub + buildStub(ManagedChannel channel) { + String expectedPeerUri = entityServerPeerUri(workloadNamespace); + return EntitySelectedSourceIntakeCommandServiceGrpc.newBlockingStub(channel) + .withMaxInboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_RESPONSE_WIRE_BYTES) + .withMaxOutboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .withCallCredentials(new GrpcServerPeerIdentityCallCredentials(expectedPeerUri)) + .withInterceptors(new GrpcServerPeerIdentityClientInterceptor(expectedPeerUri)) + .withCompression("gzip"); + } + + private static void requireWorkloadOnlyContext() { + requireNoAmbientSql( + "Entity selected-source command requires no ambient SQL or synchronization"); + SelectedSourceIntakeClientTls.requireWorkloadOnlyContext("Entity selected-source command"); + } + + private static String entityServerPeerUri(String namespace) { + return "spiffe://firemud/ns/" + namespace + "/sa/entity-management-service"; + } +} diff --git a/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeClientTls.java b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeClientTls.java new file mode 100644 index 0000000000..f95f48295b --- /dev/null +++ b/services/common-security/src/main/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeClientTls.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import java.nio.file.Files; +import java.nio.file.Path; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.security.SessionContext; + +/** Shared file-backed workload mTLS validation for selected-source intake clients. */ +final class SelectedSourceIntakeClientTls { + private SelectedSourceIntakeClientTls() {} + + static CommonGrpcClientProperties requireFileBackedMtls( + CommonGrpcClientProperties tlsProperties, String clientLabel) { + if (tlsProperties == null || tlsProperties.isPlaintext()) { + throw new IllegalArgumentException(clientLabel + " requires workload mTLS"); + } + requireReadableFile(tlsProperties.getCertChain(), clientLabel, "certificate chain"); + requireReadableFile(tlsProperties.getPrivateKey(), clientLabel, "private key"); + requireReadableFile(tlsProperties.getCaCert(), clientLabel, "CA certificate"); + return tlsProperties; + } + + static void requireWorkloadOnlyContext(String clientLabel) { + if (SessionContext.hasAuthenticatedCallerContext() + || AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null + || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null + || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null) { + throw new IllegalStateException(clientLabel + " requires workload-only context"); + } + } + + private static void requireReadableFile(String configuredPath, String clientLabel, String label) { + if (configuredPath == null + || configuredPath.isBlank() + || configuredPath.trim().startsWith("classpath:")) { + throw new IllegalArgumentException( + clientLabel + " requires file-backed certificate, key, and CA material"); + } + Path path; + try { + path = Path.of(configuredPath.trim()); + } catch (RuntimeException invalid) { + throw new IllegalArgumentException("Invalid " + clientLabel + " " + label + " path"); + } + if (!Files.isRegularFile(path) || !Files.isReadable(path)) { + throw new IllegalArgumentException( + clientLabel + " " + label + " must be an existing readable file"); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest.java new file mode 100644 index 0000000000..237e380ec9 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest.java @@ -0,0 +1,349 @@ +package net.firedevops.firemud.common.security.sourceintake; + +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.Context; +import io.grpc.Deadline; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +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 io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.automationscripting.v1.AutomationSelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceRequest; +import net.firedevops.firemud.automationscripting.v1.RetainSelectedSourceResponse; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.automation.sourceintake.AutomationEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.automation.sourceintake.AutomationSelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +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.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.security.sourceintake.SelectedSourceIntakeCommandTestPki.Identity; +import net.firedevops.firemud.common.security.sourceintake.SelectedSourceIntakeCommandTestPki.Pki; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +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; + +/** + * Positive command mTLS proof; synthetic fixture is not an Automation producer or physical census + * proof. + */ +class GrpcAutomationSelectedSourceIntakeCommandClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String AUTOMATION_URI = + "spiffe://firemud/ns/test/sa/automation-scripting-service"; + private static final String WRONG_AUTOMATION_URI = "spiffe://firemud/ns/test/sa/automation-other"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + + @TempDir static Path tempDirectory; + private static Fixture fixture; + private static Pki pki; + private Server server; + private GrpcAutomationSelectedSourceIntakeCommandClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + private AtomicReference deadline; + private static AutomationEmptySelectedSourceIntakeReceipt receipt; + + @BeforeAll + static void createSyntheticInputsAndTrustedCertificates() throws Exception { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + var authorization = fixture.wrongOwnerAuthorization(); + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var worldEvidence = + new SelectedOwnerWorldInventoryReadEvidence( + SelectedOwnerWorldInventoryReadEvidence.Request.create( + NAMESPACE, authorization, freeze), + fixture.inputs().worldInventoryReadEvidence().inventory()); + var inputs = new SelectedOwnerEmptySourceInputs(authorization, worldEvidence); + receipt = + AutomationEmptySelectedSourceIntakeReceipt.create( + inputs, + 9001L, + 9002L, + AutomationEmptySelectedSourceIntakeReceipt.requestDigest( + NAMESPACE, authorization, freeze), + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + java.time.OffsetDateTime.parse("2026-10-01T00:00:00Z")); + pki = + SelectedSourceIntakeCommandTestPki.create( + tempDirectory, + "FireMUD Automation command test CA", + AUTOMATION_URI, + WRONG_AUTOMATION_URI, + GAME_DESIGN_URI); + } + + @AfterEach + void stopTransportAndClearAmbientContext() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void loopbackMtlsReturnsExactReceiptAndPinsAutomationServerWithBoundedDeadline() + throws Exception { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, fixture.wrongOwnerAuthorization(), freeze); + byte[] receiptBytes = receipt.canonicalBytes(); + + startServer(pki.server()); + client = newClient(server, pki.gameDesignClient()); + client.init(); + var actual = client.retain(request); + assertThat(actual.request()).isEqualTo(request); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(receiptBytes); + assertThat(actual.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.wrongOwnerAuthorization().canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + assertThat(deadline.get()).isNotNull(); + assertThat(deadline.get().timeRemaining(TimeUnit.SECONDS)).isBetween(1L, 5L); + + stopCurrentTransport(); + startServer(pki.wrongServer()); + client = newClient(server, pki.gameDesignClient()); + client.init(); + assertThatThrownBy(() -> client.retain(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + @Test + void malformedReceiptResponseFailsClosedAfterAuthenticatedTransport() throws Exception { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, fixture.wrongOwnerAuthorization(), freeze); + startServer(pki.server(), true); + client = newClient(server, pki.gameDesignClient()); + client.init(); + + assertThatThrownBy(() -> client.retain(request)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("invalid selected-source receipt evidence"); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + } + + @Test + void namespaceSqlSynchronizationEndUserAndSelectedOrderAreDeniedBeforeTransport(@TempDir Path dir) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var request = + AutomationSelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, + fixture.wrongOwnerAuthorization(), + fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence()); + var wrongNamespaceClient = + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), + SelectedSourceIntakeCommandTestPki.placeholderTls(dir), + factory, + "other"); + try { + assertThatThrownBy(() -> wrongNamespaceClient.retain(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(factory); + } finally { + wrongNamespaceClient.close(); + } + + var client = + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), + SelectedSourceIntakeCommandTestPki.placeholderTls(dir), + factory, + NAMESPACE); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + SessionContext.clear(); + + for (var producerContext : + List.of( + Context.current() + .withValue( + AccountOriginalDraftOrderCredentials.CONTEXT_KEY, + AccountOriginalDraftOrderCredentials.Credential.of( + "controlled-original-author")), + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, + AccountGameLogicIntakeAuthorizationCredentials.Credential.of( + "controlled-game-logic-author")), + Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of( + "controlled-selected-intake-author")))) { + var previous = producerContext.attach(); + try { + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + } finally { + producerContext.detach(previous); + } + } + verifyNoInteractions(factory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private void startServer(Identity identity) throws Exception { + startServer(identity, false); + } + + private void startServer(Identity identity, boolean malformedResponse) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + deadline = new AtomicReference<>(); + var service = + new AutomationSelectedSourceIntakeCommandServiceGrpc + .AutomationSelectedSourceIntakeCommandServiceImplBase() { + @Override + public void retainSelectedSource( + RetainSelectedSourceRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_DESIGN_URI); + deadline.set(Context.current().getDeadline()); + var request = AutomationSelectedSourceIntakeCommandGrpcCodec.fromRequest(wire); + assertThat(request.originalAuthorizationBinding().canonicalBytes()) + .isEqualTo(fixture.wrongOwnerAuthorization().canonicalBytes()); + assertThat(request.freezeEvidence()) + .isEqualTo( + fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence()); + var response = + AutomationSelectedSourceIntakeCommandGrpcCodec.toResponse( + new AutomationSelectedSourceIntakeCommandEvidence(request, receipt)); + if (malformedResponse) { + response = response.toBuilder().setReceiptDigest("0".repeat(64)).build(); + } + observer.onNext(response); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + AutomationSelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcAutomationSelectedSourceIntakeCommandClient newClient(Server target, Identity local) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setAutomationScriptingService("localhost:" + target.getPort()); + return new GrpcAutomationSelectedSourceIntakeCommandClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + private void stopCurrentTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java new file mode 100644 index 0000000000..c147e4bb4b --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcAutomationSelectedSourceIntakeCommandClientTest.java @@ -0,0 +1,155 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.security.SessionContext; +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; + +/** Constructor and pre-transport gates only; placeholder files do not prove an mTLS handshake. */ +class GrpcAutomationSelectedSourceIntakeCommandClientTest { + @AfterEach + void clearAmbientContext() { + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void requiresReadableFileBackedMtlsAndCanonicalNamespace(@TempDir Path directory) + throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var plaintext = tls(directory); + plaintext.setPlaintext(true); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), plaintext, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("mTLS"); + + for (String invalidPath : + new String[] { + null, + "", + "classpath:credential.pem", + directory.toString(), + directory.resolve("missing.pem").toString() + }) { + var invalidCertificate = tls(directory); + invalidCertificate.setCertChain(invalidPath); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidCertificate, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + } + var invalidKey = tls(directory); + invalidKey.setPrivateKey(directory.resolve("missing-key.pem").toString()); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidKey, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + var invalidCa = tls(directory); + invalidCa.setCaCert(directory.resolve("missing-ca.pem").toString()); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), invalidCa, channelFactory, "test")) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy( + () -> + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "Test")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("namespace"); + + verifyNoInteractions(channelFactory); + } + + @Test + void rejectsAmbientSqlSynchronizationAndEndUserContextBeforeTransport(@TempDir Path directory) + throws IOException { + var channelFactory = mock(GrpcChannelFactory.class); + var client = + new GrpcAutomationSelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), tls(directory), channelFactory, "test"); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + SessionContext.clear(); + for (var producerContext : + List.of( + Context.current() + .withValue( + AccountOriginalDraftOrderCredentials.CONTEXT_KEY, + AccountOriginalDraftOrderCredentials.Credential.of( + "controlled-original-author")), + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, + AccountGameLogicIntakeAuthorizationCredentials.Credential.of( + "controlled-game-logic-author")), + Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of( + "controlled-selected-intake-author")))) { + var previous = producerContext.attach(); + try { + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + } finally { + producerContext.detach(previous); + } + } + verifyNoInteractions(channelFactory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private static CommonGrpcClientProperties tls(Path directory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "placeholder cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "placeholder key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "placeholder CA").toString()); + return tls; + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java new file mode 100644 index 0000000000..516a564fa6 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/GrpcEntitySelectedSourceIntakeCommandClientMtlsTest.java @@ -0,0 +1,289 @@ +package net.firedevops.firemud.common.security.sourceintake; + +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.Context; +import io.grpc.Deadline; +import io.grpc.Metadata; +import io.grpc.Server; +import io.grpc.ServerCall; +import io.grpc.ServerCallHandler; +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 io.grpc.stub.StreamObserver; +import java.net.InetSocketAddress; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.config.ServiceEndpointsProperties; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.GrpcChannelFactory; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentityInterceptor; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.common.security.sourceintake.SelectedSourceIntakeCommandTestPki.Identity; +import net.firedevops.firemud.common.security.sourceintake.SelectedSourceIntakeCommandTestPki.Pki; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +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; + +/** + * Positive command mTLS proof; synthetic fixture is not Entity producer or physical census proof. + */ +class GrpcEntitySelectedSourceIntakeCommandClientMtlsTest { + private static final String NAMESPACE = "test"; + private static final String ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-management-service"; + private static final String WRONG_ENTITY_URI = "spiffe://firemud/ns/test/sa/entity-other"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + + @TempDir static Path tempDirectory; + private static Fixture fixture; + private static Pki pki; + private Server server; + private GrpcEntitySelectedSourceIntakeCommandClient client; + private AtomicInteger headers; + private AtomicInteger bodies; + private AtomicReference deadline; + + @BeforeAll + static void createSyntheticInputsAndTrustedCertificates() throws Exception { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + pki = + SelectedSourceIntakeCommandTestPki.create( + tempDirectory, + "FireMUD Entity command test CA", + ENTITY_URI, + WRONG_ENTITY_URI, + GAME_DESIGN_URI); + } + + @AfterEach + void stopTransportAndClearAmbientContext() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + + @Test + void loopbackMtlsReturnsExactReceiptAndPinsEntityServerWithBoundedDeadline() throws Exception { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, fixture.authorization(), freeze); + byte[] receiptBytes = fixture.receipt().canonicalBytes(); + + startServer(pki.server()); + client = newClient(server, pki.gameDesignClient()); + client.init(); + var actual = client.retain(request); + assertThat(actual.request()).isEqualTo(request); + assertThat(actual.receipt().canonicalBytes()).isEqualTo(receiptBytes); + assertThat(actual.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat(headers).hasValue(1); + assertThat(bodies).hasValue(1); + assertThat(deadline.get()).isNotNull(); + assertThat(deadline.get().timeRemaining(TimeUnit.SECONDS)).isBetween(1L, 5L); + + stopCurrentTransport(); + startServer(pki.wrongServer()); + client = newClient(server, pki.gameDesignClient()); + client.init(); + assertThatThrownBy(() -> client.retain(request)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> + assertThat(Status.fromThrowable(failure).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED)); + assertThat(headers).hasValue(0); + assertThat(bodies).hasValue(0); + } + + @Test + void namespaceSqlSynchronizationEndUserAndSelectedOrderAreDeniedBeforeTransport(@TempDir Path dir) + throws Exception { + var factory = mock(GrpcChannelFactory.class); + var request = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, + fixture.authorization(), + fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence()); + var wrongNamespaceClient = + new GrpcEntitySelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), + SelectedSourceIntakeCommandTestPki.placeholderTls(dir), + factory, + "other"); + try { + assertThatThrownBy(() -> wrongNamespaceClient.retain(request)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("configured workload namespace"); + verifyNoInteractions(factory); + } finally { + wrongNamespaceClient.close(); + } + + var client = + new GrpcEntitySelectedSourceIntakeCommandClient( + new ServiceEndpointsProperties(), + SelectedSourceIntakeCommandTestPki.placeholderTls(dir), + factory, + NAMESPACE); + try { + TransactionSynchronizationManager.setActualTransactionActive(true); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("ambient SQL"); + TransactionSynchronizationManager.clearSynchronization(); + + SessionContext.setContext("101", List.of(), Map.of()); + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + SessionContext.clear(); + + for (var producerContext : + List.of( + Context.current() + .withValue( + AccountOriginalDraftOrderCredentials.CONTEXT_KEY, + AccountOriginalDraftOrderCredentials.Credential.of( + "controlled-original-author")), + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, + AccountGameLogicIntakeAuthorizationCredentials.Credential.of( + "controlled-game-logic-author")), + Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of( + "controlled-selected-intake-author")))) { + var previous = producerContext.attach(); + try { + assertThatThrownBy(() -> client.retain(null)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("workload-only context"); + } finally { + producerContext.detach(previous); + } + } + verifyNoInteractions(factory); + } finally { + client.close(); + TransactionSynchronizationManager.clear(); + SessionContext.clear(); + } + } + + private void startServer(Identity identity) throws Exception { + headers = new AtomicInteger(); + bodies = new AtomicInteger(); + deadline = new AtomicReference<>(); + var service = + new EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceImplBase() { + @Override + public void retainSelectedEntitySource( + RetainSelectedEntitySourceRequest wire, + StreamObserver observer) { + bodies.incrementAndGet(); + assertThat(GrpcPeerIdentity.current().uri()).isEqualTo(GAME_DESIGN_URI); + deadline.set(Context.current().getDeadline()); + var request = EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(wire); + assertThat(request.originalAuthorizationBinding().canonicalBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat(request.freezeEvidence()) + .isEqualTo( + fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence()); + observer.onNext( + EntitySelectedSourceIntakeCommandGrpcCodec.toResponse( + new EntitySelectedSourceIntakeCommandEvidence(request, fixture.receipt()))); + observer.onCompleted(); + } + }; + ServerInterceptor countHeaders = + new ServerInterceptor() { + @Override + public ServerCall.Listener interceptCall( + ServerCall call, + Metadata metadata, + ServerCallHandler next) { + headers.incrementAndGet(); + return next.startCall(call, metadata); + } + }; + server = + NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 0)) + .maxInboundMessageSize( + EntitySelectedSourceIntakeCommandGrpcCodec.MAX_REQUEST_WIRE_BYTES) + .sslContext( + GrpcSslContexts.configure( + SslContextBuilder.forServer(identity.privateKey(), identity.certificate())) + .trustManager(pki.caCertificate()) + .clientAuth(ClientAuth.REQUIRE) + .build()) + .addService( + ServerInterceptors.intercept( + service, countHeaders, new GrpcPeerIdentityInterceptor())) + .build() + .start(); + } + + private GrpcEntitySelectedSourceIntakeCommandClient newClient(Server target, Identity local) + throws Exception { + var endpoints = new ServiceEndpointsProperties(); + endpoints.setEntityManagementService("localhost:" + target.getPort()); + return new GrpcEntitySelectedSourceIntakeCommandClient( + endpoints, pki.clientProperties(tempDirectory, local), new GrpcChannelFactory(), NAMESPACE); + } + + private void stopCurrentTransport() throws Exception { + if (client != null) { + client.close(); + client = null; + } + if (server != null) { + server.shutdownNow(); + assertThat(server.awaitTermination(2, TimeUnit.SECONDS)).isTrue(); + server = null; + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java new file mode 100644 index 0000000000..0d4d9bdacd --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandClientLifecycleTest.java @@ -0,0 +1,276 @@ +package net.firedevops.firemud.common.security.sourceintake; + +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.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import io.grpc.ManagedChannel; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BooleanSupplier; +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.TlsCertificateWatcher; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +/** + * Actual file-watcher lifecycle proof with readable placeholder certificate files and mocked + * channels. This does not exercise a TLS handshake or establish workload/creator authority. + */ +class SelectedSourceIntakeCommandClientLifecycleTest { + private static final String TLS_RELOAD_PROPERTY = "firemud.grpc.tls-reload.enabled"; + + @ParameterizedTest + @EnumSource(ClientKind.class) + @Timeout(15) + @ResourceLock(Resources.SYSTEM_PROPERTIES) + void closeReleasesClientMonitorBeforeDrainingCertificateCallback( + ClientKind kind, @TempDir Path directory) throws Exception { + String previousReloadPolicy = System.getProperty(TLS_RELOAD_PROPERTY); + System.setProperty(TLS_RELOAD_PROPERTY, "true"); + CountDownLatch releaseClientMonitor = new CountDownLatch(1); + AtomicReference closeFailure = new AtomicReference<>(); + Thread monitorHolder = null; + Thread closeThread = null; + AbstractReloadingBlockingGrpcClient client = null; + TlsCertificateWatcher originalWatcher = null; + List channels = new CopyOnWriteArrayList<>(); + try { + ServiceEndpointsProperties endpoints = new ServiceEndpointsProperties(); + endpoints.setWorldManagementService("world.internal:6565"); + CommonGrpcClientProperties tls = tls(directory); + GrpcChannelFactory channelFactory = mock(GrpcChannelFactory.class); + when(channelFactory.buildChannel( + any(String.class), eq(6565), any(CommonGrpcClientProperties.class), eq(true))) + .thenAnswer( + invocation -> { + ManagedChannel channel = mock(ManagedChannel.class); + channels.add(channel); + return channel; + }); + ClientHandle handle = kind.create(endpoints, tls, channelFactory); + client = handle.client(); + handle.initialize().run(); + AbstractReloadingBlockingGrpcClient clientUnderTest = client; + + originalWatcher = watcher(client); + Set activeCallbacks = activeCallbacks(originalWatcher); + TlsCertificateWatcher closeBoundary = mock(TlsCertificateWatcher.class); + TlsCertificateWatcher delegatedWatcher = originalWatcher; + doAnswer( + invocation -> { + assertThat(Thread.holdsLock(clientUnderTest)) + .as("the client monitor must be released before watcher shutdown") + .isFalse(); + delegatedWatcher.close(); + return null; + }) + .when(closeBoundary) + .close(); + setWatcher(clientUnderTest, closeBoundary); + CountDownLatch clientMonitorHeld = new CountDownLatch(1); + monitorHolder = + new Thread( + () -> { + synchronized (clientUnderTest) { + clientMonitorHeld.countDown(); + awaitLatch(releaseClientMonitor); + } + }, + "selected-intake-command-client-monitor-holder"); + monitorHolder.start(); + assertThat(clientMonitorHeld.await(5, TimeUnit.SECONDS)).isTrue(); + + CountDownLatch closeStarted = new CountDownLatch(1); + Thread closeWorker = + new Thread( + () -> { + closeStarted.countDown(); + try { + clientUnderTest.close(); + } catch (Throwable failure) { + closeFailure.set(failure); + } + }, + "selected-intake-command-client-close"); + closeThread = closeWorker; + closeWorker.start(); + assertThat(closeStarted.await(5, TimeUnit.SECONDS)).isTrue(); + awaitCondition(() -> closeWorker.getState() == Thread.State.BLOCKED); + + Files.writeString(Path.of(tls.getCertChain()), "certificate-rotated"); + Thread callback = awaitBlockedReloadCallback(activeCallbacks); + assertThat(callback).isNotNull(); + + releaseClientMonitor.countDown(); + closeWorker.join(TimeUnit.SECONDS.toMillis(4)); + assertThat(closeWorker.isAlive()) + .as("close must not hold the client monitor while the watcher drains its callback") + .isFalse(); + assertThat(closeFailure.get()).isNull(); + + clientUnderTest.close(); + assertThatThrownBy(() -> handle.initialize().run()) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("closed"); + assertThat(channels).isNotEmpty(); + for (ManagedChannel channel : channels) { + verify(channel, times(1)).shutdown(); + } + } finally { + releaseClientMonitor.countDown(); + if (monitorHolder != null) { + monitorHolder.join(TimeUnit.SECONDS.toMillis(5)); + } + if (closeThread != null) { + closeThread.join(TimeUnit.SECONDS.toMillis(7)); + } + try { + if (originalWatcher != null) { + originalWatcher.close(); + } + } finally { + try { + if (client != null) { + if (originalWatcher != null) { + setWatcher(client, originalWatcher); + } + client.close(); + } + } finally { + restoreReloadPolicy(previousReloadPolicy); + } + } + } + } + + @FunctionalInterface + private interface Initialize { + void run() throws Exception; + } + + private record ClientHandle( + AbstractReloadingBlockingGrpcClient client, Initialize initialize) {} + + private enum ClientKind { + ENTITY, + AUTOMATION; + + ClientHandle create( + ServiceEndpointsProperties endpoints, + CommonGrpcClientProperties tls, + GrpcChannelFactory factory) { + return switch (this) { + case ENTITY -> { + var client = + new GrpcEntitySelectedSourceIntakeCommandClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + case AUTOMATION -> { + var client = + new GrpcAutomationSelectedSourceIntakeCommandClient(endpoints, tls, factory, "test"); + yield new ClientHandle(client, client::init); + } + }; + } + } + + private static Thread awaitBlockedReloadCallback(Set activeCallbacks) + throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (System.nanoTime() < deadline) { + for (Thread callback : activeCallbacks) { + if (callback.getState() == Thread.State.BLOCKED + && hasFrame(callback, "AbstractReloadingBlockingGrpcClient", "reloadChannel")) { + return callback; + } + } + Thread.sleep(10); + } + return null; + } + + private static boolean hasFrame(Thread thread, String className, String methodName) { + for (StackTraceElement frame : thread.getStackTrace()) { + if (frame.getClassName().endsWith(className) && frame.getMethodName().equals(methodName)) { + return true; + } + } + return false; + } + + private static void awaitCondition(BooleanSupplier condition) throws InterruptedException { + long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5); + while (!condition.getAsBoolean() && System.nanoTime() < deadline) { + Thread.sleep(10); + } + assertThat(condition.getAsBoolean()).isTrue(); + } + + private static void awaitLatch(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + } + } + + private static TlsCertificateWatcher watcher(AbstractReloadingBlockingGrpcClient client) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + return (TlsCertificateWatcher) field.get(client); + } + + private static void setWatcher( + AbstractReloadingBlockingGrpcClient client, TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = AbstractReloadingBlockingGrpcClient.class.getDeclaredField("watcher"); + field.setAccessible(true); + field.set(client, watcher); + } + + @SuppressWarnings("unchecked") + private static Set activeCallbacks(TlsCertificateWatcher watcher) + throws ReflectiveOperationException { + Field field = TlsCertificateWatcher.class.getDeclaredField("activeCallbacks"); + field.setAccessible(true); + return (Set) field.get(watcher); + } + + private static CommonGrpcClientProperties tls(Path directory) throws Exception { + CommonGrpcClientProperties tls = new CommonGrpcClientProperties(); + 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 certificate").toString()); + return tls; + } + + private static void restoreReloadPolicy(String previousValue) { + if (previousValue == null) { + System.clearProperty(TLS_RELOAD_PROPERTY); + } else { + System.setProperty(TLS_RELOAD_PROPERTY, previousValue); + } + } +} diff --git a/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandTestPki.java b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandTestPki.java new file mode 100644 index 0000000000..69ffed1b77 --- /dev/null +++ b/services/common-security/src/test/java/net/firedevops/firemud/common/security/sourceintake/SelectedSourceIntakeCommandTestPki.java @@ -0,0 +1,60 @@ +package net.firedevops.firemud.common.security.sourceintake; + +import java.io.IOException; +import java.nio.file.Path; +import java.security.PrivateKey; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; +import net.firedevops.firemud.test.LoopbackMtlsTestPki; + +/** Caller-specific identities for selected-source command loopback mTLS proofs. */ +final class SelectedSourceIntakeCommandTestPki { + private SelectedSourceIntakeCommandTestPki() {} + + static Pki create( + Path directory, + String caCommonName, + String serverUri, + String wrongServerUri, + String clientUri) + throws Exception { + var shared = + LoopbackMtlsTestPki.create( + directory, + caCommonName, + new LoopbackMtlsTestPki.IdentitySpec("entity-server", serverUri, true), + new LoopbackMtlsTestPki.IdentitySpec("wrong-entity-server", wrongServerUri, true), + new LoopbackMtlsTestPki.IdentitySpec("game-design-client", clientUri, false)); + return new Pki( + shared.caCertificate(), + adapt(shared.identity("entity-server")), + adapt(shared.identity("wrong-entity-server")), + adapt(shared.identity("game-design-client")), + shared); + } + + static CommonGrpcClientProperties placeholderTls(Path directory) throws IOException { + return LoopbackMtlsTestPki.placeholderTls(directory); + } + + private static Identity adapt(LoopbackMtlsTestPki.Identity identity) { + return new Identity(identity.privateKey(), identity.certificate()); + } + + record Identity(PrivateKey privateKey, X509Certificate certificate) {} + + record Pki( + X509Certificate caCertificate, + Identity server, + Identity wrongServer, + Identity gameDesignClient, + LoopbackMtlsTestPki.Pki shared) { + CommonGrpcClientProperties clientProperties(Path directory, Identity identity) + throws IOException, CertificateEncodingException { + var sharedIdentity = + new LoopbackMtlsTestPki.Identity(identity.privateKey(), identity.certificate()); + return shared.clientProperties(directory, sharedIdentity); + } + } +} diff --git a/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java new file mode 100644 index 0000000000..ed87ad4d05 --- /dev/null +++ b/services/common-test-support/src/testFixtures/java/net/firedevops/firemud/test/LoopbackMtlsTestPki.java @@ -0,0 +1,276 @@ +package net.firedevops.firemud.test; + +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.CertificateEncodingException; +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; +import java.util.concurrent.TimeUnit; +import net.firedevops.firemud.common.grpc.CommonGrpcClientProperties; + +/** Test-only PKI for loopback mTLS proofs. */ +public final class LoopbackMtlsTestPki { + private static final String STORE_PASSWORD = "test-only-store-password"; + + private LoopbackMtlsTestPki() {} + + public static Pki create(Path directory, String caCommonName, IdentitySpec... identities) + throws Exception { + Path caStore = directory.resolve("test-ca.p12"); + keytool( + "-genkeypair", + "-alias", + "test-ca", + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + caCommonName, + "-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"); + keytool( + "-exportcert", + "-alias", + "test-ca", + "-keystore", + caStore.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-rfc"); + X509Certificate caCertificate = readCertificate(caFile); + var issued = new java.util.LinkedHashMap(); + for (IdentitySpec identity : identities) { + if (issued.putIfAbsent(identity.alias(), issueIdentity(directory, caStore, caFile, identity)) + != null) { + throw new IllegalArgumentException("duplicate test certificate alias: " + identity.alias()); + } + } + return new Pki(caCertificate, Map.copyOf(issued)); + } + + public static CommonGrpcClientProperties placeholderTls(Path directory) throws IOException { + var tls = new CommonGrpcClientProperties(); + tls.setPlaintext(false); + tls.setCertChain( + Files.writeString(directory.resolve("client.crt"), "synthetic cert").toString()); + tls.setPrivateKey( + Files.writeString(directory.resolve("client.key"), "synthetic key").toString()); + tls.setCaCert(Files.writeString(directory.resolve("ca.crt"), "synthetic CA").toString()); + return tls; + } + + public record IdentitySpec(String alias, String workloadUri, boolean server) {} + + public record Identity(PrivateKey privateKey, X509Certificate certificate) {} + + public record Pki(X509Certificate caCertificate, Map identities) { + public Pki { + identities = Map.copyOf(identities); + } + + public Identity identity(String alias) { + Identity identity = identities.get(alias); + if (identity == null) { + throw new IllegalArgumentException("unknown test certificate alias: " + alias); + } + return identity; + } + + public CommonGrpcClientProperties clientProperties(Path directory, Identity identity) + throws IOException, CertificateEncodingException { + Path clientDirectory = Files.createTempDirectory(directory, "loopback-mtls-client-"); + Path certificate = + writePem( + clientDirectory.resolve("client.crt"), + "CERTIFICATE", + identity.certificate().getEncoded()); + Path privateKey = + writePem( + clientDirectory.resolve("client.key"), + "PRIVATE KEY", + identity.privateKey().getEncoded()); + Path caFile = + writePem( + clientDirectory.resolve("client-ca.crt"), "CERTIFICATE", caCertificate.getEncoded()); + var properties = new CommonGrpcClientProperties(); + properties.setPlaintext(false); + properties.setCertChain(certificate.toString()); + properties.setPrivateKey(privateKey.toString()); + properties.setCaCert(caFile.toString()); + return properties; + } + } + + private static Identity issueIdentity( + Path directory, Path caStore, Path caFile, IdentitySpec identity) throws Exception { + String alias = identity.alias(); + String san = "URI:" + identity.workloadUri() + ",DNS:localhost,IP:127.0.0.1"; + Path store = directory.resolve(alias + ".p12"); + Path request = directory.resolve(alias + ".csr"); + Path certificate = directory.resolve(alias + ".crt"); + keytool( + "-genkeypair", + "-alias", + alias, + "-keyalg", + "RSA", + "-keysize", + "2048", + "-dname", + "CN=" + alias, + "-validity", + "30", + "-ext", + "KU=digitalSignature,keyEncipherment", + "-ext", + "EKU=" + (identity.server() ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san, + "-storetype", + "PKCS12", + "-keystore", + store.toString(), + "-storepass", + STORE_PASSWORD, + "-keypass", + STORE_PASSWORD); + keytool( + "-certreq", + "-alias", + alias, + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + request.toString(), + "-ext", + "SAN=" + san); + keytool( + "-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=" + (identity.server() ? "serverAuth" : "clientAuth"), + "-ext", + "SAN=" + san); + keytool( + "-importcert", + "-alias", + "test-ca", + "-keystore", + store.toString(), + "-storetype", + "PKCS12", + "-storepass", + STORE_PASSWORD, + "-file", + caFile.toString(), + "-noprompt"); + keytool( + "-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 Identity( + (PrivateKey) keyStore.getKey(alias, STORE_PASSWORD.toCharArray()), + (X509Certificate) keyStore.getCertificate(alias)); + } + + private static void keytool(String... arguments) throws Exception { + Path executable = + Path.of( + System.getProperty("java.home"), + "bin", + System.getProperty("os.name").toLowerCase().contains("windows") + ? "keytool.exe" + : "keytool"); + var command = new ArrayList(); + command.add(executable.toString()); + command.addAll(List.of(arguments)); + Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); + if (!process.waitFor(30, TimeUnit.SECONDS)) { + process.destroyForcibly(); + process.waitFor(5, TimeUnit.SECONDS); + throw new IllegalStateException("keytool timed out"); + } + String output; + try (var stream = process.getInputStream()) { + output = new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + if (process.exitValue() != 0) { + throw new IllegalStateException("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); + } + } + + 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/entity-management-service/build.gradle.kts b/services/entity-management-service/build.gradle.kts index f83aff8cf7..548b296313 100644 --- a/services/entity-management-service/build.gradle.kts +++ b/services/entity-management-service/build.gradle.kts @@ -15,3 +15,17 @@ dependencies { implementation(project(":common-security")) implementation(libs.spring.boot.starter.cache) } + +// Export only owner classes for composed proofs; application and Flyway resources stay local. +val entityClassesProofJar by tasks.registering(Jar::class) { + archiveClassifier.set("classes-proof") + dependsOn(tasks.named("classes")) + from(sourceSets.main.get().output.classesDirs) +} + +val entityClassesProof by configurations.creating { + isCanBeConsumed = true + isCanBeResolved = false + extendsFrom(configurations.implementation.get()) + outgoing.artifact(entityClassesProofJar) +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java new file mode 100644 index 0000000000..44ee512dee --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepository.java @@ -0,0 +1,933 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.time.OffsetDateTime; +import java.time.ZoneOffset; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.impl.DSL; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Entity persistence boundary for immutable, freshly founded empty catalogues. */ +public final class EntityEmptySelectedSourceIntakeRepository { + private static final String KEY_RESERVATION = "entity_empty_source_numeric_key_reservation"; + private static final String ASSOCIATION = "entity_empty_selected_source_association"; + private static final String FAMILY_STATE = "entity_empty_selected_source_family_state"; + private static final String RECEIPT = "entity_empty_selected_source_receipt"; + private static final Map EMPTY_ONLY_PROVIDER_TABLES = + Map.ofEntries( + Map.entry( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", "entity_empty_source_actor_body_layout_assignments"), + Map.entry("ARCHETYPE_ASSIGNMENTS", "entity_empty_source_archetype_assignments"), + Map.entry("ARCHETYPE_CONSTRAINTS", "entity_empty_source_archetype_constraints"), + Map.entry("ARCHETYPE_ROOTS", "entity_empty_source_archetype_roots"), + Map.entry("BALANCE_CURVE_ATTACHMENTS", "entity_empty_source_balance_curve_attachments"), + Map.entry("BALANCE_CURVE_ROOTS", "entity_empty_source_balance_curve_roots"), + Map.entry("EQUIPMENT_ATTACHMENT_RULES", "entity_empty_source_equipment_attachment_rules"), + Map.entry("EQUIPMENT_CAPABILITIES", "entity_empty_source_equipment_capabilities"), + Map.entry( + "EQUIPMENT_COMPATIBILITY_RULES", "entity_empty_source_equipment_compatibility_rules"), + Map.entry("EQUIPMENT_OCCUPANCY_RULES", "entity_empty_source_equipment_occupancy_rules"), + Map.entry("INBOUND_LOOT_BINDINGS", "entity_empty_source_inbound_loot_bindings"), + Map.entry("LOOT_ITEM_MAPPINGS", "entity_empty_source_loot_item_mappings"), + Map.entry("LOOT_TABLE_ROOTS", "entity_empty_source_loot_table_roots"), + Map.entry( + "OTHER_ACTOR_TEMPLATE_ROOTS", "entity_empty_source_other_actor_template_roots")); + private static final List EMPTY_ONLY_PROVIDER_LOCKS = + List.of( + "entity_empty_source_other_actor_template_roots", + "entity_empty_source_equipment_capabilities", + "entity_empty_source_equipment_attachment_rules", + "entity_empty_source_equipment_compatibility_rules", + "entity_empty_source_equipment_occupancy_rules", + "entity_empty_source_actor_body_layout_assignments", + "entity_empty_source_loot_table_roots", + "entity_empty_source_loot_item_mappings", + "entity_empty_source_inbound_loot_bindings", + "entity_empty_source_balance_curve_roots", + "entity_empty_source_balance_curve_attachments", + "entity_empty_source_archetype_roots", + "entity_empty_source_archetype_constraints", + "entity_empty_source_archetype_assignments"); + + private static final String READ_RECEIPT = + "SELECT a.target_namespace, a.genesis_id, a.operation_id, a.fence_id, " + + "a.intake_request_id, a.canonical_tenant_id, a.canonical_version_id, " + + "a.local_tenant_key, a.local_version_key, a.request_digest, a.schema_digest, " + + "a.authorization_binding_digest, a.selected_source_digest, a.world_read_request_id, " + + "a.world_read_request_digest, a.world_closure_digest, a.receipt_digest, a.associated_at, " + + "r.request_digest, r.schema_digest, r.receipt_digest, r.receipt_bytes, r.retained_at, " + + "a.selected_commit_id, a.source_revision_id, a.source_revision_order " + + "FROM " + + ASSOCIATION + + " a LEFT JOIN " + + RECEIPT + + " r ON r.target_namespace = a.target_namespace " + + "AND r.intake_request_id = a.intake_request_id " + + "WHERE a.target_namespace = ? AND a.intake_request_id = ?"; + + private static final String SOURCE_TABLE_LOCKS = + "LOCK TABLE actor_active_conditions, actor_resource_states, body_layout_slot_definitions, " + + "character_equipment, character_friend, characters, container_instances, " + + "crafting_ingredients, crafting_recipes, entity_mutation_effects, " + + "equipment_slot_definitions, inventory, item_instances, item_stacks, " + + "item_transfer_audits, item_visible_ref_counters, items, npcs, room_ground_inventory IN SHARE MODE"; + + private final DSLContext dsl; + + public EntityEmptySelectedSourceIntakeRepository(DSLContext dsl) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + } + + /** + * Reads only a committed exact receipt; absence is not interpreted as abort or source absence. + */ + public Optional read( + String targetNamespace, UUID intakeRequestId) { + requireNoAmbientOwnerSql("Entity source receipt read"); + requireReadKey(targetNamespace, intakeRequestId); + return readValidated(dsl, targetNamespace, intakeRequestId); + } + + /** + * Resolves the one immutable selected-empty receipt for a canonical tenant and Game Design + * Version row. Every association in the tenant prefix is fully read back before its retained + * original TargetProof is considered; owner-local numeric keys are not publication identity. + */ + public EntityEmptySelectedSourceIntakeReceipt readPublicationScope( + String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + requireNoAmbientOwnerSql("Entity publication receipt read"); + requirePublicationScopeKey(targetNamespace, canonicalTenantId, gameDesignVersionRowId); + + return dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"); + var associations = + tx.fetch( + "SELECT canonical_version_id, intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND canonical_tenant_id = ? " + + "ORDER BY canonical_version_id", + targetNamespace, + canonicalTenantId); + if (associations.isEmpty()) { + throw new IllegalStateException( + "Entity selected-empty publication receipt is unavailable"); + } + + var matches = new ArrayList(); + for (Record association : associations) { + UUID associatedCanonicalVersionId = association.get(0, UUID.class); + UUID intakeRequestId = association.get(1, UUID.class); + if (associatedCanonicalVersionId == null || intakeRequestId == null) { + throw new CorruptReceiptException( + "Entity publication association identity is corrupt"); + } + EntityEmptySelectedSourceIntakeReceipt receipt = + readValidated(tx, targetNamespace, intakeRequestId) + .orElseThrow( + () -> + new CorruptReceiptException( + "Entity publication association has no committed receipt")); + var target = receipt.authorizationBinding().selected().target(); + if (!canonicalTenantId.equals(receipt.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(receipt.canonicalVersionId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || !associatedCanonicalVersionId.equals(target.canonicalVersionId())) { + throw new CorruptReceiptException( + "Entity publication association differs from the retained selected target"); + } + if (target.gameDesignVersionRowId() == gameDesignVersionRowId) { + matches.add(receipt); + } + } + if (matches.size() != 1) { + throw new IllegalStateException( + "Entity selected-empty publication scope is missing or ambiguous"); + } + return matches.get(0); + }); + } + + /** + * Commits a fresh empty catalogue and reads it back independently. A provider missing from the + * current Entity schema blocks founding, even if its creator declaration says the family is + * empty. + */ + public EntityEmptySelectedSourceIntakeReceipt retainFresh( + SelectedOwnerEmptySourceInputs inputs, String requestDigest) { + Objects.requireNonNull(inputs, "validated selected empty-source inputs are required"); + SelectedOwnerIntakeAuthorizationBinding binding = inputs.authorizationBinding(); + String expectedDigest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + binding.targetNamespace(), + binding, + inputs.worldInventoryReadEvidence().request().freezeEvidence()); + if (!expectedDigest.equals(requestDigest)) { + throw new IllegalArgumentException("Entity source intake request digest differs"); + } + requireExactEntityBinding(binding); + requireNoAmbientOwnerSql("Entity source catalogue transaction"); + + UUID genesisId = UUID.randomUUID(); + EntityEmptySelectedSourceIntakeReceipt committed = + dsl.transactionResult( + configuration -> { + DSLContext tx = DSL.using(configuration); + tx.execute("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"); + lockOwnerRecords(tx); + lockSourceAndInboundTables(tx); + + Optional previous = + readValidated(tx, binding.targetNamespace(), binding.intakeRequestId()); + if (previous.isPresent()) { + EntityEmptySelectedSourceIntakeReceipt receipt = previous.orElseThrow(); + receipt.requireSameInputs(inputs); + return receipt; + } + requireNoPriorScopeOrOperation(tx, binding); + + long maximumOccupiedKey = maximumOccupiedSourceKey(tx); + long localTenantKey = Math.addExact(maximumOccupiedKey, 1L); + long localVersionKey = Math.addExact(maximumOccupiedKey, 2L); + List familyStates = + censusEveryDeclaredFamily(tx, inputs, localTenantKey, localVersionKey); + + reserveCanonicalKey(tx, "TENANT", localTenantKey); + reserveCanonicalKey(tx, "VERSION", localVersionKey); + OffsetDateTime retainedAt = + requiredScalar(tx, "SELECT CURRENT_TIMESTAMP", OffsetDateTime.class) + .withOffsetSameInstant(ZoneOffset.UTC); + EntityEmptySelectedSourceIntakeReceipt receipt = + EntityEmptySelectedSourceIntakeReceipt.create( + inputs, + genesisId, + localTenantKey, + localVersionKey, + requestDigest, + familyStates, + retainedAt); + insertAssociation(tx, receipt); + insertEmptyOnlyProviderStates(tx, receipt); + insertFamilyStates(tx, receipt); + insertReceipt(tx, receipt); + return receipt; + }); + + EntityEmptySelectedSourceIntakeReceipt readBack = + read(committed.targetNamespace(), committed.intakeRequestId()) + .orElseThrow( + () -> + new CorruptReceiptException( + "Committed Entity source catalogue receipt is unavailable")); + if (!Arrays.equals(committed.canonicalBytes(), readBack.canonicalBytes()) + || !committed.receiptDigest().equals(readBack.receiptDigest()) + || !committed.requestDigest().equals(readBack.requestDigest()) + || !committed.genesisId().equals(readBack.genesisId())) { + throw new CorruptReceiptException("Committed Entity source receipt readback differs"); + } + return readBack; + } + + private static void lockOwnerRecords(DSLContext tx) { + tx.execute( + "LOCK TABLE " + + KEY_RESERVATION + + ", " + + ASSOCIATION + + ", " + + FAMILY_STATE + + ", " + + RECEIPT + + ", " + + String.join(", ", EMPTY_ONLY_PROVIDER_LOCKS) + + " IN SHARE ROW EXCLUSIVE MODE"); + } + + private static void lockSourceAndInboundTables(DSLContext tx) { + // Locks cover every source row, Entity item FK, actor/holder path, and logical slot/layout + // reference read by the conservative census. SHARE is held until the catalogue commit. + tx.execute(SOURCE_TABLE_LOCKS); + } + + private static void requireNoPriorScopeOrOperation( + DSLContext tx, SelectedOwnerIntakeAuthorizationBinding binding) { + Record prior = + tx.fetchOne( + "SELECT intake_request_id FROM " + + ASSOCIATION + + " WHERE target_namespace = ? AND (" + + "(canonical_tenant_id = ? AND canonical_version_id = ?) OR operation_id = ?) LIMIT 1", + binding.targetNamespace(), + binding.tenantId(), + binding.versionId(), + binding.operationId()); + if (prior != null) { + throw new IntakeConflictException( + "Entity selected scope or owner operation is already associated"); + } + } + + private static List + censusEveryDeclaredFamily( + DSLContext tx, + SelectedOwnerEmptySourceInputs inputs, + long localTenantKey, + long localVersionKey) { + List declaredFamilies = + declaredFamilies( + inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson()); + var result = new ArrayList(23); + for (String family : declaredFamilies) { + requireReadableProvider(family); + Census counts = + EMPTY_ONLY_PROVIDER_TABLES.containsKey(family) + ? Census.emptyOnlyProviderState() + : switch (family) { + case "ITEM_TEMPLATE_ROOTS" -> censusItems(tx, localTenantKey, localVersionKey); + case "NPC_TEMPLATE_ROOTS" -> censusNpcs(tx, localTenantKey, localVersionKey); + case "CRAFTING_RECIPE_ROOTS" -> + censusRecipes(tx, localTenantKey, localVersionKey, false); + case "CRAFTING_RECIPE_RESULT_BINDINGS" -> + censusRecipes(tx, localTenantKey, localVersionKey, true); + case "CRAFTING_INGREDIENT_BINDINGS" -> + censusIngredients(tx, localTenantKey, localVersionKey); + case "EQUIPMENT_SLOT_ROOTS" -> + censusEquipmentSlots(tx, localTenantKey, localVersionKey, false); + case "EQUIPMENT_SLOT_GROUPS" -> + censusEquipmentSlots(tx, localTenantKey, localVersionKey, true); + case "BODY_LAYOUT_ROOTS" -> + censusBodyLayouts(tx, localTenantKey, localVersionKey, true); + case "BODY_LAYOUT_MEMBERSHIPS" -> + censusBodyLayouts(tx, localTenantKey, localVersionKey, false); + default -> + throw new IllegalStateException( + "No readable persisted Entity source provider for family " + family); + }; + if (!counts.isZero()) { + throw new IntakeConflictException( + "Entity source family or inbound reference census is not freshly empty: " + family); + } + result.add( + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + family, + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + EMPTY_ONLY_PROVIDER_TABLES.containsKey(family) + ? EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER + : EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, + counts.rows(), + counts.unqualifiedRows(), + counts.retainedRows(), + counts.selectedScopeRows(), + counts.references())); + } + if (result.size() != 23) { + throw new IllegalStateException("Entity source census did not read all 23 declared families"); + } + return List.copyOf(result); + } + + static void requireReadableProvider(String family) { + if (!EMPTY_ONLY_PROVIDER_TABLES.containsKey(family) + && !List.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS") + .contains(family)) { + throw new IllegalStateException( + "No readable persisted Entity source provider for family " + family); + } + } + + private static Census censusItems(DSLContext tx, long tenantKey, long versionKey) { + return new Census( + count(tx, "SELECT COUNT(*) FROM items"), + count( + tx, + "SELECT COUNT(*) FROM items i WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = i.tenant_id AND a.local_version_key = i.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM items i WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = i.tenant_id AND a.local_version_key = i.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM items WHERE tenant_id = ? OR version_id = ?", + tenantKey, + versionKey), + countItemReferenceEdges(tx)); + } + + private static Census censusNpcs(DSLContext tx, long tenantKey, long versionKey) { + return new Census( + count(tx, "SELECT COUNT(*) FROM npcs"), + count( + tx, + "SELECT COUNT(*) FROM npcs n WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = n.tenant_id AND a.local_version_key = n.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM npcs n WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = n.tenant_id AND a.local_version_key = n.version_id)"), + count( + tx, + "SELECT COUNT(*) FROM npcs WHERE tenant_id = ? OR version_id = ?", + tenantKey, + versionKey), + 0L); + } + + private static Census censusRecipes( + DSLContext tx, long tenantKey, long versionKey, boolean resultBinding) { + String nonnullResult = resultBinding ? " WHERE result_item_id IS NOT NULL" : ""; + String aliasFilter = resultBinding ? " AND r.result_item_id IS NOT NULL" : ""; + return new Census( + count(tx, "SELECT COUNT(*) FROM crafting_recipes" + nonnullResult), + count( + tx, + "SELECT COUNT(*) FROM crafting_recipes r WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)" + + aliasFilter), + count( + tx, + "SELECT COUNT(*) FROM crafting_recipes r WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)" + + aliasFilter), + count( + tx, + "SELECT COUNT(*) FROM crafting_recipes r WHERE (r.tenant_id = ? OR r.version_id = ?)" + + aliasFilter, + tenantKey, + versionKey), + resultBinding + ? count(tx, "SELECT COUNT(*) FROM crafting_recipes WHERE result_item_id IS NOT NULL") + : count(tx, "SELECT COUNT(*) FROM crafting_ingredients")); + } + + private static Census censusIngredients(DSLContext tx, long tenantKey, long versionKey) { + String recipeAssociation = + "SELECT COUNT(*) FROM crafting_ingredients i JOIN crafting_recipes r ON r.id = i.recipe_id "; + return new Census( + count(tx, "SELECT COUNT(*) FROM crafting_ingredients"), + count( + tx, + recipeAssociation + + "WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"), + count( + tx, + recipeAssociation + + "WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = r.tenant_id AND a.local_version_key = r.version_id)"), + count( + tx, + recipeAssociation + "WHERE r.tenant_id = ? OR r.version_id = ?", + tenantKey, + versionKey), + count(tx, "SELECT COUNT(*) FROM crafting_ingredients")); + } + + private static Census censusEquipmentSlots( + DSLContext tx, long tenantKey, long versionKey, boolean groups) { + String identity = + groups + ? "SELECT DISTINCT tenant_id, version_id, slot_group_key AS source_key " + + "FROM equipment_slot_definitions WHERE slot_group_key IS NOT NULL" + : "SELECT tenant_id, version_id, slot_key AS source_key FROM equipment_slot_definitions"; + String itemReferences = + "SELECT COUNT(*) FROM (" + + "SELECT equipment_slot AS source_key FROM items WHERE equipment_slot IS NOT NULL " + + "UNION ALL SELECT slot FROM character_equipment WHERE slot IS NOT NULL " + + "UNION ALL SELECT equipment_slot FROM item_instances WHERE equipment_slot IS NOT NULL " + + "UNION ALL SELECT equipment_slot FROM item_stacks WHERE equipment_slot IS NOT NULL " + + "UNION ALL SELECT equipment_slot FROM container_instances WHERE equipment_slot IS NOT NULL" + + ") slot_refs"; + String groupReferences = + "SELECT COUNT(*) FROM items WHERE equipment_slot_group_key IS NOT NULL"; + String total = "SELECT COUNT(*) FROM (" + identity + ") entity_family"; + String unqualified = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String retained = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String selected = + "SELECT COUNT(*) FROM (" + identity + ") f WHERE f.tenant_id = ? OR f.version_id = ?"; + return new Census( + count(tx, total), + count(tx, unqualified), + count(tx, retained), + count(tx, selected, tenantKey, versionKey), + groups ? count(tx, groupReferences) : count(tx, itemReferences)); + } + + private static Census censusBodyLayouts( + DSLContext tx, long tenantKey, long versionKey, boolean roots) { + String identity = + roots + ? "SELECT DISTINCT tenant_id, version_id, body_layout_key AS source_key " + + "FROM body_layout_slot_definitions" + : "SELECT tenant_id, version_id, body_layout_key, slot_key " + + "FROM body_layout_slot_definitions"; + String total = "SELECT COUNT(*) FROM (" + identity + ") entity_family"; + String unqualified = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE NOT EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String retained = + "SELECT COUNT(*) FROM (SELECT f.* FROM (" + + identity + + ") f WHERE EXISTS (SELECT 1 FROM " + + ASSOCIATION + + " a WHERE a.local_tenant_key = f.tenant_id AND a.local_version_key = f.version_id)) q"; + String selected = + "SELECT COUNT(*) FROM (" + identity + ") f WHERE f.tenant_id = ? OR f.version_id = ?"; + return new Census( + count(tx, total), + count(tx, unqualified), + count(tx, retained), + count(tx, selected, tenantKey, versionKey), + roots + ? count(tx, "SELECT COUNT(*) FROM characters WHERE body_layout_key IS NOT NULL") + : count( + tx, + "SELECT COUNT(*) FROM characters c JOIN character_equipment e " + + "ON e.character_id = c.id WHERE c.body_layout_key IS NOT NULL")); + } + + private static long countItemReferenceEdges(DSLContext tx) { + return count( + tx, + "SELECT COUNT(*) FROM (" + + "SELECT item_id FROM inventory " + + "UNION ALL SELECT result_item_id FROM crafting_recipes " + + "UNION ALL SELECT item_id FROM crafting_ingredients " + + "UNION ALL SELECT item_id FROM room_ground_inventory " + + "UNION ALL SELECT item_id FROM character_equipment " + + "UNION ALL SELECT item_id FROM container_instances " + + "UNION ALL SELECT item_id FROM item_instances " + + "UNION ALL SELECT item_id FROM item_stacks " + + "UNION ALL SELECT item_id FROM item_transfer_audits " + + "UNION ALL SELECT item_instance_id FROM item_transfer_audits WHERE item_instance_id IS NOT NULL" + + ") item_refs"); + } + + private static long maximumOccupiedSourceKey(DSLContext tx) { + return requiredScalar( + tx, + "SELECT COALESCE(MAX(key_value), 0) FROM (" + + "SELECT numeric_key AS key_value FROM " + + KEY_RESERVATION + + " UNION ALL SELECT tenant_id FROM items WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM npcs WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM crafting_recipes WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM equipment_slot_definitions WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM body_layout_slot_definitions WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM room_ground_inventory WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM container_instances WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_instances WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_stacks WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM characters WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM character_friend WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_visible_ref_counters WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM entity_mutation_effects WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM item_transfer_audits WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM actor_resource_states WHERE tenant_id > 0" + + " UNION ALL SELECT tenant_id FROM actor_active_conditions WHERE tenant_id > 0" + + " UNION ALL SELECT version_id FROM items WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM npcs WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM crafting_recipes WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM equipment_slot_definitions WHERE version_id > 0" + + " UNION ALL SELECT version_id FROM body_layout_slot_definitions WHERE version_id > 0" + + ") occupied_entity_source_keys", + Long.class); + } + + private static void reserveCanonicalKey(DSLContext tx, String kind, long key) { + int inserted = + tx.execute( + "INSERT INTO " + + KEY_RESERVATION + + " (key_kind, numeric_key, claim_kind) VALUES (?, ?, 'CANONICAL_EMPTY_SOURCE')", + kind, + key); + if (inserted != 1) { + throw new IllegalStateException("Entity allocated numeric source key was not reserved"); + } + } + + private static void insertAssociation( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + int inserted = + tx.execute( + "INSERT INTO " + + ASSOCIATION + + " (target_namespace, genesis_id, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, " + + "request_digest, schema_digest, authorization_binding_digest, selected_source_digest, " + + "world_read_request_id, world_read_request_digest, world_closure_digest, receipt_digest, " + + "associated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.genesisId(), + receipt.operationId(), + receipt.fenceId(), + receipt.intakeRequestId(), + receipt.canonicalTenantId(), + receipt.canonicalVersionId(), + receipt.selectedCommitId(), + receipt.sourceRevisionId(), + receipt.sourceRevisionOrder(), + receipt.localTenantKey(), + receipt.localVersionKey(), + receipt.requestDigest(), + receipt.schemaDigest(), + receipt.authorizationBindingDigest(), + receipt.selectedSourceDigest(), + receipt.worldReadRequestId(), + receipt.worldReadRequestDigest(), + receipt.worldClosureDigest(), + receipt.receiptDigest(), + receipt.retainedAt()); + if (inserted != 1) + throw new IllegalStateException("Entity source association was not inserted"); + } + + private static void insertFamilyStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + for (var state : receipt.familyStates()) { + int inserted = + tx.execute( + "INSERT INTO " + + FAMILY_STATE + + " (target_namespace, intake_request_id, family_name, owner_state, evidence_kind, row_count, " + + "unqualified_row_count, retained_row_count, selected_scope_row_count, reference_count) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + receipt.targetNamespace(), + receipt.intakeRequestId(), + state.family(), + state.state().name(), + state.evidenceKind().name(), + state.rowCount(), + state.unqualifiedRowCount(), + state.retainedRowCount(), + state.selectedScopeRowCount(), + state.referenceCount()); + if (inserted != 1) { + throw new IllegalStateException("Entity source family state was not retained"); + } + } + } + + private static void insertEmptyOnlyProviderStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + for (var state : receipt.familyStates()) { + if (state.evidenceKind() + != EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) { + continue; + } + String table = EMPTY_ONLY_PROVIDER_TABLES.get(state.family()); + if (table == null) { + throw new IllegalStateException("Entity EMPTY-only family has no owner table"); + } + int inserted = + tx.execute( + "INSERT INTO " + + table + + " (target_namespace, intake_request_id, provider_schema_version, owner_state, " + + "row_count, reference_count, authorization_binding_digest, selected_source_digest, " + + "source_revision_binding_digest, world_closure_digest, provider_state_digest, observed_at) " + + "VALUES (?, ?, 1, ?, 0, 0, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.intakeRequestId(), + state.state().name(), + receipt.authorizationBindingDigest(), + receipt.selectedSourceDigest(), + receipt.selectedSourceRevisionBindingDigest(), + receipt.worldClosureDigest(), + receipt.providerStateDigest(state.family()), + receipt.retainedAt()); + if (inserted != 1) { + throw new IllegalStateException("Entity EMPTY-only provider state was not retained"); + } + } + } + + private static void insertReceipt(DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + int inserted = + tx.execute( + "INSERT INTO " + + RECEIPT + + " (target_namespace, intake_request_id, request_digest, schema_digest, " + + "receipt_digest, receipt_bytes, retained_at) VALUES (?, ?, ?, ?, ?, ?, " + + "CAST(? AS TIMESTAMPTZ))", + receipt.targetNamespace(), + receipt.intakeRequestId(), + receipt.requestDigest(), + receipt.schemaDigest(), + receipt.receiptDigest(), + receipt.canonicalBytes(), + receipt.retainedAt()); + if (inserted != 1) throw new IllegalStateException("Entity source receipt was not inserted"); + } + + private static Optional readValidated( + DSLContext tx, String targetNamespace, UUID intakeRequestId) { + Record row = tx.fetchOne(READ_RECEIPT, targetNamespace, intakeRequestId); + if (row == null) return Optional.empty(); + byte[] receiptBytes = row.get(21, byte[].class); + if (receiptBytes == null || row.get(22, OffsetDateTime.class) == null) { + throw new CorruptReceiptException("Entity source association has no committed receipt"); + } + final EntityEmptySelectedSourceIntakeReceipt receipt; + try { + receipt = EntityEmptySelectedSourceIntakeReceipt.fromStored(receiptBytes); + } catch (RuntimeException malformed) { + throw new CorruptReceiptException("Entity stored source receipt is corrupt"); + } + if (!Objects.equals(row.get(0, String.class), receipt.targetNamespace()) + || !Objects.equals(row.get(1, UUID.class), receipt.genesisId()) + || !Objects.equals(row.get(2, UUID.class), receipt.operationId()) + || !Objects.equals(row.get(3, UUID.class), receipt.fenceId()) + || !Objects.equals(row.get(4, UUID.class), receipt.intakeRequestId()) + || !Objects.equals(row.get(5, UUID.class), receipt.canonicalTenantId()) + || !Objects.equals(row.get(6, UUID.class), receipt.canonicalVersionId()) + || !Objects.equals(row.get(7, Long.class), receipt.localTenantKey()) + || !Objects.equals(row.get(8, Long.class), receipt.localVersionKey()) + || !Objects.equals(row.get(9, String.class), receipt.requestDigest()) + || !Objects.equals(row.get(10, String.class), receipt.schemaDigest()) + || !Objects.equals(row.get(11, String.class), receipt.authorizationBindingDigest()) + || !Objects.equals(row.get(12, String.class), receipt.selectedSourceDigest()) + || !Objects.equals(row.get(13, UUID.class), receipt.worldReadRequestId()) + || !Objects.equals(row.get(14, String.class), receipt.worldReadRequestDigest()) + || !Objects.equals(row.get(15, String.class), receipt.worldClosureDigest()) + || !Objects.equals(row.get(16, String.class), receipt.receiptDigest()) + || !sameInstant(row.get(17, OffsetDateTime.class), receipt.retainedAt()) + || !Objects.equals(row.get(18, String.class), receipt.requestDigest()) + || !Objects.equals(row.get(19, String.class), receipt.schemaDigest()) + || !Objects.equals(row.get(20, String.class), receipt.receiptDigest()) + || !sameInstant(row.get(22, OffsetDateTime.class), receipt.retainedAt()) + || !Objects.equals(row.get(23, UUID.class), receipt.selectedCommitId()) + || !Objects.equals(row.get(24, UUID.class), receipt.sourceRevisionId()) + || !Objects.equals(row.get(25, String.class), receipt.sourceRevisionOrder())) { + throw new CorruptReceiptException("Entity association differs from its immutable receipt"); + } + requirePersistedEmptyOnlyProviderStates(tx, receipt); + requirePersistedFamilyStates(tx, receipt); + return Optional.of(receipt); + } + + private static boolean sameInstant(OffsetDateTime actual, OffsetDateTime expected) { + return actual != null && expected != null && actual.toInstant().equals(expected.toInstant()); + } + + private static void requirePersistedEmptyOnlyProviderStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + for (var state : receipt.familyStates()) { + if (state.evidenceKind() + != EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.EMPTY_ONLY_OWNER_PROVIDER) { + continue; + } + String table = EMPTY_ONLY_PROVIDER_TABLES.get(state.family()); + if (table == null) { + throw new CorruptReceiptException("Entity EMPTY-only family has no owner table"); + } + Record row = + tx.fetchOne( + "SELECT provider_schema_version, owner_state, row_count, reference_count, " + + "authorization_binding_digest, selected_source_digest, " + + "source_revision_binding_digest, world_closure_digest, provider_state_digest, observed_at " + + "FROM " + + table + + " WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + if (row == null + || !Objects.equals(row.get(0, Short.class), (short) 1) + || !Objects.equals(row.get(1, String.class), state.state().name()) + || !Objects.equals(row.get(2, Long.class), state.rowCount()) + || !Objects.equals(row.get(3, Long.class), state.referenceCount()) + || !Objects.equals(row.get(4, String.class), receipt.authorizationBindingDigest()) + || !Objects.equals(row.get(5, String.class), receipt.selectedSourceDigest()) + || !Objects.equals( + row.get(6, String.class), receipt.selectedSourceRevisionBindingDigest()) + || !Objects.equals(row.get(7, String.class), receipt.worldClosureDigest()) + || !Objects.equals(row.get(8, String.class), receipt.providerStateDigest(state.family())) + || !sameInstant(row.get(9, OffsetDateTime.class), receipt.retainedAt())) { + throw new CorruptReceiptException( + "Entity EMPTY-only provider readback is missing or differs for " + state.family()); + } + } + } + + private static void requirePersistedFamilyStates( + DSLContext tx, EntityEmptySelectedSourceIntakeReceipt receipt) { + var rows = + tx.fetch( + "SELECT family_name, owner_state, evidence_kind, row_count, unqualified_row_count, retained_row_count, " + + "selected_scope_row_count, reference_count FROM " + + FAMILY_STATE + + " WHERE target_namespace = ? AND intake_request_id = ? ORDER BY family_name", + receipt.targetNamespace(), + receipt.intakeRequestId()); + if (rows.size() != receipt.familyStates().size()) { + throw new CorruptReceiptException("Entity retained family-state vector is incomplete"); + } + var expected = + receipt.familyStates().stream() + .sorted( + java.util.Comparator.comparing( + EntityEmptySelectedSourceIntakeReceipt.FamilyCensus::family)) + .toList(); + for (int index = 0; index < expected.size(); index++) { + Record row = rows.get(index); + var state = expected.get(index); + if (!Objects.equals(row.get(0, String.class), state.family()) + || !Objects.equals(row.get(1, String.class), state.state().name()) + || !Objects.equals(row.get(2, String.class), state.evidenceKind().name()) + || !Objects.equals(row.get(3, Long.class), state.rowCount()) + || !Objects.equals(row.get(4, Long.class), state.unqualifiedRowCount()) + || !Objects.equals(row.get(5, Long.class), state.retainedRowCount()) + || !Objects.equals(row.get(6, Long.class), state.selectedScopeRowCount()) + || !Objects.equals(row.get(7, Long.class), state.referenceCount())) { + throw new CorruptReceiptException("Entity retained family state differs from its receipt"); + } + } + } + + private static List declaredFamilies(String canonicalDeclaration) { + return EntityEmptySelectedSourceIntakeReceipt.familyNames(canonicalDeclaration); + } + + private static void requireExactEntityBinding(SelectedOwnerIntakeAuthorizationBinding binding) { + if (binding.owner() != Owner.ENTITY_MANAGEMENT + || !"account-entity-intake-authorization/v1".equals(binding.schema()) + || !"ENTITY_INTAKE_RETENTION".equals(binding.purpose()) + || !binding + .intendedReader() + .equals( + "spiffe://firemud/ns/" + + binding.targetNamespace() + + "/sa/entity-management-service")) { + throw new IllegalArgumentException("Exact original Entity Account authorization is required"); + } + } + + private static long count(DSLContext tx, String sql, Object... arguments) { + return requiredScalar(tx, sql, Long.class, arguments); + } + + private static T requiredScalar( + DSLContext tx, String sql, Class type, Object... arguments) { + Record result = tx.fetchOne(sql, arguments); + if (result == null || result.get(0, type) == null) { + throw new IllegalStateException("Entity source census query returned no scalar value"); + } + return result.get(0, type); + } + + private static void requireReadKey(String targetNamespace, UUID intakeRequestId) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) || intakeRequestId == null) { + throw new IllegalArgumentException( + "Canonical Entity source receipt read identity is required"); + } + DraftAuthorizationFenceBinding.requireUuid(intakeRequestId); + } + + private static void requirePublicationScopeKey( + String targetNamespace, UUID canonicalTenantId, long gameDesignVersionRowId) { + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || canonicalTenantId == null + || new UUID(0L, 0L).equals(canonicalTenantId) + || gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Entity publication scope identity is required"); + } + } + + private static void requireNoAmbientOwnerSql(String label) { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + label + " requires an independent Entity transaction boundary"); + } + } + + private record Census( + long rows, long unqualifiedRows, long retainedRows, long selectedScopeRows, long references) { + private Census { + if (rows < 0L + || unqualifiedRows < 0L + || retainedRows < 0L + || selectedScopeRows < 0L + || references < 0L + || Math.addExact(unqualifiedRows, retainedRows) != rows) { + throw new IllegalStateException("Entity census partitions are invalid"); + } + } + + private static Census emptyOnlyProviderState() { + // This is not inferred from missing legacy storage: the caller persists a typed, immutable + // EMPTY provider record for this exact newly authorized source and independently reads it. + return new Census(0L, 0L, 0L, 0L, 0L); + } + + private boolean isZero() { + return rows == 0L + && unqualifiedRows == 0L + && retainedRows == 0L + && selectedScopeRows == 0L + && references == 0L; + } + } + + public static final class IntakeConflictException extends IllegalStateException { + public IntakeConflictException(String message) { + super(message); + } + } + + /** Indicates that retained receipt bytes or owner rows fail their immutable readback contract. */ + public static final class CorruptReceiptException extends IllegalStateException { + public CorruptReceiptException(String message) { + super(message); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java new file mode 100644 index 0000000000..68345b3919 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeService.java @@ -0,0 +1,205 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadEvidence; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence; +import net.firedevops.firemud.common.security.SessionContext; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered preparation service for authenticated, freshly founded empty Entity scopes. */ +public final class EntityEmptySelectedSourceIntakeService { + private final String configuredNamespace; + private final EntityEmptySelectedSourceIntakeRepository repository; + private final SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient; + private final SelectedOwnerWorldInventoryReadClient worldInventoryReadClient; + + public EntityEmptySelectedSourceIntakeService( + String configuredNamespace, + EntityEmptySelectedSourceIntakeRepository repository, + SelectedOwnerIntakeAuthorizationReadClient authorizationReadClient, + SelectedOwnerWorldInventoryReadClient worldInventoryReadClient) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Entity namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.repository = Objects.requireNonNull(repository, "repository"); + this.authorizationReadClient = + Objects.requireNonNull(authorizationReadClient, "authorizationReadClient"); + this.worldInventoryReadClient = + Objects.requireNonNull(worldInventoryReadClient, "worldInventoryReadClient"); + } + + /** + * Replays an exact retained receipt or prepares a fresh owner-local retention attempt. This + * method does not publish, activate, create nonempty templates, or settle Account participation. + */ + public EntityEmptySelectedSourceIntakeReceipt retain( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding originalBinding, + WorldSelectedDraftPublicationFreezeEvidence exactFreeze) { + requireConfiguredNamespace(targetNamespace); + requireAuthenticatedGameDesignCaller(targetNamespace); + requireNoAmbientOwnerSql(); + requireRequest(targetNamespace, originalBinding, exactFreeze); + String requestDigest = + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + targetNamespace, originalBinding, exactFreeze); + + var retained = repository.read(targetNamespace, originalBinding.intakeRequestId()); + if (retained.isPresent()) { + EntityEmptySelectedSourceIntakeReceipt receipt = retained.orElseThrow(); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + SelectedOwnerIntakeAuthorizationReadEvidence.Request authorizationRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var authorizationEvidence = authorizationReadClient.read(authorizationRequest); + if (authorizationEvidence == null + || !authorizationRequest.equals(authorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the exact selected-owner read request"); + } + + SelectedOwnerWorldInventoryReadEvidence.Request worldRequest = + SelectedOwnerWorldInventoryReadEvidence.Request.create( + targetNamespace, originalBinding, exactFreeze); + var worldEvidence = worldInventoryReadClient.read(worldRequest); + if (worldEvidence == null || !worldRequest.equals(worldEvidence.request())) { + throw new IllegalStateException("World did not echo the exact selected-owner read request"); + } + + // Typed inputs bind bytes only. The authenticated clients supply producer identity; Account's + // distinct source participation remains protected until an exact owner terminal is settled. + SelectedOwnerEmptySourceInputs inputs = + new SelectedOwnerEmptySourceInputs(originalBinding, worldEvidence); + requireEmptyWorldEntityClosure(worldEvidence.inventory().publicEvidence()); + + // A second HELD sample narrows the gap after the remote World read. It does not extend or prove + // continuous Account protection through Entity's local commit. + SelectedOwnerIntakeAuthorizationReadEvidence.Request finalAuthorizationRequest = + SelectedOwnerIntakeAuthorizationReadEvidence.Request.create( + targetNamespace, originalBinding); + var finalAuthorizationEvidence = authorizationReadClient.read(finalAuthorizationRequest); + if (finalAuthorizationEvidence == null + || !finalAuthorizationRequest.equals(finalAuthorizationEvidence.request())) { + throw new IllegalStateException("Account did not echo the final selected-owner read request"); + } + + EntityEmptySelectedSourceIntakeReceipt receipt = repository.retainFresh(inputs, requestDigest); + receipt.requireSameRequest(targetNamespace, originalBinding, exactFreeze); + return receipt; + } + + private void requireConfiguredNamespace(String targetNamespace) { + if (!configuredNamespace.equals(targetNamespace)) { + throw new SecurityException( + "Selected Entity intake namespace differs from the configured Entity owner namespace"); + } + } + + private static void requireAuthenticatedGameDesignCaller(String targetNamespace) { + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw new SecurityException("Authenticated same-namespace Game Design peer is required"); + } + if (AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null + || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null + || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null + || SessionContext.hasAuthenticatedCallerContext() + || !GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(peer.namespace()) + || !("spiffe://firemud/ns/" + targetNamespace + "/sa/game-design-service") + .equals(peer.uri())) { + throw new SecurityException( + "Selected Entity intake requires the exact same-namespace Game Design peer"); + } + } + + private static void requireRequest( + String targetNamespace, + SelectedOwnerIntakeAuthorizationBinding binding, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + Objects.requireNonNull(binding, "original Account authorization binding is required"); + Objects.requireNonNull(freezeEvidence, "exact World freeze is required"); + if (!GrpcPeerIdentity.isValidNamespace(targetNamespace) + || !targetNamespace.equals(binding.targetNamespace()) + || binding.owner() != Owner.ENTITY_MANAGEMENT + || !binding.schema().equals("account-entity-intake-authorization/v1") + || !binding.purpose().equals("ENTITY_INTAKE_RETENTION")) { + throw new IllegalArgumentException( + "Fresh Entity intake requires its exact finalized Account owner binding"); + } + var freeze = freezeEvidence.request(); + if (!targetNamespace.equals(freeze.targetNamespace()) + || !binding.tenantId().equals(freeze.canonicalTenantId()) + || !binding.versionId().equals(freeze.canonicalVersionId()) + || !binding + .selected() + .equals(freeze.accountBinding().input().selection().selectedCommit())) { + throw new IllegalArgumentException( + "Entity owner binding differs from the exact selected World freeze"); + } + } + + private static void requireEmptyWorldEntityClosure( + WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence inventory) { + if (!WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA.equals( + inventory.schema()) + || inventory.schemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION + || !WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL.equals( + inventory.sourceModel().modelId()) + || inventory.sourceModel().graphSchemaVersion() + != WorldSelectedPublicationArtifactInventoryEvidence + .INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION + || inventory.sourceModel().inboundSourceClosure() == null) { + throw new IllegalArgumentException( + "Entity empty-source intake requires the complete supported World closure"); + } + var sourceModel = inventory.sourceModel(); + int spawnCount = + sourceModel.familyCounts().stream() + .filter(family -> "WORLD_ENTITY_SPAWN_BINDING".equals(family.family())) + .mapToInt(WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount::rowCount) + .findFirst() + .orElseThrow( + () -> new IllegalArgumentException("World population family state is unavailable")); + if (spawnCount != 0 + || sourceModel.spawnBindingCount() != 0 + || !sourceModel.spawnBindingInputs().isEmpty()) { + throw new IllegalArgumentException( + "Entity empty-source intake cannot retain World population bindings"); + } + var closure = sourceModel.inboundSourceClosure(); + if (closure.schemaVersion() != 1 || closure.familyCounts().size() != 7) { + throw new IllegalArgumentException("World inbound closure family vector is incomplete"); + } + for (var family : closure.familyCounts()) { + if (family.count() != 0) { + throw new IllegalArgumentException( + "Entity empty-source intake cannot retain World item, loot, behavior, or hook references"); + } + } + } + + private static void requireNoAmbientOwnerSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException( + "Account and World evidence reads must run outside Entity SQL"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java new file mode 100644 index 0000000000..6751a4653f --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeTerminalReadService.java @@ -0,0 +1,92 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import java.util.Arrays; +import java.util.Objects; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import org.jooq.exception.DataAccessException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Account-only lookup over Entity's immutable selected-source terminal receipt. */ +public final class EntityEmptySelectedSourceIntakeTerminalReadService { + private final EntityEmptySelectedSourceIntakeRepository repository; + private final String namespace; + + public EntityEmptySelectedSourceIntakeTerminalReadService( + EntityEmptySelectedSourceIntakeRepository repository, String namespace) { + this.repository = Objects.requireNonNull(repository, "repository"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Canonical namespace required"); + } + this.namespace = namespace; + } + + /** Called by the transport before decoding caller-carried evidence or touching owner storage. */ + void requireAuthenticatedAccountCaller() { + if (SessionContext.hasAuthenticatedCallerContext()) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !"account-service".equals(peer.service()) + || !("spiffe://firemud/ns/" + namespace + "/sa/account-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } + + /** Reads only the exact original COMMITTED_EMPTY receipt; absence is not terminal abort. */ + public EntitySelectedSourceIntakeTerminalReadEvidence read( + EntitySelectedSourceIntakeTerminalReadEvidence.Request request) { + requireAuthenticatedAccountCaller(); + Objects.requireNonNull(request, "terminal-read request is required"); + if (!namespace.equals(request.targetNamespace())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw Status.FAILED_PRECONDITION.asRuntimeException(); + } + + final net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt + receipt; + try { + receipt = + repository + .read(namespace, request.binding().intakeRequestId()) + .orElseThrow(() -> Status.NOT_FOUND.asRuntimeException()); + } catch (StatusRuntimeException denied) { + throw denied; + } catch (EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException corrupt) { + throw Status.DATA_LOSS + .withDescription("Entity committed receipt is invalid") + .asRuntimeException(); + } catch (DataAccessException | org.springframework.dao.DataAccessException unavailable) { + throw Status.UNAVAILABLE + .withDescription("Entity terminal receipt storage is unavailable") + .asRuntimeException(); + } catch (IllegalArgumentException | IllegalStateException corrupt) { + throw Status.DATA_LOSS + .withDescription("Entity committed receipt is invalid") + .asRuntimeException(); + } + + if (!Arrays.equals(request.binding().canonicalBytes(), receipt.authorizationBindingBytes())) { + throw Status.ALREADY_EXISTS + .withDescription("Entity receipt differs from the complete original authorization") + .asRuntimeException(); + } + try { + return new EntitySelectedSourceIntakeTerminalReadEvidence(request, receipt); + } catch (IllegalArgumentException corrupt) { + throw Status.DATA_LOSS + .withDescription("Entity receipt differs from its original order") + .asRuntimeException(); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java new file mode 100644 index 0000000000..22a8e3b96b --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceService.java @@ -0,0 +1,216 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.util.List; +import java.util.Objects; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.AuthoredWorldReleaseAttestationEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** + * Unregistered Entity consumer for Game Design's independently authenticated authored-core read. + */ +public final class EntityRetainedAuthoredActorCoreSourceService { + private static final String ENTITY_RELEASE_SCHEMA = + "v" + AuthoredWorldReleaseAttestationEvidence.SELECTED_FULL_SCHEMA_VERSION; + + private final String configuredNamespace; + private final AuthoredInitialActorCoreReadClient gameDesignClient; + private final EntityEmptySelectedSourceIntakeRepository repository; + + public EntityRetainedAuthoredActorCoreSourceService( + String configuredNamespace, + AuthoredInitialActorCoreReadClient gameDesignClient, + EntityEmptySelectedSourceIntakeRepository repository) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Entity namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.gameDesignClient = Objects.requireNonNull(gameDesignClient, "gameDesignClient"); + this.repository = Objects.requireNonNull(repository, "repository"); + } + + /** + * Obtains the exact already-pinned read directly from Game Design, then corroborates it against + * Entity's retained selected source and the immutable Entity participant in that selected + * release. The returned object is the unchanged public result from the authenticated client. + */ + public AuthoredInitialActorCoreReadEvidence.ReadResult read( + AuthoredInitialActorCoreReadEvidence.ReadRequest request) { + Objects.requireNonNull(request, "authored-core read request is required"); + requireNoAmbientOwnerSql(); + + Request associationRequest = request.associationRequest(); + if (!configuredNamespace.equals(associationRequest.targetNamespace()) + || !(associationRequest.selection() instanceof ExactReplay)) { + throw denied("Exact same-namespace pinned Game Design read is required"); + } + + // This is a direct workload-authenticated read. No Entity owner transaction may surround it. + AuthoredInitialActorCoreReadEvidence.ReadResult publicResult = gameDesignClient.read(request); + if (publicResult == null || !associationRequest.equals(publicResult.request())) { + throw denied("Game Design authored-core read differs from the exact original request"); + } + Result associationRead = publicResult.associationRead(); + if (associationRead == null || !associationRequest.equals(associationRead.request())) { + throw denied("Game Design association read differs from the exact original request"); + } + + Association association = associationRead.association(); + PublishedReleaseBundle release = associationRead.releaseBundle(); + if (association == null || release == null) { + throw denied("Game Design selected association or release is unavailable"); + } + if (release.getVersionId() <= 0L) { + throw denied("Selected release has no canonical Version row"); + } + + // COMMITTED_EMPTY is only Entity's pre-publication source receipt. The public Game Design read + // remains the independent authored-core evidence; this receipt only correlates its selection. + // The repository resolves every association in a read-only repeatable-read snapshot. + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.readPublicationScope( + configuredNamespace, association.canonicalTenantId(), release.getVersionId()); + requireExactReleaseAndSource(associationRequest, association, release, receipt); + requireExactProjections(publicResult.projections(), association, receipt); + return publicResult; + } + + private void requireExactReleaseAndSource( + Request request, + Association association, + PublishedReleaseBundle release, + EntityEmptySelectedSourceIntakeReceipt receipt) { + if (receipt == null) { + throw denied("Entity retained selected-source receipt is unavailable"); + } + ExactReplay replay = (ExactReplay) request.selection(); + var authorization = receipt.authorizationBinding(); + var selected = authorization.selected(); + var target = selected.target(); + var worldRead = receipt.inputs().worldInventoryReadEvidence(); + var worldInventory = worldRead.inventory(); + var worldOwner = worldInventory.publicEvidence().ownerScope(); + var worldReceipt = association.worldReceipt(); + var worldSelection = + worldRead.request().freezeEvidence().request().accountBinding().input().selection(); + + if (!configuredNamespace.equals(receipt.targetNamespace()) + || !configuredNamespace.equals(authorization.targetNamespace()) + || authorization.owner() != Owner.ENTITY_MANAGEMENT + || !association.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !association.canonicalVersionId().equals(receipt.canonicalVersionId()) + || !association.selectedCommitId().equals(receipt.selectedCommitId()) + || !replay.canonicalVersionId().equals(receipt.canonicalVersionId()) + || !replay.selectedCommitId().equals(receipt.selectedCommitId()) + || !replay.publishWorkflowId().equals(association.publishWorkflowId()) + || !replay.associationDigest().equals(association.associationDigest()) + || !receipt.canonicalTenantId().equals(target.canonicalTenantId()) + || !receipt.canonicalVersionId().equals(target.canonicalVersionId()) + || target.gameDesignVersionRowId() != release.getVersionId() + || !selected.commitId().equals(receipt.selectedCommitId()) + || !configuredNamespace.equals(association.targetNamespace()) + || !association.intakeRequestId().equals(worldOwner.intakeRequestId()) + || !association.worldOperationId().equals(worldOwner.intakeOperationId()) + || !association.publicationSelectionDigest().equals(worldSelection.digest()) + || !worldReceipt.targetNamespace().equals(worldOwner.targetNamespace()) + || !worldReceipt.canonicalTenantId().equals(worldOwner.canonicalTenantId()) + || !worldReceipt.intakeRequestId().equals(worldOwner.intakeRequestId()) + || !worldReceipt.operationId().equals(worldOwner.intakeOperationId()) + || !worldReceipt.sourceOperationId().equals(worldOwner.sourceOperationId()) + || !worldReceipt.sourceEvidenceDigest().equals(worldOwner.sourceEvidenceDigest()) + || !worldReceipt.receiptDigest().equals(worldOwner.intakeReceiptDigest()) + || !release.getCanonicalTenantId().equals(receipt.canonicalTenantId().toString()) + || !release.getCanonicalVersionId().equals(receipt.canonicalVersionId().toString()) + || release.getVersionId() != target.gameDesignVersionRowId() + || !release.getPublishWorkflowId().equals(association.publishWorkflowId()) + || !ENTITY_RELEASE_SCHEMA.equals(release.getAttestationSchemaVersion()) + || !association.sourceOperationId().equals(worldOwner.sourceOperationId()) + || !association.sourceEvidenceDigest().equals(worldOwner.sourceEvidenceDigest()) + || !receipt.canonicalTenantId().equals(worldOwner.canonicalTenantId()) + || !receipt.canonicalVersionId().equals(worldOwner.canonicalVersionId()) + || !receipt + .selectedCommitId() + .toString() + .equals( + receipt + .inputs() + .worldInventoryReadEvidence() + .request() + .freezeEvidence() + .acknowledgement() + .appliedCommitId()) + || !receipt.operationId().equals(authorization.operationId()) + || !receipt.fenceId().equals(authorization.fenceId()) + || !receipt.intakeRequestId().equals(authorization.intakeRequestId())) { + throw denied("Entity receipt differs from the exact selected source operation or release"); + } + + String expectedEntityDigest = + EntitySelectedEmptyPublicationDigestService.contentDigest( + receipt.canonicalTenantId(), + target.gameDesignVersionRowId(), + receipt.canonicalVersionId(), + receipt.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson()); + List matchingEntityParticipants = + release.getParticipantDigestsList().stream() + .filter(value -> "ENTITY_MANAGEMENT".equals(value.getParticipantKey())) + .toList(); + if (matchingEntityParticipants.size() != 1) { + throw denied("Selected release has no unique immutable Entity participant digest"); + } + ParticipantDigest entityParticipant = matchingEntityParticipants.getFirst(); + if (!Long.toString(target.gameDesignVersionRowId()).equals(entityParticipant.getScopeValue()) + || !receipt.selectedCommitId().toString().equals(entityParticipant.getAppliedCommitId()) + || entityParticipant.getDigestSchemaVersion() + != EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION + || !expectedEntityDigest.equals(entityParticipant.getContentDigest()) + || entityParticipant.hasAbilitySchemaDigest()) { + throw denied("Selected release Entity digest differs from the retained Entity receipt"); + } + } + + private static void requireExactProjections( + List projections, + Association association, + EntityEmptySelectedSourceIntakeReceipt receipt) { + if (projections == null) { + throw denied("Game Design authored-core projection list is unavailable"); + } + String selectedCommitDigest = receipt.authorizationBinding().selected().digest(); + for (AuthoredInitialActorCoreProjection projection : projections) { + if (projection == null + || !projection.canonicalTenantId().equals(receipt.canonicalTenantId()) + || !projection.canonicalVersionId().equals(receipt.canonicalVersionId()) + || !projection.selectedCommitId().equals(receipt.selectedCommitId()) + || !projection.selectedCommitDigest().equals(selectedCommitDigest) + || !projection.worldSourceOperationId().equals(association.sourceOperationId()) + || !projection.worldSourceEvidenceDigest().equals(association.sourceEvidenceDigest()) + || !projection.worldSlug().equals(association.worldSlug()) + || !projection.publicationWorkflowId().equals(association.publishWorkflowId())) { + throw denied("Authored-core projection differs from Entity's exact retained source"); + } + } + } + + private static void requireNoAmbientOwnerSql() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw denied("Entity authored-core consumption requires no ambient owner SQL"); + } + } + + private static IllegalStateException denied(String message) { + return new IllegalStateException(message); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java new file mode 100644 index 0000000000..48545091c9 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiver.java @@ -0,0 +1,103 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.MeterRegistry; +import java.util.Objects; +import net.firedevops.firemud.common.grpc.GrpcAppErrors; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.AdminAuthorizationException; +import net.firedevops.firemud.common.security.PublicationReadGuard; +import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; +import net.firedevops.firemud.entitymanagement.v1.EntityManagementServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestResponse; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Unregistered native receiver for the selected-empty Entity publication digest path. */ +public final class EntitySelectedEmptyPublicationDigestGrpcReceiver + extends EntityManagementServiceGrpc.EntityManagementServiceImplBase { + private static final Logger LOGGER = + LoggerFactory.getLogger(EntitySelectedEmptyPublicationDigestGrpcReceiver.class); + + private final EntitySelectedEmptyPublicationDigestService digestService; + private final PublicationReadGuard publicationReadGuard; + private final MeterRegistry meterRegistry; + + public EntitySelectedEmptyPublicationDigestGrpcReceiver( + EntitySelectedEmptyPublicationDigestService digestService, + String configuredNamespace, + MeterRegistry meterRegistry) { + this.digestService = Objects.requireNonNull(digestService, "digestService"); + this.publicationReadGuard = PublicationReadGuard.configured(configuredNamespace); + this.meterRegistry = Objects.requireNonNull(meterRegistry, "meterRegistry"); + } + + @Override + public void getDraftDesignDigest( + GetDraftDesignDigestRequest request, + StreamObserver responseObserver) { + try { + requirePublicationRead(); + if (request.getScopeCase() != GetDraftDesignDigestRequest.ScopeCase.VERSION_ID) { + responseObserver.onNext( + error( + "UNSUPPORTED_SCOPE", + "Entity selected-empty publication supports version_id scope only")); + responseObserver.onCompleted(); + return; + } + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.forScope( + PublicationDigestRequestBinding.ScopeKind.FULL_VERSION, + request.getTenantId(), + request.getVersionId(), + request.getBaseVersionId(), + request.getScriptPatchVersion(), + request.getPublishRequestId()); + binding.validateSupplied(request.getDerivedWorkflowIdentity(), request.getRequestDigest()); + + EntityDraftDesignDigest digest = digestService.getDraftDesignDigest(binding); + binding.requireOwnerScope(digest.tenantId(), digest.scopeValue()); + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setAppliedCommitId(digest.appliedCommitId()) + .setContentDigest(digest.contentDigest()) + .setDigestSchemaVersion(digest.digestSchemaVersion()) + .build()); + responseObserver.onCompleted(); + } catch (AdminAuthorizationException denied) { + responseObserver.onNext(error("PERMISSION_DENIED", denied.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalArgumentException invalid) { + responseObserver.onNext(error("INVALID_ARGUMENT", invalid.getMessage())); + responseObserver.onCompleted(); + } catch (IllegalStateException unavailable) { + responseObserver.onNext(error("FAILED_PRECONDITION", unavailable.getMessage())); + responseObserver.onCompleted(); + } catch (RuntimeException failure) { + responseObserver.onNext( + GetDraftDesignDigestResponse.newBuilder() + .setError( + GrpcAppErrors.internal(meterRegistry, LOGGER, "GetDraftDesignDigest", failure)) + .build()); + responseObserver.onCompleted(); + } + } + + private void requirePublicationRead() { + if (publicationReadGuard == null) { + throw new AdminAuthorizationException("Publication read authorization is not configured"); + } + publicationReadGuard.requirePublicationRead( + PublicationReadGuard.ENTITY_MANAGEMENT_DIGEST_METHOD); + } + + private GetDraftDesignDigestResponse error(String code, String message) { + return GetDraftDesignDigestResponse.newBuilder() + .setError(GrpcAppErrors.error(meterRegistry, LOGGER, "GetDraftDesignDigest", code, message)) + .build(); + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java new file mode 100644 index 0000000000..e4d1e9e78e --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestService.java @@ -0,0 +1,117 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import java.util.Objects; +import java.util.UUID; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedEmptyPublicationDigestSupport; +import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; + +/** Unregistered selected-empty full-version digest reader over Entity's retained owner receipt. */ +public final class EntitySelectedEmptyPublicationDigestService { + public static final int DIGEST_SCHEMA_VERSION = 3; + private static final String DIGEST_DOMAIN = "entity-selected-empty-publication-digest/v1"; + + private final String configuredNamespace; + private final EntityEmptySelectedSourceIntakeRepository repository; + + public EntitySelectedEmptyPublicationDigestService( + String configuredNamespace, EntityEmptySelectedSourceIntakeRepository repository) { + if (!GrpcPeerIdentity.isValidNamespace(configuredNamespace)) { + throw new IllegalArgumentException("Configured Entity namespace is required"); + } + this.configuredNamespace = configuredNamespace; + this.repository = Objects.requireNonNull(repository, "repository"); + } + + /** Returns a selected-empty digest only for one exact canonical tenant and GD Version row. */ + public EntityDraftDesignDigest getDraftDesignDigest( + PublicationDigestRequestBinding publicationRequest) { + Objects.requireNonNull(publicationRequest, "publication request is required"); + if (publicationRequest.scopeKind() != PublicationDigestRequestBinding.ScopeKind.FULL_VERSION) { + throw new IllegalArgumentException( + "Entity selected-empty publication supports full versions only"); + } + UUID canonicalTenantId = + SelectedEmptyPublicationDigestSupport.canonicalUuid( + publicationRequest.tenantId(), "tenantId"); + long gameDesignVersionRowId = + SelectedEmptyPublicationDigestSupport.canonicalPositiveLong( + publicationRequest.versionId(), "versionId"); + + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.readPublicationScope( + configuredNamespace, canonicalTenantId, gameDesignVersionRowId); + var target = receipt.authorizationBinding().selected().target(); + if (!configuredNamespace.equals(receipt.targetNamespace()) + || !canonicalTenantId.equals(receipt.canonicalTenantId()) + || !canonicalTenantId.equals(target.canonicalTenantId()) + || target.gameDesignVersionRowId() != gameDesignVersionRowId + || !receipt.canonicalVersionId().equals(target.canonicalVersionId())) { + throw new IllegalStateException( + "Entity selected-empty receipt differs from publication scope"); + } + + var inputs = receipt.inputs(); + SelectedEmptyPublicationDigestSupport.requireOriginalPublicationRequest( + publicationRequest, + canonicalTenantId, + gameDesignVersionRowId, + receipt.canonicalVersionId(), + receipt.selectedCommitId(), + inputs.worldInventoryReadEvidence().request().freezeEvidence(), + "Entity"); + if (inputs.authorizationBinding().owner() != Owner.ENTITY_MANAGEMENT) { + throw new IllegalStateException("Entity receipt contains a different owner declaration"); + } + requireEmptyReceipt(receipt); + String inventoryJson = + inputs.ownerSourceInventoryDeclaration().entityInventory().canonicalJson(); + String contentDigest = + contentDigest( + canonicalTenantId, gameDesignVersionRowId, receipt.canonicalVersionId(), inventoryJson); + return new EntityDraftDesignDigest( + publicationRequest.tenantId(), + publicationRequest.versionId(), + receipt.selectedCommitId().toString(), + contentDigest, + DIGEST_SCHEMA_VERSION); + } + + static String contentDigest( + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + if (gameDesignVersionRowId <= 0L) { + throw new IllegalArgumentException("Game Design Version row must be positive"); + } + Objects.requireNonNull(canonicalTenantId, "canonicalTenantId"); + Objects.requireNonNull(canonicalVersionId, "canonicalVersionId"); + Objects.requireNonNull(canonicalInventoryJson, "canonicalInventoryJson"); + return SelectedEmptyPublicationDigestSupport.framedSha256( + DIGEST_DOMAIN, + DIGEST_SCHEMA_VERSION, + canonicalTenantId.toString(), + Long.toString(gameDesignVersionRowId), + canonicalVersionId.toString(), + canonicalInventoryJson); + } + + private static void requireEmptyReceipt(EntityEmptySelectedSourceIntakeReceipt receipt) { + if (receipt.familyStates().size() != 23 + || receipt.familyStates().stream() + .anyMatch( + state -> + state.state() != EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY + || state.rowCount() != 0L + || state.unqualifiedRowCount() != 0L + || state.retainedRowCount() != 0L + || state.selectedScopeRowCount() != 0L + || state.referenceCount() != 0L)) { + throw new IllegalStateException("Entity selected-empty receipt is incomplete or nonempty"); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java new file mode 100644 index 0000000000..662c100e62 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcService.java @@ -0,0 +1,108 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeCommandServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Unregistered Game Design command boundary for retaining exact selected Entity inputs. */ +public final class EntitySelectedSourceIntakeCommandGrpcService + extends EntitySelectedSourceIntakeCommandServiceGrpc + .EntitySelectedSourceIntakeCommandServiceImplBase { + private final EntityEmptySelectedSourceIntakeService owner; + private final String namespace; + + public EntitySelectedSourceIntakeCommandGrpcService( + EntityEmptySelectedSourceIntakeService owner, String namespace) { + this.owner = Objects.requireNonNull(owner, "selected-source intake owner is required"); + if (!GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("configured namespace is invalid"); + } + this.namespace = namespace; + } + + @Override + public void retainSelectedEntitySource( + RetainSelectedEntitySourceRequest request, + StreamObserver observer) { + try { + requireAuthenticatedGameDesignCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + if (!namespace.equals(request.getTargetNamespace())) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + return; + } + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + return; + } + + final EntitySelectedSourceIntakeCommandEvidence.Request decoded; + try { + decoded = EntitySelectedSourceIntakeCommandGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + + try { + var receipt = + owner.retain( + decoded.targetNamespace(), + decoded.originalAuthorizationBinding(), + decoded.freezeEvidence()); + var evidence = new EntitySelectedSourceIntakeCommandEvidence(decoded, receipt); + observer.onNext(EntitySelectedSourceIntakeCommandGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(Status.fromCode(denied.getStatus().getCode()).asRuntimeException()); + } catch (SecurityException denied) { + observer.onError(Status.PERMISSION_DENIED.asRuntimeException()); + } catch (EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException corrupt) { + observer.onError(Status.DATA_LOSS.asRuntimeException()); + } catch (EntityEmptySelectedSourceIntakeRepository.IntakeConflictException conflict) { + observer.onError(Status.ALREADY_EXISTS.asRuntimeException()); + } catch (org.jooq.exception.DataAccessException + | org.springframework.dao.DataAccessException unavailable) { + observer.onError(Status.UNAVAILABLE.asRuntimeException()); + } catch (IllegalArgumentException | IllegalStateException unavailable) { + observer.onError(Status.FAILED_PRECONDITION.asRuntimeException()); + } catch (RuntimeException failure) { + observer.onError(Status.INTERNAL.asRuntimeException()); + } + } + + /** Authenticate the exact same-namespace workload and reject user context before decoding. */ + private void requireAuthenticatedGameDesignCaller() { + if (SessionContext.hasAuthenticatedCallerContext() + || AccountOriginalDraftOrderCredentials.CONTEXT_KEY.get() != null + || SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY.get() != null + || AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY.get() != null) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + var peer = GrpcPeerIdentity.current(); + if (peer == null) { + throw Status.UNAUTHENTICATED.asRuntimeException(); + } + if (!namespace.equals(peer.namespace()) + || !"game-design-service".equals(peer.service()) + || !("spiffe://firemud/ns/" + namespace + "/sa/game-design-service").equals(peer.uri())) { + throw Status.PERMISSION_DENIED.asRuntimeException(); + } + } +} diff --git a/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java new file mode 100644 index 0000000000..1b58c29642 --- /dev/null +++ b/services/entity-management-service/src/main/java/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadGrpcService.java @@ -0,0 +1,53 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Objects; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.entitymanagement.v1.EntitySelectedSourceIntakeTerminalReadServiceGrpc; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; + +/** No automatic registration; authenticate Account before parsing its claimed original binding. */ +public final class EntitySelectedSourceIntakeTerminalReadGrpcService + extends EntitySelectedSourceIntakeTerminalReadServiceGrpc + .EntitySelectedSourceIntakeTerminalReadServiceImplBase { + private final EntityEmptySelectedSourceIntakeTerminalReadService owner; + + public EntitySelectedSourceIntakeTerminalReadGrpcService( + EntityEmptySelectedSourceIntakeTerminalReadService owner) { + this.owner = Objects.requireNonNull(owner, "terminal-read owner is required"); + } + + @Override + public void readSelectedSourceIntakeTerminal( + ReadSelectedSourceIntakeTerminalRequest request, + StreamObserver observer) { + try { + owner.requireAuthenticatedAccountCaller(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + return; + } + + final net.firedevops.firemud.common.entity.sourceintake + .EntitySelectedSourceIntakeTerminalReadEvidence.Request + decoded; + try { + decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromRequest(request); + } catch (RuntimeException malformed) { + observer.onError(Status.INVALID_ARGUMENT.asRuntimeException()); + return; + } + try { + var evidence = owner.read(decoded); + observer.onNext(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toResponse(evidence)); + observer.onCompleted(); + } catch (StatusRuntimeException denied) { + observer.onError(denied); + } catch (RuntimeException corrupt) { + observer.onError(Status.DATA_LOSS.asRuntimeException()); + } + } +} diff --git a/services/entity-management-service/src/main/resources/db/migration/V1011__fresh_selected_empty_source_catalogue.sql b/services/entity-management-service/src/main/resources/db/migration/V1011__fresh_selected_empty_source_catalogue.sql new file mode 100644 index 0000000000..fa5cce936a --- /dev/null +++ b/services/entity-management-service/src/main/resources/db/migration/V1011__fresh_selected_empty_source_catalogue.sql @@ -0,0 +1,1141 @@ +-- Fresh-only selected-source retention. Existing Entity rows are never adopted as a selected +-- source; they are reserved as occupied numeric keys and deny a fresh empty-source census. +CREATE TABLE entity_empty_source_numeric_key_reservation ( + key_kind VARCHAR(16) NOT NULL, + numeric_key BIGINT NOT NULL, + claim_kind VARCHAR(32) NOT NULL, + CONSTRAINT pk_entity_empty_source_numeric_key_reservation + PRIMARY KEY (key_kind, numeric_key), + CONSTRAINT uq_entity_empty_source_numeric_key_claim + UNIQUE (numeric_key, key_kind, claim_kind), + CONSTRAINT ck_entity_empty_source_numeric_key_kind + CHECK (key_kind IN ('TENANT', 'VERSION')), + CONSTRAINT ck_entity_empty_source_numeric_key_positive + CHECK (numeric_key > 0), + CONSTRAINT ck_entity_empty_source_numeric_key_claim + CHECK (claim_kind IN ('LEGACY_NUMERIC', 'CANONICAL_EMPTY_SOURCE')) +); + +CREATE TABLE entity_empty_selected_source_association ( + target_namespace VARCHAR(63) NOT NULL, + genesis_id UUID NOT NULL, + operation_id UUID NOT NULL, + fence_id UUID NOT NULL, + intake_request_id UUID NOT NULL, + canonical_tenant_id UUID NOT NULL, + canonical_version_id UUID NOT NULL, + selected_commit_id UUID NOT NULL, + source_revision_id UUID NOT NULL, + source_revision_order VARCHAR(32) NOT NULL, + local_tenant_key BIGINT NOT NULL, + local_tenant_key_kind VARCHAR(16) NOT NULL DEFAULT 'TENANT', + local_tenant_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + local_version_key BIGINT NOT NULL, + local_version_key_kind VARCHAR(16) NOT NULL DEFAULT 'VERSION', + local_version_key_claim_kind VARCHAR(32) NOT NULL DEFAULT 'CANONICAL_EMPTY_SOURCE', + request_digest VARCHAR(71) NOT NULL, + schema_digest VARCHAR(71) NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + world_read_request_id UUID NOT NULL, + world_read_request_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + associated_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_selected_source_association + PRIMARY KEY (target_namespace, canonical_tenant_id, canonical_version_id), + CONSTRAINT uq_entity_empty_selected_source_request + UNIQUE (target_namespace, intake_request_id), + CONSTRAINT uq_entity_empty_selected_source_operation + UNIQUE (target_namespace, operation_id), + CONSTRAINT uq_entity_empty_selected_source_genesis + UNIQUE (genesis_id), + CONSTRAINT uq_entity_empty_selected_source_local_tenant + UNIQUE (local_tenant_key), + CONSTRAINT uq_entity_empty_selected_source_local_version + UNIQUE (local_version_key), + CONSTRAINT ck_entity_empty_selected_source_namespace + CHECK (target_namespace ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$'), + CONSTRAINT ck_entity_empty_selected_source_ids_nonzero + CHECK ( + genesis_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND operation_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND fence_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND intake_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_tenant_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND canonical_version_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND selected_commit_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND source_revision_id <> '00000000-0000-0000-0000-000000000000'::UUID + AND world_read_request_id <> '00000000-0000-0000-0000-000000000000'::UUID + ), + CONSTRAINT ck_entity_empty_selected_source_local_keys + CHECK ( + local_tenant_key > 0 + AND local_version_key > 0 + AND local_tenant_key <> local_version_key + AND local_tenant_key_kind = 'TENANT' + AND local_tenant_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + AND local_version_key_kind = 'VERSION' + AND local_version_key_claim_kind = 'CANONICAL_EMPTY_SOURCE' + ), + CONSTRAINT ck_entity_empty_selected_source_revision_order + CHECK (source_revision_order ~ '^(0|[1-9][0-9]*)$'), + CONSTRAINT ck_entity_empty_selected_source_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND schema_digest ~ '^sha256:[0-9a-f]{64}$' + AND authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_read_request_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + ), + CONSTRAINT fk_entity_empty_selected_source_tenant_key + FOREIGN KEY (local_tenant_key, local_tenant_key_kind, local_tenant_key_claim_kind) + REFERENCES entity_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind), + CONSTRAINT fk_entity_empty_selected_source_version_key + FOREIGN KEY (local_version_key, local_version_key_kind, local_version_key_claim_kind) + REFERENCES entity_empty_source_numeric_key_reservation + (numeric_key, key_kind, claim_kind) +); + +-- These fourteen owner-local providers deliberately support only an explicit EMPTY state. +-- Each has its own persisted typed table; the receipt family-state ledger is not a provider. +CREATE TABLE entity_empty_source_other_actor_template_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_other_actor_template_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_other_actor_template_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_other_actor_template_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_capabilities ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_capabilities PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_capabilities_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_capabilities_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_capabilities_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_capabilities_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_capabilities_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_attachment_rules ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_attachment_rules PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_attachment_rules_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_attachment_rules_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_compatibility_rules ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_compatibility_rules PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_compatibility_rules_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_compatibility_rules_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_equipment_occupancy_rules ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_equipment_occupancy_rules PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_equipment_occupancy_rules_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_equipment_occupancy_rules_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_actor_body_layout_assignments ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_actor_body_layout_assignments PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_actor_body_layout_assignments_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_actor_body_layout_assignments_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_loot_table_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_loot_table_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_loot_table_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_loot_table_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_loot_table_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_loot_table_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_loot_table_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_loot_item_mappings ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_loot_item_mappings PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_loot_item_mappings_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_loot_item_mappings_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_loot_item_mappings_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_loot_item_mappings_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_loot_item_mappings_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_inbound_loot_bindings ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_inbound_loot_bindings PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_inbound_loot_bindings_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_inbound_loot_bindings_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_balance_curve_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_balance_curve_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_balance_curve_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_balance_curve_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_balance_curve_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_balance_curve_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_balance_curve_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_balance_curve_attachments ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_balance_curve_attachments PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_balance_curve_attachments_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_balance_curve_attachments_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_archetype_roots ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_archetype_roots PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_archetype_roots_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_archetype_roots_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_archetype_roots_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_archetype_roots_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_archetype_roots_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_archetype_constraints ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_archetype_constraints PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_archetype_constraints_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_archetype_constraints_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_archetype_constraints_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_archetype_constraints_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_archetype_constraints_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); + +CREATE TABLE entity_empty_source_archetype_assignments ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + provider_schema_version SMALLINT NOT NULL, + owner_state VARCHAR(16) NOT NULL, + row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + authorization_binding_digest VARCHAR(71) NOT NULL, + selected_source_digest VARCHAR(71) NOT NULL, + source_revision_binding_digest VARCHAR(71) NOT NULL, + world_closure_digest VARCHAR(71) NOT NULL, + provider_state_digest VARCHAR(71) NOT NULL, + observed_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_source_archetype_assignments PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_source_archetype_assignments_association FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_source_archetype_assignments_schema CHECK (provider_schema_version = 1), + CONSTRAINT ck_entity_empty_source_archetype_assignments_state CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_source_archetype_assignments_counts CHECK (row_count = 0 AND reference_count = 0), + CONSTRAINT ck_entity_empty_source_archetype_assignments_digests CHECK ( + authorization_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND selected_source_digest ~ '^sha256:[0-9a-f]{64}$' + AND source_revision_binding_digest ~ '^sha256:[0-9a-f]{64}$' + AND world_closure_digest ~ '^sha256:[0-9a-f]{64}$' + AND provider_state_digest ~ '^sha256:[0-9a-f]{64}$' + ) +); +CREATE TABLE entity_empty_selected_source_family_state ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + family_name VARCHAR(64) NOT NULL, + owner_state VARCHAR(16) NOT NULL, + evidence_kind VARCHAR(32) NOT NULL, + row_count BIGINT NOT NULL, + unqualified_row_count BIGINT NOT NULL, + retained_row_count BIGINT NOT NULL, + selected_scope_row_count BIGINT NOT NULL, + reference_count BIGINT NOT NULL, + CONSTRAINT pk_entity_empty_selected_source_family_state + PRIMARY KEY (target_namespace, intake_request_id, family_name), + CONSTRAINT fk_entity_empty_selected_source_family_association + FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_selected_source_family_name + CHECK (family_name IN ( + 'ACTOR_BODY_LAYOUT_ASSIGNMENTS', + 'ARCHETYPE_ASSIGNMENTS', + 'ARCHETYPE_CONSTRAINTS', + 'ARCHETYPE_ROOTS', + 'BALANCE_CURVE_ATTACHMENTS', + 'BALANCE_CURVE_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS', + 'BODY_LAYOUT_ROOTS', + 'CRAFTING_INGREDIENT_BINDINGS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', + 'CRAFTING_RECIPE_ROOTS', + 'EQUIPMENT_ATTACHMENT_RULES', + 'EQUIPMENT_CAPABILITIES', + 'EQUIPMENT_COMPATIBILITY_RULES', + 'EQUIPMENT_OCCUPANCY_RULES', + 'EQUIPMENT_SLOT_GROUPS', + 'EQUIPMENT_SLOT_ROOTS', + 'INBOUND_LOOT_BINDINGS', + 'ITEM_TEMPLATE_ROOTS', + 'LOOT_ITEM_MAPPINGS', + 'LOOT_TABLE_ROOTS', + 'NPC_TEMPLATE_ROOTS', + 'OTHER_ACTOR_TEMPLATE_ROOTS' + )), + CONSTRAINT ck_entity_empty_selected_source_family_state + CHECK (owner_state = 'EMPTY'), + CONSTRAINT ck_entity_empty_selected_source_family_evidence_kind + CHECK ( + (family_name IN ( + 'ITEM_TEMPLATE_ROOTS', 'NPC_TEMPLATE_ROOTS', 'CRAFTING_RECIPE_ROOTS', + 'CRAFTING_RECIPE_RESULT_BINDINGS', 'CRAFTING_INGREDIENT_BINDINGS', + 'EQUIPMENT_SLOT_ROOTS', 'EQUIPMENT_SLOT_GROUPS', 'BODY_LAYOUT_ROOTS', + 'BODY_LAYOUT_MEMBERSHIPS' + ) AND evidence_kind = 'V1_SOURCE_CENSUS') + OR (family_name IN ( + 'ACTOR_BODY_LAYOUT_ASSIGNMENTS', 'ARCHETYPE_ASSIGNMENTS', + 'ARCHETYPE_CONSTRAINTS', 'ARCHETYPE_ROOTS', 'BALANCE_CURVE_ATTACHMENTS', + 'BALANCE_CURVE_ROOTS', 'EQUIPMENT_ATTACHMENT_RULES', + 'EQUIPMENT_CAPABILITIES', 'EQUIPMENT_COMPATIBILITY_RULES', + 'EQUIPMENT_OCCUPANCY_RULES', 'INBOUND_LOOT_BINDINGS', 'LOOT_ITEM_MAPPINGS', + 'LOOT_TABLE_ROOTS', 'OTHER_ACTOR_TEMPLATE_ROOTS' + ) AND evidence_kind = 'EMPTY_ONLY_OWNER_PROVIDER') + ), + CONSTRAINT ck_entity_empty_selected_source_family_counts + CHECK ( + row_count = 0 + AND unqualified_row_count = 0 + AND retained_row_count = 0 + AND selected_scope_row_count = 0 + AND reference_count = 0 + ) +); + +CREATE TABLE entity_empty_selected_source_receipt ( + target_namespace VARCHAR(63) NOT NULL, + intake_request_id UUID NOT NULL, + request_digest VARCHAR(71) NOT NULL, + schema_digest VARCHAR(71) NOT NULL, + receipt_digest VARCHAR(71) NOT NULL, + receipt_bytes BYTEA NOT NULL, + retained_at TIMESTAMPTZ NOT NULL, + CONSTRAINT pk_entity_empty_selected_source_receipt + PRIMARY KEY (target_namespace, intake_request_id), + CONSTRAINT fk_entity_empty_selected_source_receipt_association + FOREIGN KEY (target_namespace, intake_request_id) + REFERENCES entity_empty_selected_source_association (target_namespace, intake_request_id) + ON DELETE RESTRICT, + CONSTRAINT ck_entity_empty_selected_source_receipt_digests + CHECK ( + request_digest ~ '^sha256:[0-9a-f]{64}$' + AND schema_digest ~ '^sha256:[0-9a-f]{64}$' + AND receipt_digest ~ '^sha256:[0-9a-f]{64}$' + AND octet_length(receipt_bytes) BETWEEN 1 AND 83886080 + ) +); + +CREATE INDEX idx_entity_empty_source_key_claim_kind + ON entity_empty_source_numeric_key_reservation (claim_kind, key_kind, numeric_key); + +/* [jooq ignore start] */ +CREATE FUNCTION entity_source_positive_numeric_key(value_text TEXT) +RETURNS BIGINT +LANGUAGE plpgsql +IMMUTABLE +STRICT +SET search_path = pg_catalog +AS $$ +DECLARE + parsed_value NUMERIC; +BEGIN + IF value_text !~ '^[0-9]+$' THEN + RETURN NULL; + END IF; + parsed_value := value_text::NUMERIC; + IF parsed_value <= 0 OR parsed_value > 9223372036854775807 THEN + RETURN NULL; + END IF; + RETURN parsed_value::BIGINT; +END; +$$; +/* [jooq ignore stop] */ + +-- Lock the receipt/key tables first and then every V1 tenant/version holder and source/reference +-- relation. This both seeds real occupied keys and closes insert/update phantoms for the same +-- fixed order used by the owner-local founding transaction. +/* [jooq ignore start] */ +LOCK TABLE entity_empty_source_numeric_key_reservation, + entity_empty_selected_source_association, + entity_empty_selected_source_family_state, + entity_empty_selected_source_receipt, + entity_empty_source_other_actor_template_roots, + entity_empty_source_equipment_capabilities, + entity_empty_source_equipment_attachment_rules, + entity_empty_source_equipment_compatibility_rules, + entity_empty_source_equipment_occupancy_rules, + entity_empty_source_actor_body_layout_assignments, + entity_empty_source_loot_table_roots, + entity_empty_source_loot_item_mappings, + entity_empty_source_inbound_loot_bindings, + entity_empty_source_balance_curve_roots, + entity_empty_source_balance_curve_attachments, + entity_empty_source_archetype_roots, + entity_empty_source_archetype_constraints, + entity_empty_source_archetype_assignments + IN SHARE ROW EXCLUSIVE MODE; +/* [jooq ignore stop] */ +/* [jooq ignore start] */ +LOCK TABLE actor_active_conditions, actor_resource_states, body_layout_slot_definitions, + character_equipment, character_friend, characters, container_instances, + crafting_ingredients, crafting_recipes, entity_mutation_effects, + equipment_slot_definitions, inventory, item_instances, item_stacks, + item_transfer_audits, item_visible_ref_counters, items, npcs, room_ground_inventory + IN SHARE MODE; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +INSERT INTO entity_empty_source_numeric_key_reservation (key_kind, numeric_key, claim_kind) +SELECT DISTINCT key_kind, numeric_key, 'LEGACY_NUMERIC' +FROM ( + SELECT 'TENANT'::VARCHAR(16) AS key_kind, tenant_id AS numeric_key FROM characters + UNION ALL SELECT 'TENANT', tenant_id FROM npcs + UNION ALL SELECT 'TENANT', tenant_id FROM items + UNION ALL SELECT 'TENANT', tenant_id FROM crafting_recipes + UNION ALL SELECT 'TENANT', tenant_id FROM character_friend + UNION ALL SELECT 'TENANT', tenant_id FROM room_ground_inventory + UNION ALL SELECT 'TENANT', tenant_id FROM container_instances + UNION ALL SELECT 'TENANT', tenant_id FROM item_instances + UNION ALL SELECT 'TENANT', tenant_id FROM item_visible_ref_counters + UNION ALL SELECT 'TENANT', tenant_id FROM item_stacks + UNION ALL SELECT 'TENANT', tenant_id FROM entity_mutation_effects + UNION ALL SELECT 'TENANT', tenant_id FROM item_transfer_audits + UNION ALL SELECT 'TENANT', tenant_id FROM equipment_slot_definitions + UNION ALL SELECT 'TENANT', tenant_id FROM body_layout_slot_definitions + UNION ALL SELECT 'TENANT', tenant_id FROM actor_resource_states + UNION ALL SELECT 'TENANT', tenant_id FROM actor_active_conditions + UNION ALL SELECT 'VERSION', version_id FROM items + UNION ALL SELECT 'VERSION', version_id FROM npcs + UNION ALL SELECT 'VERSION', version_id FROM crafting_recipes + UNION ALL SELECT 'VERSION', version_id FROM equipment_slot_definitions + UNION ALL SELECT 'VERSION', version_id FROM body_layout_slot_definitions +) AS existing_entity_keys +WHERE numeric_key > 0 +ON CONFLICT (key_kind, numeric_key) DO NOTHING; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +DO $entity_empty_source_functions$ +DECLARE + owner_schema TEXT := current_schema(); +BEGIN + IF owner_schema IS NULL THEN + RAISE EXCEPTION 'Entity empty-source functions require an explicit installation schema'; + END IF; + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_require_source_numeric_key_unreserved( + requested_kind TEXT, requested_key BIGINT + ) RETURNS VOID + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + retained_claim TEXT; + BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Entity authored-source row writes require READ COMMITTED isolation'; + END IF; + IF requested_key IS NULL OR requested_key <= 0 THEN + RETURN; + END IF; + SELECT claim_kind INTO retained_claim + FROM %I.entity_empty_source_numeric_key_reservation + WHERE key_kind = requested_kind AND numeric_key = requested_key; + IF retained_claim = 'CANONICAL_EMPTY_SOURCE' THEN + RAISE EXCEPTION 'Entity numeric source key is reserved by an immutable empty-source receipt'; + END IF; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_guard_source_owner_row() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_value JSONB; + new_value JSONB; + old_tenant_key BIGINT; + new_tenant_key BIGINT; + old_version_key BIGINT; + new_version_key BIGINT; + old_is_owner_resolved_character BOOLEAN := FALSE; + new_is_owner_resolved_character BOOLEAN := FALSE; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_value := to_jsonb(OLD); + old_tenant_key := %I.entity_source_positive_numeric_key(old_value->>'tenant_id'); + old_version_key := %I.entity_source_positive_numeric_key(old_value->>'version_id'); + IF TG_TABLE_NAME = 'characters' THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', NULL::BIGINT); + SELECT EXISTS ( + SELECT 1 + FROM %I.entity_tenant_identities tenant_identity + JOIN %I.entity_playable_state_namespace_scopes namespace_scope + ON namespace_scope.tenant_uuid = tenant_identity.canonical_tenant_uuid + WHERE tenant_identity.entity_tenant_row_id = old_tenant_key + AND tenant_identity.canonical_tenant_uuid = + NULLIF(old_value->>'tenant_uuid', '')::UUID + AND namespace_scope.playable_state_namespace_id = + NULLIF(old_value->>'playable_state_namespace_id', '')::UUID + AND namespace_scope.playable_state_scope = + old_value->>'playable_state_scope' + AND old_value->>'actor_identity_status' = 'OWNER_RESOLVED' + AND old_value->>'actor_identity_quarantine_reason' IS NULL + AND NULLIF(old_value->>'character_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + AND NULLIF(old_value->>'account_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + ) INTO old_is_owner_resolved_character; + IF NOT old_is_owner_resolved_character THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', old_tenant_key); + END IF; + ELSE + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', old_tenant_key); + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', old_version_key); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_value := to_jsonb(NEW); + new_tenant_key := %I.entity_source_positive_numeric_key(new_value->>'tenant_id'); + new_version_key := %I.entity_source_positive_numeric_key(new_value->>'version_id'); + IF TG_TABLE_NAME = 'characters' THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', NULL::BIGINT); + SELECT EXISTS ( + SELECT 1 + FROM %I.entity_tenant_identities tenant_identity + JOIN %I.entity_playable_state_namespace_scopes namespace_scope + ON namespace_scope.tenant_uuid = tenant_identity.canonical_tenant_uuid + WHERE tenant_identity.entity_tenant_row_id = new_tenant_key + AND tenant_identity.canonical_tenant_uuid = + NULLIF(new_value->>'tenant_uuid', '')::UUID + AND namespace_scope.playable_state_namespace_id = + NULLIF(new_value->>'playable_state_namespace_id', '')::UUID + AND namespace_scope.playable_state_scope = + new_value->>'playable_state_scope' + AND new_value->>'actor_identity_status' = 'OWNER_RESOLVED' + AND new_value->>'actor_identity_quarantine_reason' IS NULL + AND NULLIF(new_value->>'character_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + AND NULLIF(new_value->>'account_uuid', '')::UUID <> + '00000000-0000-0000-0000-000000000000'::UUID + ) INTO new_is_owner_resolved_character; + IF NOT new_is_owner_resolved_character THEN + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', new_tenant_key); + END IF; + ELSE + PERFORM %I.entity_require_source_numeric_key_unreserved( + 'TENANT', new_tenant_key); + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', new_version_key); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, + owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, + owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_guard_character_template_reference() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_character_id BIGINT; + new_character_id BIGINT; + referenced_tenant BIGINT; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_character_id := (to_jsonb(OLD)->>'character_id')::BIGINT; + SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = old_character_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity character reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_character_id := (to_jsonb(NEW)->>'character_id')::BIGINT; + SELECT tenant_id INTO referenced_tenant FROM %I.characters WHERE id = new_character_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity character reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_guard_recipe_ingredient_reference() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + DECLARE + old_recipe_id BIGINT; + new_recipe_id BIGINT; + referenced_tenant BIGINT; + referenced_version BIGINT; + BEGIN + IF TG_OP IN ('UPDATE', 'DELETE') THEN + old_recipe_id := (to_jsonb(OLD)->>'recipe_id')::BIGINT; + SELECT tenant_id, version_id INTO referenced_tenant, referenced_version + FROM %I.crafting_recipes WHERE id = old_recipe_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity crafting recipe reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', referenced_version); + END IF; + IF TG_OP IN ('INSERT', 'UPDATE') THEN + new_recipe_id := (to_jsonb(NEW)->>'recipe_id')::BIGINT; + SELECT tenant_id, version_id INTO referenced_tenant, referenced_version + FROM %I.crafting_recipes WHERE id = new_recipe_id; + IF NOT FOUND THEN + RAISE EXCEPTION 'Entity crafting recipe reference owner is unavailable'; + END IF; + PERFORM %I.entity_require_source_numeric_key_unreserved('TENANT', referenced_tenant); + PERFORM %I.entity_require_source_numeric_key_unreserved('VERSION', referenced_version); + END IF; + IF TG_OP = 'DELETE' THEN + RETURN OLD; + END IF; + RETURN NEW; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema, owner_schema, owner_schema, + owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_reject_source_truncate() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + IF current_setting('transaction_isolation') <> 'read committed' THEN + RAISE EXCEPTION 'Entity authored-source TRUNCATE requires READ COMMITTED isolation'; + END IF; + IF EXISTS ( + SELECT 1 FROM %I.entity_empty_source_numeric_key_reservation + WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE' + ) THEN + RAISE EXCEPTION 'Entity authored-source TRUNCATE is forbidden after canonical intake'; + END IF; + RETURN NULL; + END; + $body$ + $function$, owner_schema, owner_schema, owner_schema); + + EXECUTE format($function$ + CREATE FUNCTION %I.entity_reject_empty_source_record_mutation() + RETURNS TRIGGER + LANGUAGE plpgsql + SECURITY DEFINER + SET search_path = pg_catalog, %I + AS $body$ + BEGIN + RAISE EXCEPTION 'Entity empty-source intake records are immutable'; + END; + $body$ + $function$, owner_schema, owner_schema); +END; +$entity_empty_source_functions$; +/* [jooq ignore stop] */ + +/* [jooq ignore start] */ +REVOKE ALL ON FUNCTION entity_source_positive_numeric_key(TEXT) FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_require_source_numeric_key_unreserved(TEXT, BIGINT) FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_guard_source_owner_row() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_guard_character_template_reference() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_guard_recipe_ingredient_reference() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_reject_source_truncate() FROM PUBLIC; +REVOKE ALL ON FUNCTION entity_reject_empty_source_record_mutation() FROM PUBLIC; + +CREATE TRIGGER trg_entity_items_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON items + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_npcs_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON npcs + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_recipes_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON crafting_recipes + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_equipment_slots_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON equipment_slot_definitions + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_body_layouts_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON body_layout_slot_definitions + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); + +CREATE TRIGGER trg_entity_character_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON characters + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_character_friend_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON character_friend + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_room_ground_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON room_ground_inventory + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_container_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON container_instances + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_instance_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_instances + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_stack_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_stacks + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_audit_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_transfer_audits + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_item_reference_counter_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON item_visible_ref_counters + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_mutation_effect_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON entity_mutation_effects + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_actor_resource_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON actor_resource_states + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); +CREATE TRIGGER trg_entity_actor_condition_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON actor_active_conditions + FOR EACH ROW EXECUTE FUNCTION entity_guard_source_owner_row(); + +CREATE TRIGGER trg_entity_inventory_character_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON inventory + FOR EACH ROW EXECUTE FUNCTION entity_guard_character_template_reference(); +CREATE TRIGGER trg_entity_character_equipment_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON character_equipment + FOR EACH ROW EXECUTE FUNCTION entity_guard_character_template_reference(); +CREATE TRIGGER trg_entity_crafting_ingredient_source_reservation + BEFORE INSERT OR UPDATE OR DELETE ON crafting_ingredients + FOR EACH ROW EXECUTE FUNCTION entity_guard_recipe_ingredient_reference(); + +CREATE TRIGGER trg_entity_items_source_no_truncate + BEFORE TRUNCATE ON items + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_npcs_source_no_truncate + BEFORE TRUNCATE ON npcs + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_recipes_source_no_truncate + BEFORE TRUNCATE ON crafting_recipes + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_ingredients_source_no_truncate + BEFORE TRUNCATE ON crafting_ingredients + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_equipment_slots_source_no_truncate + BEFORE TRUNCATE ON equipment_slot_definitions + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); +CREATE TRIGGER trg_entity_body_layouts_source_no_truncate + BEFORE TRUNCATE ON body_layout_slot_definitions + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_source_truncate(); + +CREATE TRIGGER trg_entity_empty_source_key_reservation_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_numeric_key_reservation + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_key_reservation_no_truncate + BEFORE TRUNCATE ON entity_empty_source_numeric_key_reservation + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_association_immutable + BEFORE UPDATE OR DELETE ON entity_empty_selected_source_association + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_association_no_truncate + BEFORE TRUNCATE ON entity_empty_selected_source_association + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_family_state_immutable + BEFORE UPDATE OR DELETE ON entity_empty_selected_source_family_state + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_family_state_no_truncate + BEFORE TRUNCATE ON entity_empty_selected_source_family_state + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_receipt_immutable + BEFORE UPDATE OR DELETE ON entity_empty_selected_source_receipt + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_receipt_no_truncate + BEFORE TRUNCATE ON entity_empty_selected_source_receipt + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_other_actor_template_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_other_actor_template_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_other_actor_template_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_other_actor_template_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_capabilities_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_capabilities + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_capabilities_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_capabilities + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_attachment_rules_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_attachment_rules + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_attachment_rules_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_attachment_rules + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_compatibility_rules_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_compatibility_rules + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_compatibility_rules_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_compatibility_rules + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_occupancy_rules_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_equipment_occupancy_rules + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_equipment_occupancy_rules_no_truncate + BEFORE TRUNCATE ON entity_empty_source_equipment_occupancy_rules + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_actor_body_layout_assignments_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_actor_body_layout_assignments + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_actor_body_layout_assignments_no_truncate + BEFORE TRUNCATE ON entity_empty_source_actor_body_layout_assignments + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_table_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_loot_table_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_table_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_loot_table_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_item_mappings_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_loot_item_mappings + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_loot_item_mappings_no_truncate + BEFORE TRUNCATE ON entity_empty_source_loot_item_mappings + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_inbound_loot_bindings_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_inbound_loot_bindings + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_inbound_loot_bindings_no_truncate + BEFORE TRUNCATE ON entity_empty_source_inbound_loot_bindings + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_balance_curve_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_balance_curve_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_attachments_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_balance_curve_attachments + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_balance_curve_attachments_no_truncate + BEFORE TRUNCATE ON entity_empty_source_balance_curve_attachments + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_roots_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_roots + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_roots_no_truncate + BEFORE TRUNCATE ON entity_empty_source_archetype_roots + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_constraints_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_constraints + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_constraints_no_truncate + BEFORE TRUNCATE ON entity_empty_source_archetype_constraints + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_assignments_immutable + BEFORE UPDATE OR DELETE ON entity_empty_source_archetype_assignments + FOR EACH ROW EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +CREATE TRIGGER trg_entity_empty_source_archetype_assignments_no_truncate + BEFORE TRUNCATE ON entity_empty_source_archetype_assignments + FOR EACH STATEMENT EXECUTE FUNCTION entity_reject_empty_source_record_mutation(); +/* [jooq ignore stop] */ diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java index 5726f1b3a9..e5decc2f7d 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/PreseededActorAssignmentIntegrationTest.java @@ -21,6 +21,7 @@ import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import net.firedevops.firemud.common.account.RuntimeAccountIdentityEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; import net.firedevops.firemud.entitymanagement.entity.ActorActiveCondition; import net.firedevops.firemud.entitymanagement.entity.ActorResourceState; import net.firedevops.firemud.entitymanagement.entity.Character; @@ -31,6 +32,7 @@ import net.firedevops.firemud.entitymanagement.repository.CharacterEquipmentRepository; import net.firedevops.firemud.entitymanagement.repository.CharacterFriendRepository; import net.firedevops.firemud.entitymanagement.repository.CharacterRepository; +import net.firedevops.firemud.entitymanagement.repository.EntityEmptySelectedSourceIntakePostgresFixture; import net.firedevops.firemud.entitymanagement.repository.InventoryEntryRepository; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterEntryPolicy; import net.firedevops.firemud.entitymanagement.service.CanonicalGameplayRosterExecutionContext; @@ -44,6 +46,7 @@ import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentRequest; import net.firedevops.firemud.entitymanagement.service.PreseededActorAssignmentResult; import net.firedevops.firemud.entitymanagement.service.PreseededActorCorePayload; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; import net.firedevops.firemud.entitymanagement.v1.PlayableStateScope; import net.firedevops.firemud.test.PostgresBackedServiceTestSupport; import net.firedevops.firemud.test.TestContainerImages; @@ -51,6 +54,9 @@ import org.flywaydb.core.api.MigrationVersion; import org.flywaydb.core.api.configuration.FluentConfiguration; import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -60,6 +66,7 @@ import org.springframework.data.domain.Pageable; import org.springframework.grpc.server.lifecycle.GrpcServerLifecycle; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.test.context.bean.override.mockito.MockitoBean; @@ -403,7 +410,7 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( upgradedHistory.subList(parentHistory.size(), upgradedHistory.size()); assertThat(successorHistory) .extracting(AppliedMigration::version) - .containsExactly("1006", "1007", "1008", "1009", "1010"); + .containsExactly("1006", "1007", "1008", "1009", "1010", "1011"); assertThat(successorHistory) .extracting(AppliedMigration::script) .containsExactly( @@ -411,7 +418,8 @@ void quarantinesEveryRetainedDuplicateBeforeEnforcingUniqueLiveAccountNamespace( "V1007__preseeded_assignment_owner_snapshot.sql", "V1008__canonical_gameplay_roster_snapshots.sql", "V1009__canonical_publication_uuid_actor_evidence.sql", - "V1010__canonical_roster_owner_counters.sql"); + "V1010__canonical_roster_owner_counters.sql", + "V1011__fresh_selected_empty_source_catalogue.sql"); assertThat(successorHistory).extracting(AppliedMigration::checksum).doesNotContainNull(); try (Connection connection = connectToSchema(schema)) { @@ -681,6 +689,99 @@ void numericTenantCollisionKeepsQuarantinedCanonicalActorOutOfLegacyReadersAndWr assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters(true); } + @Test + void reservedAuthoredTenantKeyDoesNotBlockOwnerResolvedCharacterAssignment() throws Exception { + for (boolean captureEmptyRosterBeforeSource : List.of(true, false)) { + String schema = "pc_" + UUID.randomUUID().toString().replace("-", ""); + try { + migrationFlyway(schema).load().migrate(); + DSLContext isolatedDsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES); + EntityEmptySelectedSourceIntakeRepository sourceRepository = + new EntityEmptySelectedSourceIntakeRepository(isolatedDsl); + var sourceFixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + tenantUuid = sourceFixture.authorization().tenantId(); + var owner = + evidence( + assignmentUuid, + accountUuid, + 4L, + PlayableStateScope.PLAYABLE_STATE_SCOPE_SHARED, + sourceFixture.authorization().versionId()); + + if (captureEmptyRosterBeforeSource) { + assertEmptyCanonicalRosterCreatedTenantMapping(isolatedDsl, owner); + } + + var sourceReceipt = + sourceRepository.retainFresh( + sourceFixture.inputs(), + EntityEmptySelectedSourceIntakeReceipt.requestDigest( + sourceFixture.authorization().targetNamespace(), + sourceFixture.authorization(), + sourceFixture.freezeEvidence())); + assertThat(sourceReceipt.localTenantKey()).isEqualTo(1L); + + if (!captureEmptyRosterBeforeSource) { + assertEmptyCanonicalRosterCreatedTenantMapping(isolatedDsl, owner); + } + + Long entityTenantRowId = + isolatedDsl + .fetchSingle( + "SELECT entity_tenant_row_id FROM entity_tenant_identities " + + "WHERE canonical_tenant_uuid = ?", + owner.canonicalTenantUuid()) + .get(0, Long.class); + assertThat(entityTenantRowId).isEqualTo(sourceReceipt.localTenantKey()); + byte[] receiptBytes = sourceReceipt.canonicalBytes(); + + PreseededActorAssignmentRequest request = assignmentRequest(owner, "Reserved-Key Actor"); + PreseededActorAssignmentResult assigned = + isolatedDsl.transactionResult( + configuration -> + new CharacterRepository(DSL.using(configuration)) + .assignPreseededActor( + request, + owner, + accountIdentity(assignmentUuid, accountUuid), + request.mutationIntentDigest())); + assertThat(assigned.outcome()).isEqualTo(PreseededActorAssignmentResult.Outcome.ASSIGNED); + assertThat(assigned.characterUuid()).isNotNull(); + + assertThatThrownBy( + () -> + isolatedDsl.execute( + "INSERT INTO characters (account_id, name, tenant_id) " + + "VALUES (23, 'Legacy Reserved-Key Actor', ?)", + sourceReceipt.localTenantKey())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("reserved by an immutable empty-source receipt"); + assertThatThrownBy( + () -> + isolatedDsl.execute( + "UPDATE characters SET account_uuid = NULL, tenant_uuid = NULL, " + + "playable_state_namespace_id = NULL, playable_state_scope = NULL, " + + "actor_identity_status = 'QUARANTINED', " + + "actor_identity_quarantine_reason = 'OWNER_PROVENANCE_MISSING' " + + "WHERE character_uuid = ?", + assigned.characterUuid())) + .isInstanceOf(org.jooq.exception.DataAccessException.class) + .hasMessageContaining("reserved by an immutable empty-source receipt"); + + var retainedSourceReceipt = + sourceRepository + .read(sourceReceipt.targetNamespace(), sourceReceipt.intakeRequestId()) + .orElseThrow(); + assertThat(retainedSourceReceipt.canonicalBytes()).containsExactly(receiptBytes); + assertThat(retainedSourceReceipt.receiptDigest()).isEqualTo(sourceReceipt.receiptDigest()); + } finally { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + } + } + } + private void assertNumericTenantCollisionKeepsCanonicalActorOutOfLegacyReadersAndWriters( boolean quarantined) { PreseededActorAssignmentResult assigned = @@ -1484,6 +1585,62 @@ private PreseededActorAssignmentResult assign( request.mutationIntentDigest()); } + private void assertEmptyCanonicalRosterCreatedTenantMapping( + DSLContext isolatedDsl, PreseededActorAssignmentOwnerEvidence owner) { + UUID gameInstanceUuid = UUID.randomUUID(); + CanonicalGameplayRosterTarget target = + new CanonicalGameplayRosterTarget( + owner.canonicalTenantUuid(), + owner.realmUuid(), + owner.worldSlug(), + owner.realmSlug(), + gameInstanceUuid, + owner.catalogRevision(), + 1L, + 1L, + owner.canonicalVersionUuid(), + owner.frozenPolicyDigest(), + owner.publishedReleaseBundleRef(), + "5".repeat(64), + owner.publishedOwnerProofDigest(), + owner.playableStateNamespaceId(), + owner.playableStateScope(), + CanonicalGameplayRosterEntryPolicy.PRESEEDED_ONLY); + UUID requestUuid = UUID.randomUUID(); + CanonicalGameplayRosterReadRequest request = + new CanonicalGameplayRosterReadRequest( + requestUuid, + owner.canonicalAccountUuid(), + target, + new CanonicalGameplayRosterExecutionContext( + owner.canonicalAccountUuid(), + target.tenantUuid(), + target.playableStateNamespaceId(), + target.gameInstanceUuid(), + null, + UUID.randomUUID(), + target.realmUuid(), + requestUuid, + target.playableStateScope())); + var snapshot = + isolatedDsl.transactionResult( + configuration -> + new CharacterRepository(DSL.using(configuration)) + .captureCanonicalGameplayRosterSnapshot( + request, + new CanonicalGameplayRosterOwnerEvidence( + requestUuid, owner.canonicalAccountUuid(), target, Instant.now()))); + assertThat(snapshot.actors()).isEmpty(); + Long mappedTenantRowId = + isolatedDsl + .fetchSingle( + "SELECT entity_tenant_row_id FROM entity_tenant_identities " + + "WHERE canonical_tenant_uuid = ?", + owner.canonicalTenantUuid()) + .get(0, Long.class); + assertThat(mappedTenantRowId).isEqualTo(1L); + } + private PreseededActorAssignmentRequest assignmentRequest( PreseededActorAssignmentOwnerEvidence target) { return assignmentRequest(target, "Assigned Actor"); @@ -1538,6 +1695,20 @@ private static PreseededActorAssignmentOwnerEvidence withPublishedReleaseBundleR private PreseededActorAssignmentOwnerEvidence evidence( UUID operationUuid, UUID actorAccountUuid, long catalogRevision, PlayableStateScope scope) { + return evidence( + operationUuid, + actorAccountUuid, + catalogRevision, + scope, + UUID.fromString("17000000-0000-4000-8000-000000000017")); + } + + private PreseededActorAssignmentOwnerEvidence evidence( + UUID operationUuid, + UUID actorAccountUuid, + long catalogRevision, + PlayableStateScope scope, + UUID canonicalVersionUuid) { return new PreseededActorAssignmentOwnerEvidence( operationUuid, actorAccountUuid, @@ -1551,7 +1722,7 @@ private PreseededActorAssignmentOwnerEvidence evidence( "realm", "game-instance", catalogRevision, - UUID.fromString("17000000-0000-4000-8000-000000000017"), + canonicalVersionUuid, "2".repeat(64), namespaceUuid, scope, @@ -1596,6 +1767,19 @@ private FluentConfiguration migrationFlyway(String schema) { return configuration; } + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } + private List appliedMigrationHistory(String schema) throws SQLException { List migrations = new ArrayList<>(); try (Connection connection = connectToSchema(schema); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java index 6a211e4f2d..07f3c20e20 100644 --- a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/RetainedActorIdentityIntegrationTest.java @@ -642,7 +642,7 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { .extracting(migration -> migration.getVersion().getVersion()) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010"); + "1010", "1011"); assertThat(flyway.info().applied()) .filteredOn(migration -> migration.getVersion() != null) .extracting(migration -> migration.getScript()) @@ -658,9 +658,10 @@ void freshDefaultFlywayInstallsCompleteCombinedManifest() { "V1007__preseeded_assignment_owner_snapshot.sql", "V1008__canonical_gameplay_roster_snapshots.sql", "V1009__canonical_publication_uuid_actor_evidence.sql", - "V1010__canonical_roster_owner_counters.sql"); + "V1010__canonical_roster_owner_counters.sql", + "V1011__fresh_selected_empty_source_catalogue.sql"); assertThat(flyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1010")); + .isEqualTo(MigrationVersion.fromVersion("1011")); assertThat(flyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); @@ -733,7 +734,7 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro .extracting(MigrationHistoryEntry::version) .containsExactly( "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", - "1010"); + "1010", "1011"); assertThat(upgradedHistory) .extracting(MigrationHistoryEntry::script) .containsExactly( @@ -748,7 +749,8 @@ void flywayParentFrontierToLatestRetainsLegacyRowsAndValidatesConstraints() thro "V1007__preseeded_assignment_owner_snapshot.sql", "V1008__canonical_gameplay_roster_snapshots.sql", "V1009__canonical_publication_uuid_actor_evidence.sql", - "V1010__canonical_roster_owner_counters.sql"); + "V1010__canonical_roster_owner_counters.sql", + "V1011__fresh_selected_empty_source_catalogue.sql"); assertThat(upgradedHistory).allSatisfy(entry -> assertThat(entry.success()).isTrue()); try (Connection connection = connectToMigrationSchema(); @@ -1011,7 +1013,7 @@ private void migrateLegacySchemaToLatest() { assertThat(upgradeFlyway.getConfiguration().isOutOfOrder()).isFalse(); upgradeFlyway.migrate(); assertThat(upgradeFlyway.info().current().getVersion()) - .isEqualTo(MigrationVersion.fromVersion("1010")); + .isEqualTo(MigrationVersion.fromVersion("1011")); assertThat(upgradeFlyway.info().applied()) .extracting(migration -> migration.getState()) .doesNotContain(MigrationState.OUT_OF_ORDER); diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java new file mode 100644 index 0000000000..5a4c8718d2 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest.java @@ -0,0 +1,320 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.sql.Connection; +import java.sql.SQLException; +import java.sql.Statement; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** PostgreSQL proof for V1011's actual-parent legacy-key seed and retained-key writer guards. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class EntityEmptySelectedSourceIntakeMigrationPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + + @BeforeEach + void seedLegacyRowsBeforeV1011() { + schema = "entity_empty_source_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + var legacyFlywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)) + .target("1010"); + legacyFlywayConfiguration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + legacyFlywayConfiguration.load().migrate(); + + DSLContext legacyDsl = DSL.using(dataSource, SQLDialect.POSTGRES); + // Synthetic V1010 parent rows exercise migration occupancy only. They are not selected-source + // evidence and do not authenticate Account, Game Design, or World producers. + legacyDsl.execute( + "INSERT INTO characters (account_id, name, tenant_id) VALUES (1, 'legacy', 31001)"); + legacyDsl.execute( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('legacy', 41001, 51001)"); + legacyDsl.execute( + "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, " + + "source_holder_kind, destination_holder_kind) " + + "VALUES (61001, 99001, 1, 'MOVE', 'legacy-audit', 'UNKNOWN', 'UNKNOWN')"); + + legacyDsl.execute( + "INSERT INTO entity_tenant_identities (canonical_tenant_uuid) VALUES (?)", + UUID.randomUUID()); + legacyDsl.execute( + "INSERT INTO saga_instance (saga_name, state) VALUES ('retained-entity-source', 'PENDING')"); + legacyDsl.execute( + "INSERT INTO saga_step (instance_id, name, status) SELECT id, 'retained-step', 'PENDING' FROM saga_instance WHERE saga_name = 'retained-entity-source'"); + var parentRows = retainedParentRows(legacyDsl); + var parentHistory = history(legacyDsl); + assertThat( + legacyDsl + .fetch( + "SELECT version FROM flyway_schema_history WHERE success AND version IS NOT NULL ORDER BY installed_rank") + .getValues(0, String.class)) + .containsExactly( + "1", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", + "1010"); + + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + flywayConfiguration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + flywayConfiguration.load().migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + assertThat(retainedParentRows(dsl)).isEqualTo(parentRows); + assertThat(history(dsl).subList(0, parentHistory.size())) + .containsExactlyElementsOf(parentHistory); + assertThat( + dsl.fetchSingle( + "SELECT version FROM flyway_schema_history ORDER BY installed_rank DESC LIMIT 1") + .get(0, String.class)) + .isEqualTo("1011"); + } + + @AfterEach + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + void migrationSeedsActualLegacySourceAndAuditTenantVersionKeys() { + List legacyKeys = + dsl.fetch( + "SELECT key_kind, numeric_key, claim_kind " + + "FROM entity_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'LEGACY_NUMERIC' ORDER BY key_kind, numeric_key") + .map( + row -> + new ReservedNumericKey( + row.get(0, String.class), + row.get(1, Long.class), + row.get(2, String.class))); + assertThat(legacyKeys) + .containsExactly( + new ReservedNumericKey("TENANT", 31001L, "LEGACY_NUMERIC"), + new ReservedNumericKey("TENANT", 41001L, "LEGACY_NUMERIC"), + new ReservedNumericKey("TENANT", 61001L, "LEGACY_NUMERIC"), + new ReservedNumericKey("VERSION", 51001L, "LEGACY_NUMERIC")); + assertLegacyKey("TENANT", 31001L); + assertLegacyKey("TENANT", 41001L); + assertLegacyKey("TENANT", 61001L); + assertLegacyKey("VERSION", 51001L); + assertThat( + dsl.fetchSingle( + "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " + + "WHERE key_kind = 'VERSION' AND numeric_key = 51001 " + + "AND claim_kind = 'LEGACY_NUMERIC'") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void retainedNumericKeysRejectLaterSourceRuntimeAndAuditWriters() { + dsl.execute( + "INSERT INTO entity_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', 99001, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', 99002, 'CANONICAL_EMPTY_SOURCE')"); + + assertRejected( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', 99001, 99002)"); + assertRejected("UPDATE items SET tenant_id = 99001 WHERE tenant_id = 41001"); + assertRejected( + "INSERT INTO characters (account_id, name, tenant_id) VALUES (2, 'blocked', 99001)"); + assertRejected("UPDATE characters SET tenant_id = 99001 WHERE tenant_id = 31001"); + assertRejected( + "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, " + + "source_holder_kind, destination_holder_kind) " + + "VALUES (99001, 99003, 1, 'MOVE', 'blocked-audit', 'UNKNOWN', 'UNKNOWN')"); + } + + @Test + void unassociatedLegacyKeysRemainWritable() { + dsl.execute( + "INSERT INTO items (name, tenant_id, version_id) " + + "VALUES ('unassociated legacy item', 71001, 71002)"); + dsl.execute( + "INSERT INTO characters (account_id, name, tenant_id) " + + "VALUES (3, 'unassociated legacy character', 72001)"); + + assertThat( + dsl.fetchSingle("SELECT COUNT(*) FROM items WHERE tenant_id = 71001") + .get(0, Long.class)) + .isEqualTo(1L); + assertThat( + dsl.fetchSingle("SELECT COUNT(*) FROM characters WHERE tenant_id = 72001") + .get(0, Long.class)) + .isEqualTo(1L); + } + + @Test + void staleRepeatableReadWritersCannotMissACommittedCanonicalReservation() throws SQLException { + try (Connection staleRowWriter = repeatableReadSnapshot()) { + commitCanonicalReservation(99001L); + try { + assertThatThrownBy( + () -> + execute( + staleRowWriter, + "INSERT INTO characters (account_id, name, tenant_id) " + + "VALUES (99001, 'stale-snapshot-character', 99001)")) + .isInstanceOf(SQLException.class) + .hasMessageContaining( + "Entity authored-source row writes require READ COMMITTED isolation"); + } finally { + staleRowWriter.rollback(); + } + } + + try (Connection staleTruncator = repeatableReadSnapshot()) { + commitCanonicalReservation(99002L); + try { + assertThatThrownBy(() -> execute(staleTruncator, "TRUNCATE TABLE items CASCADE")) + .isInstanceOf(SQLException.class) + .hasMessageContaining( + "Entity authored-source TRUNCATE requires READ COMMITTED isolation"); + } finally { + staleTruncator.rollback(); + } + } + } + + /** Storage retention only; synthetic parent rows establish no authenticated owner authority. */ + private static Map> retainedParentRows(DSLContext source) { + Map> rows = new java.util.LinkedHashMap<>(); + for (String table : + List.of( + "characters", + "items", + "item_transfer_audits", + "entity_tenant_identities", + "entity_playable_state_namespace_scopes", + "entity_preseeded_actor_assignment_operations", + "entity_canonical_gameplay_roster_snapshots", + "entity_canonical_gameplay_roster_snapshot_actors", + "saga_instance", + "saga_step")) { + rows.put( + table, + source + .fetch( + "SELECT jsonb_build_object('row', to_jsonb(t), 'xmin', t.xmin::TEXT)::TEXT FROM " + + table + + " t ORDER BY to_jsonb(t)::TEXT") + .getValues(0, String.class)); + } + return rows; + } + + private static List history(DSLContext source) { + return source + .fetch( + "SELECT to_jsonb(t)::TEXT || ':' || t.xmin::TEXT FROM flyway_schema_history t ORDER BY installed_rank") + .getValues(0, String.class); + } + + private void assertLegacyKey(String kind, long key) { + assertThat( + dsl.fetchSingle( + "SELECT claim_kind FROM entity_empty_source_numeric_key_reservation " + + "WHERE key_kind = ? AND numeric_key = ?", + kind, + key) + .get(0, String.class)) + .isEqualTo("LEGACY_NUMERIC"); + } + + private void assertRejected(String sql) { + assertThatThrownBy(() -> dsl.execute(sql)).isInstanceOf(DataAccessException.class); + } + + private Connection repeatableReadSnapshot() throws SQLException { + Connection connection = dataSource(schema).getConnection(); + connection.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); + connection.setAutoCommit(false); + try (Statement statement = connection.createStatement()) { + statement + .executeQuery("SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation") + .close(); + } + return connection; + } + + private void commitCanonicalReservation(long tenantKey) throws SQLException { + try (Connection founder = dataSource(schema).getConnection()) { + founder.setAutoCommit(false); + try (var reservation = + founder.prepareStatement( + "INSERT INTO entity_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) " + + "VALUES ('TENANT', ?, 'CANONICAL_EMPTY_SOURCE')")) { + reservation.setLong(1, tenantKey); + reservation.executeUpdate(); + } + founder.commit(); + } + } + + private static void execute(Connection connection, String sql) throws SQLException { + try (Statement statement = connection.createStatement()) { + statement.execute(sql); + } + } + + private record ReservedNumericKey(String keyKind, Long numericKey, String claimKind) {} + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java new file mode 100644 index 0000000000..b776b87265 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakePostgresFixture.java @@ -0,0 +1,468 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import java.io.ByteArrayOutputStream; +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.time.OffsetDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerEmptySourceInputs; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.authoring.DraftAuthorizationFenceBinding; +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.Owner; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.RevisionPayload; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.TargetProof; +import net.firedevops.firemud.common.entity.EntityAuthoredSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.AssetSnapshot; +import net.firedevops.firemud.common.gamedesign.BrandingSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.CommandSnapshot; +import net.firedevops.firemud.common.gamedesign.DraftSynchronizedVisibilityEvidence.AppliedEpoch; +import net.firedevops.firemud.common.gamedesign.RealmPolicySnapshot; +import net.firedevops.firemud.common.gamedesign.SelectedOwnerIntakeSourceContent; +import net.firedevops.firemud.common.gamedesign.TemplateConfigOwnerSourceInventoryDeclaration; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceSnapshot; +import net.firedevops.firemud.common.gamedesign.TemplateConfigSourceValues; +import net.firedevops.firemud.common.gamelogic.GameplayRuleManifest; +import net.firedevops.firemud.common.gamelogic.GameplayRuleSelectedSource; +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.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence.Acknowledgement; +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.publication.WorldSelectedPublicationArtifactInventoryEvidence.ArtifactDecision; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Checkpoint; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.FamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.Freeze; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceClosureDeclaration; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.InboundSourceFamilyCount; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicAccountOrder; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.RegionGeneratorInput; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SelectedApplication; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.SourceModel; + +/** + * Test-only synthetic inputs built through the same typed Common decoders as the shared fixture. + * They are not authenticated Account or World producer evidence or physical owner proof. + */ +public final class EntityEmptySelectedSourceIntakePostgresFixture { + static final String NAMESPACE = "test"; + static final UUID TENANT = id("11111111-1111-4111-8111-111111111111"); + static final UUID VERSION = id("22222222-2222-4222-8222-222222222222"); + static final UUID ACTOR = id("99999999-9999-4999-8999-999999999999"); + + private static final UUID OPERATION = id("55555555-5555-4555-8555-555555555555"); + private static final UUID FENCE = id("66666666-6666-4666-8666-666666666666"); + private static final UUID INTAKE_REQUEST = id("77777777-7777-4777-8777-777777777777"); + private static final UUID GENESIS_RECEIPT = id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"); + + private static final String TEMPLATE_CONFIG = + "{\"schemaVersion\":1,\"baseVersionId\":\"" + + VERSION + + "\",\"world\":{\"regions\":[],\"rooms\":[]}," + + "\"entity\":{\"items\":[],\"npcs\":[]},\"gameLogic\":{\"inputs\":[]}," + + "\"automation\":{\"scripts\":[],\"scriptPatch\":{\"presence\":\"ABSENT\"}}," + + "\"supportedSettings\":[]}"; + + private EntityEmptySelectedSourceIntakePostgresFixture() {} + + public static Fixture create(String sourceEpoch) { + DraftCommitBinding selected = selected(); + var scope = + new net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope( + Owner.ENTITY_MANAGEMENT, NAMESPACE, OPERATION, FENCE, INTAKE_REQUEST, ACTOR, selected); + TemplateConfigSourceSnapshot templateSnapshot = templateSnapshot(selected, sourceEpoch); + SelectedOwnerIntakeAuthorizationBinding authorization = + new SelectedOwnerIntakeAuthorizationBinding( + sourceContent(scope, templateSnapshot), accountSources()); + WorldSelectedDraftPublicationFreezeEvidence freeze = freezeEvidence(selected); + var inventory = + WorldSelectedPublicationArtifactInventoryEvidence.fromPublicEvidence( + freeze, publicInventory(freeze)); + var worldRequest = + SelectedOwnerWorldInventoryReadEvidence.create(NAMESPACE, authorization, freeze); + var worldEvidence = new SelectedOwnerWorldInventoryReadEvidence(worldRequest, inventory); + return new Fixture( + authorization, + freeze, + worldEvidence, + new SelectedOwnerEmptySourceInputs(authorization, worldEvidence)); + } + + static Fixture withFreshWorldReadCorrelation(Fixture original) { + var request = + SelectedOwnerWorldInventoryReadEvidence.create( + NAMESPACE, original.authorization(), original.freezeEvidence()); + var evidence = + new SelectedOwnerWorldInventoryReadEvidence(request, original.worldEvidence().inventory()); + return new Fixture( + original.authorization(), + original.freezeEvidence(), + evidence, + new SelectedOwnerEmptySourceInputs(original.authorization(), evidence)); + } + + private static TemplateConfigSourceSnapshot templateSnapshot( + DraftCommitBinding selected, String sourceEpoch) { + var declaration = + EntityAuthoredSourceInventoryDeclaration.parse( + "{\"schema\":\"entity-authored-source-inventory/v1\"," + + "\"equipmentApplicability\":\"NOT_APPLICABLE\",\"families\":{" + + "\"ACTOR_BODY_LAYOUT_ASSIGNMENTS\":[],\"ARCHETYPE_ASSIGNMENTS\":[]," + + "\"ARCHETYPE_CONSTRAINTS\":[],\"ARCHETYPE_ROOTS\":[]," + + "\"BALANCE_CURVE_ATTACHMENTS\":[],\"BALANCE_CURVE_ROOTS\":[]," + + "\"BODY_LAYOUT_MEMBERSHIPS\":[],\"BODY_LAYOUT_ROOTS\":[]," + + "\"CRAFTING_INGREDIENT_BINDINGS\":[],\"CRAFTING_RECIPE_RESULT_BINDINGS\":[]," + + "\"CRAFTING_RECIPE_ROOTS\":[],\"EQUIPMENT_ATTACHMENT_RULES\":[]," + + "\"EQUIPMENT_CAPABILITIES\":[],\"EQUIPMENT_COMPATIBILITY_RULES\":[]," + + "\"EQUIPMENT_OCCUPANCY_RULES\":[],\"EQUIPMENT_SLOT_GROUPS\":[]," + + "\"EQUIPMENT_SLOT_ROOTS\":[],\"INBOUND_LOOT_BINDINGS\":[]," + + "\"ITEM_TEMPLATE_ROOTS\":[],\"LOOT_ITEM_MAPPINGS\":[]," + + "\"LOOT_TABLE_ROOTS\":[],\"NPC_TEMPLATE_ROOTS\":[]," + + "\"OTHER_ACTOR_TEMPLATE_ROOTS\":[]}}"); + String declarationPayload = + TemplateConfigSourceValues.ownerInventoryPayload(Owner.ENTITY_MANAGEMENT, declaration); + DraftCommitBinding authored = authoredBinding(declarationPayload); + TemplateConfigOwnerSourceInventoryDeclaration ownerDeclaration = + TemplateConfigSourceValues.mutations(authored).stream() + .filter( + mutation -> + mutation.operation() + == TemplateConfigSourceValues.OperationKind.DECLARE_OWNER_SOURCE_INVENTORY) + .map(TemplateConfigSourceValues.Mutation::ownerInventoryDeclaration) + .findFirst() + .orElseThrow(); + return new TemplateConfigSourceSnapshot( + selected, + sourceEpoch, + authored.commitId(), + GENESIS_RECEIPT, + List.of(), + List.of(ownerDeclaration)); + } + + private static DraftCommitBinding authoredBinding(String payload) { + return DraftCommitBinding.create( + target(), + id("51515151-5151-4151-8151-515151515151"), + id("52525252-5252-4252-8252-525252525252"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", + id("53535353-5353-4353-8353-535353535353"), + Owner.GAME_DESIGN_CONTROL_PLANE, + payload)), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.GAME_DESIGN_CONTROL_PLANE, + TemplateConfigSourceValues.SCOPE, + VERSION.toString(), + TemplateConfigSourceValues.SCOPE, + TemplateConfigSourceValues.SCOPE_ID, + "0"))); + } + + private static SelectedOwnerIntakeSourceContent sourceContent( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeSourceReadScope scope, + TemplateConfigSourceSnapshot templateSnapshot) { + var out = new ByteArrayOutputStream(); + frame(out, SelectedOwnerIntakeSourceContent.DOMAIN); + frame(out, scope.canonicalBytes()); + frame(out, scope.digest()); + for (String family : + List.of( + "COMMAND", "REALM_POLICY", "ASSET", "GAMEPLAY_RULE", "BRANDING", "TEMPLATE_CONFIG")) { + byte[] snapshot = + "TEMPLATE_CONFIG".equals(family) + ? templateSnapshot.canonicalBytes() + : sourceSnapshot(family, scope.selected()); + frame(out, family); + frame(out, snapshot); + frame(out, DraftAuthorizationFenceBinding.digest(snapshot)); + } + byte[] bytes = out.toByteArray(); + return SelectedOwnerIntakeSourceContent.fromStored( + bytes, scope, DraftAuthorizationFenceBinding.digest(bytes)); + } + + private static byte[] sourceSnapshot(String family, DraftCommitBinding selected) { + // These values exercise exact stored-byte decoding only; they are synthetic, not owner proof. + return switch (family) { + case "COMMAND" -> + new CommandSnapshot(selected, "0", null, "sha256:" + "0".repeat(64), List.of()) + .canonicalBytes(); + case "REALM_POLICY" -> new RealmPolicySnapshot(selected, "0", List.of()).canonicalBytes(); + case "ASSET" -> + new AssetSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()).canonicalBytes(); + case "GAMEPLAY_RULE" -> + new GameplayRuleSelectedSource( + GameplayRuleManifest.canonical( + Map.of( + "schema", + "game-design-gameplay-rule-source-snapshot/v1", + "bindingJson", + selected.canonicalJson(), + "bindingDigest", + selected.digest(), + "sourceEpoch", + "0", + "inheritedCommitId", + "", + "genesisReceiptId", + GENESIS_RECEIPT.toString(), + "manifestJson", + GameplayRuleManifest.explicitEmpty().canonicalJson(), + "entries", + List.of()))) + .canonicalBytes(); + case "BRANDING" -> + new BrandingSourceSnapshot(selected, "0", null, GENESIS_RECEIPT, List.of()) + .canonicalBytes(); + default -> throw new IllegalArgumentException("Unsupported source family fixture: " + family); + }; + } + + private static List accountSources() { + return List.of( + source(SourceKind.TENANT, TENANT.toString(), "tenant"), + source(SourceKind.ACCOUNT, ACTOR.toString(), "account"), + source(SourceKind.MEMBERSHIP, ACTOR + "/" + TENANT, "membership")); + } + + private static SourceEvidence source(SourceKind kind, String scope, String marker) { + return new SourceEvidence( + kind, scope, null, "1", null, null, marker.getBytes(StandardCharsets.UTF_8)); + } + + private static DraftCommitBinding selected() { + return DraftCommitBinding.create( + target(), + id("33333333-3333-4333-8333-333333333333"), + id("44444444-4444-4444-8444-444444444444"), + "base-commit-0", + List.of( + new RevisionPayload( + "0", id("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaab"), Owner.WORLD_MANAGEMENT, "{}")), + List.of( + new DraftCommitBinding.AffectedUnit( + Owner.WORLD_MANAGEMENT, "REGION", "region-1", "AGGREGATE", "region-1", "0"))); + } + + private static TargetProof target() { + return new TargetProof(TENANT, VERSION, 23L, "tenant", 42L, "tenant", "NEW_GAME_ROW"); + } + + private static WorldSelectedDraftPublicationFreezeEvidence freezeEvidence( + DraftCommitBinding selected) { + var selection = + AuthoredDraftPublishSelectionBinding.capture( + new PublishIntent( + TENANT, + VERSION, + "publication-request", + "9", + "synthetic selected-owner intake fixture", + selected.requestId(), + selected.commitId(), + selected.digest()), + selected.target(), + selected, + new VisibilityFence( + selected.target(), + selected.requestId(), + selected.commitId(), + selected.digest(), + "[]", + OffsetDateTime.parse("2026-10-01T00:00:00Z"))); + var account = + new AccountPublicationAuthorizationBinding( + id("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + id("ffffffff-ffff-4fff-8fff-ffffffffffff"), + new AccountPublicationAuthorizationBinding.PreallocationInput(ACTOR, selection), + List.of(source(SourceKind.ACCOUNT, ACTOR.toString(), "account-publication"))); + var request = + WorldSelectedDraftPublicationFreezeEvidence.Request.create( + NAMESPACE, + TENANT, + VERSION, + selection.intent().publishRequestId(), + 9, + selection.digest().substring("sha256:".length()), + account); + var acknowledgement = + new Acknowledgement( + request, + id("12121212-1212-4212-8212-121212121212"), + 9, + id("13131313-1313-4313-8313-131313131313"), + OwnerFreezePhase.FROZEN, + selected.commitId().toString(), + "a".repeat(64), + 4); + return WorldSelectedDraftPublicationFreezeGrpcCodec.fromResponse( + request, WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(acknowledgement)); + } + + private static PublicEvidence publicInventory( + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence) { + var request = freezeEvidence.request(); + var acknowledgement = freezeEvidence.acknowledgement(); + var account = request.accountBinding(); + var selection = account.input().selection(); + var selected = selection.selectedCommit(); + var sourceModel = + new SourceModel( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SOURCE_MODEL, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_GRAPH_SCHEMA_VERSION, + "sha256:" + "4".repeat(64), + "sha256:" + "5".repeat(64), + List.of( + new FamilyCount("REGION", 1), + new FamilyCount("ZONE", 1), + new FamilyCount("ROOM", 1), + new FamilyCount("ROOM_EXIT", 1), + new FamilyCount("GENERATION_RULE", 0), + new FamilyCount("WORLD_ENTITY_SPAWN_BINDING", 0)), + List.of(new RegionGeneratorInput(id("15151515-1515-4515-8515-151515151515"), "", "")), + List.of("id", "name", "scopeType", "scopeId", "value"), + List.of( + "id", + "shardId", + "name", + "weather", + "generationSeed", + "generatorType", + "generatorParams", + "spacingMultiplier"), + List.of("id", "regionId", "name"), + List.of( + "id", + "zoneId", + "name", + "description", + "nameLocalizedVariantsJson", + "descriptionLocalizedVariantsJson"), + List.of("id", "fromRoomId", "toRoomId", "direction", "cost"), + List.of( + "id", + "roomId", + "entityTemplateType", + "entityReference.kind", + "entityReference.tenantId", + "entityReference.versionId", + "entityReference.templateId", + "spawnCount", + "respawnDelaySeconds"), + List.of(), + 0, + 0, + selected.affectedUnits(Owner.WORLD_MANAGEMENT).stream() + .map( + unit -> + new AppliedEpoch( + unit.aggregateType(), + unit.aggregateId(), + unit.scopeType(), + unit.scopeId(), + unit.expectedEpoch(), + new BigInteger(unit.expectedEpoch()).add(BigInteger.ONE).toString())) + .toList(), + emptyInboundClosure()); + var ownerScope = + new PublicOwnerScope( + request.targetNamespace(), + TENANT, + VERSION, + id("14141414-1414-4414-8414-141414141414"), + acknowledgement.intakeRequestId(), + id("13131313-1313-4313-8313-131313131313"), + "sha256:" + "1".repeat(64), + id("17171717-1717-4717-8717-171717171717"), + "sha256:" + "2".repeat(64), + "sha256:" + "3".repeat(64)); + return new PublicEvidence( + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA, + WorldSelectedPublicationArtifactInventoryEvidence.INBOUND_CLOSURE_SCHEMA_VERSION, + "COMPLETE", + ownerScope, + new SelectedApplication( + id("16161616-1616-4616-8616-161616161616"), + selected.requestId(), + selected.commitId().toString(), + selected.digest(), + "sha256:" + "6".repeat(64)), + new PublicAccountOrder( + account.operationId(), + account.fenceId(), + account.input().actorAccountId(), + selection.intent().publishRequestId(), + selection.digest(), + selected.commitId().toString(), + DraftAuthorizationFenceBinding.digest(account.canonicalBytes())), + new Freeze( + acknowledgement.publicationFence(), + request.publicationRequestId(), + request.requestDigest(), + Long.toString(acknowledgement.versionStateEpoch()), + PublicationDigestRequestBinding.full( + request.canonicalTenantId().toString(), + Long.toString(selection.target().gameDesignVersionRowId()), + request.publicationRequestId()) + .derivedWorkflowIdentity()), + new Checkpoint(acknowledgement.appliedCommitId(), acknowledgement.contentDigest(), 4), + sourceModel, + List.of( + new ArtifactDecision( + "NAVMESH", "NOT_REQUIRED", "ROOM_LOGICAL_TOPOLOGY_HAS_NO_SPATIAL_NAVMESH_INPUT"), + new ArtifactDecision( + "PATH_GRAPH", + "NOT_REQUIRED", + "AUTHORED_ROOM_EXIT_EDGES_ARE_THE_SUPPORTED_TRAVERSAL_GRAPH"))); + } + + private static InboundSourceClosureDeclaration emptyInboundClosure() { + return new InboundSourceClosureDeclaration( + 1, + List.of( + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ROOT", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_LOOT_REFERENCE_ATTACHMENT", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_SELECTION", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_BEHAVIOR_BINDING", 0), + new InboundSourceFamilyCount("WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_HOOK", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_SCRIPT_REFERENCE", 0), + new InboundSourceFamilyCount( + "WORLD_INBOUND_SOURCE_FAMILY_AUTOMATION_TARGET_BINDING", 0))); + } + + private static void frame(ByteArrayOutputStream out, String value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static void frame(ByteArrayOutputStream out, byte[] value) { + DraftAuthorizationFenceBinding.frame(out, value); + } + + private static UUID id(String value) { + return UUID.fromString(value); + } + + public record Fixture( + SelectedOwnerIntakeAuthorizationBinding authorization, + WorldSelectedDraftPublicationFreezeEvidence freezeEvidence, + SelectedOwnerWorldInventoryReadEvidence worldEvidence, + SelectedOwnerEmptySourceInputs inputs) {} +} diff --git a/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java new file mode 100644 index 0000000000..2dcabe3a54 --- /dev/null +++ b/services/entity-management-service/src/test/java/integration/net/firedevops/firemud/entitymanagement/repository/EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest.java @@ -0,0 +1,702 @@ +package net.firedevops.firemud.entitymanagement.repository; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.ByteArrayOutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Objects; +import java.util.TimeZone; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import net.firedevops.firemud.common.authoring.DraftCommitBinding.Owner; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedEmptyPublicationDigestService; +import net.firedevops.firemud.test.TestContainerImages; +import org.flywaydb.core.Flyway; +import org.flywaydb.database.postgresql.PostgreSQLConfigurationExtension; +import org.jooq.DSLContext; +import org.jooq.ExecuteContext; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.jooq.impl.DefaultExecuteListener; +import org.jooq.impl.DefaultExecuteListenerProvider; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.parallel.ResourceLock; +import org.junit.jupiter.api.parallel.Resources; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +/** Physical PostgreSQL proof for Entity's synthetic-input fresh EMPTY-only retention boundary. */ +@Testcontainers(disabledWithoutDocker = true) +@SuppressWarnings("resource") +class EntityEmptySelectedSourceIntakeRepositoryPostgresIntegrationTest { + private static final String MIGRATION_LOCATION = + "filesystem:" + Path.of("src/main/resources/db/migration").toAbsolutePath().normalize(); + private static final List EMPTY_ONLY_TABLES = + List.of( + "entity_empty_source_actor_body_layout_assignments", + "entity_empty_source_archetype_assignments", + "entity_empty_source_archetype_constraints", + "entity_empty_source_archetype_roots", + "entity_empty_source_balance_curve_attachments", + "entity_empty_source_balance_curve_roots", + "entity_empty_source_equipment_attachment_rules", + "entity_empty_source_equipment_capabilities", + "entity_empty_source_equipment_compatibility_rules", + "entity_empty_source_equipment_occupancy_rules", + "entity_empty_source_inbound_loot_bindings", + "entity_empty_source_loot_item_mappings", + "entity_empty_source_loot_table_roots", + "entity_empty_source_other_actor_template_roots"); + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + private String schema; + private DSLContext dsl; + private EntityEmptySelectedSourceIntakeRepository repository; + + @BeforeEach + void migrateFreshIsolatedSchema() { + schema = "entity_empty_source_repo_" + UUID.randomUUID().toString().replace("-", ""); + DriverManagerDataSource dataSource = dataSource(schema); + var flywayConfiguration = + Flyway.configure() + .dataSource(dataSource) + .locations(MIGRATION_LOCATION, "classpath:db/migration/saga") + .schemas(schema) + .defaultSchema(schema) + .placeholders(Map.of("serviceSchema", schema)); + flywayConfiguration + .getConfigurationExtension(PostgreSQLConfigurationExtension.class) + .setTransactionalLock(false); + flywayConfiguration.load().migrate(); + dsl = DSL.using(dataSource, SQLDialect.POSTGRES); + repository = new EntityEmptySelectedSourceIntakeRepository(dsl); + } + + @AfterEach + void dropIsolatedSchema() { + if (schema != null) { + String checkedSchema = schema.replaceAll("[^a-zA-Z0-9_]", ""); + DSL.using(dataSource(null), SQLDialect.POSTGRES) + .execute("DROP SCHEMA IF EXISTS \"" + checkedSchema + "\" CASCADE"); + schema = null; + } + } + + @Test + @ResourceLock(Resources.TIME_ZONE) + void persistsAllTwentyThreeExplicitEmptyStatesAndReplaysOriginalReceiptBytes() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + var inputs = fixture.inputs(); + assertThat(inputs.ownerSourceInventoryDeclaration().owner()).isEqualTo(Owner.ENTITY_MANAGEMENT); + assertThat( + inputs + .worldInventoryReadEvidence() + .inventory() + .publicEvidence() + .sourceModel() + .inboundSourceClosure() + .familyCounts()) + .allSatisfy(count -> assertThat(count.count()).isZero()); + String requestDigest = requestDigest(fixture); + + TimeZone originalTimeZone = TimeZone.getDefault(); + EntityEmptySelectedSourceIntakeReceipt first; + try { + TimeZone.setDefault(TimeZone.getTimeZone("UTC")); + first = repository.retainFresh(inputs, requestDigest); + } finally { + TimeZone.setDefault(originalTimeZone); + } + assertThat(first.familyStates()) + .hasSize(23) + .allSatisfy( + state -> { + assertThat(state.state()) + .isEqualTo(EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY); + assertThat(state.rowCount()).isZero(); + assertThat(state.referenceCount()).isZero(); + }); + assertThat(first.familyStates()) + .filteredOn( + state -> + state.evidenceKind() + == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind + .EMPTY_ONLY_OWNER_PROVIDER) + .hasSize(14); + assertThat(first.familyStates()) + .filteredOn( + state -> + state.evidenceKind() + == EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS) + .hasSize(9); + assertThat(first.localTenantKey()).isPositive(); + assertThat(first.localVersionKey()).isPositive().isNotEqualTo(first.localTenantKey()); + assertThat(first.authorizationBindingBytes()) + .containsExactly(inputs.authorizationBinding().canonicalBytes()); + assertThat(first.selectedSourceBytes()) + .containsExactly(inputs.sourceContent().canonicalBytes()); + assertThat(first.worldClosureBytes()) + .containsExactly(inputs.worldInventoryReadEvidence().inventory().canonicalBytes()); + + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association")) + .isEqualTo(1L); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_family_state")) + .isEqualTo(23L); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_receipt")).isEqualTo(1L); + for (String table : EMPTY_ONLY_TABLES) { + assertThat(rowCount("SELECT COUNT(*) FROM " + table)).as(table).isEqualTo(1L); + } + EntityEmptySelectedSourceIntakeReceipt readBack; + try { + TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Auckland")); + readBack = repository.read(first.targetNamespace(), first.intakeRequestId()).orElseThrow(); + } finally { + TimeZone.setDefault(originalTimeZone); + } + assertThat(readBack.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(readBack.receiptDigest()).isEqualTo(first.receiptDigest()); + assertThat(readBack.retainedAt().toInstant()).isEqualTo(first.retainedAt().toInstant()); + + assertThatThrownBy( + () -> + dsl.execute( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('blocked', ?, ?)", + first.localTenantKey(), + first.localVersionKey())) + .isInstanceOf(DataAccessException.class); + dsl.execute( + "INSERT INTO items (name, tenant_id, version_id) VALUES ('unassociated', 81001, 81002)"); + assertThat(rowCount("SELECT COUNT(*) FROM items WHERE tenant_id = 81001")).isEqualTo(1L); + + var retry = + EntityEmptySelectedSourceIntakePostgresFixture.withFreshWorldReadCorrelation(fixture); + assertThat(retry.worldEvidence().request().readRequestId()) + .isNotEqualTo(fixture.worldEvidence().request().readRequestId()); + EntityEmptySelectedSourceIntakeReceipt replay; + try { + TimeZone.setDefault(TimeZone.getTimeZone("Pacific/Auckland")); + replay = repository.retainFresh(retry.inputs(), requestDigest(retry)); + } finally { + TimeZone.setDefault(originalTimeZone); + } + assertThat(replay.canonicalBytes()).containsExactly(first.canonicalBytes()); + assertThat(replay.receiptDigest()).isEqualTo(first.receiptDigest()); + assertThat(replay.retainedAt().toInstant()).isEqualTo(first.retainedAt().toInstant()); + assertThat(replay.worldReadRequestId()).isEqualTo(first.worldReadRequestId()); + + var changed = EntityEmptySelectedSourceIntakePostgresFixture.create("2"); + assertThatThrownBy(() -> repository.retainFresh(changed.inputs(), requestDigest(changed))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("different selected evidence"); + assertThat( + repository + .read(first.targetNamespace(), first.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(first.canonicalBytes()); + } + + @Test + void existingGlobalEntityRowsAndReferencesDenyFreshGenesisAndRollBackOwnerRecords() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute("INSERT INTO items (name, tenant_id, version_id) VALUES ('legacy', 72001, 72002)"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not freshly empty"); + assertNoCanonicalOwnerRecords(); + } + + @Test + void multiplePriorScopeOrOperationMatchesProduceTheOwnerConflict() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + var binding = fixture.authorization(); + seedAssociation( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa1"), + UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbb1"), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-ccccccccccc1"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-ddddddddddd1"), + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + EntityEmptySelectedSourceIntakePostgresFixture.VERSION, + 91001L, + 91002L); + seedAssociation( + UUID.fromString("aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaa2"), + binding.operationId(), + UUID.fromString("cccccccc-cccc-4ccc-8ccc-ccccccccccc2"), + UUID.fromString("dddddddd-dddd-4ddd-8ddd-ddddddddddd2"), + UUID.fromString("eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee"), + UUID.fromString("ffffffff-ffff-4fff-8fff-ffffffffffff"), + 91003L, + 91004L); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessage("Entity selected scope or owner operation is already associated"); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association")) + .isEqualTo(2L); + } + + @Test + void selectedEmptyPublicationReaderResolvesOnlyTheValidatedReceiptForTenantAndGameDesignRow() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + long gameDesignVersionRowId = + fixture.authorization().selected().target().gameDesignVersionRowId(); + + assertThat( + repository + .readPublicationScope( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId) + .canonicalBytes()) + .containsExactly(receipt.canonicalBytes()); + assertThatThrownBy( + () -> + repository.readPublicationScope( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId + 1L)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("missing or ambiguous"); + + var digest = + new EntitySelectedEmptyPublicationDigestService( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + fixture.freezeEvidence().request().publicationRequestId())); + assertThat(digest.tenantId()) + .isEqualTo(EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString()); + assertThat(digest.scopeValue()).isEqualTo(Long.toString(gameDesignVersionRowId)); + assertThat(digest.appliedCommitId()).isEqualTo(receipt.selectedCommitId().toString()); + String canonicalInventoryJson = + fixture.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson(); + assertThat(digest.contentDigest()) + .isEqualTo( + expectedSelectedEmptyDigest( + "entity-selected-empty-publication-digest/v1", + "3", + EntityEmptySelectedSourceIntakePostgresFixture.TENANT, + gameDesignVersionRowId, + receipt.canonicalVersionId(), + canonicalInventoryJson)); + assertThat(digest.digestSchemaVersion()) + .isEqualTo(EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION); + + String rowBeforeMismatchedPublicationRead = + dsl.fetchSingle( + "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text " + + "FROM entity_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()) + .get(0, String.class); + assertThatThrownBy( + () -> + new EntitySelectedEmptyPublicationDigestService( + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, repository) + .getDraftDesignDigest( + PublicationDigestRequestBinding.full( + EntityEmptySelectedSourceIntakePostgresFixture.TENANT.toString(), + Long.toString(gameDesignVersionRowId), + "publish-request-2"))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("original retained World freeze"); + String rowAfterMismatchedPublicationRead = + dsl.fetchSingle( + "SELECT encode(receipt_bytes, 'hex') || ':' || xmin::text " + + "FROM entity_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()) + .get(0, String.class); + assertThat(rowAfterMismatchedPublicationRead).isEqualTo(rowBeforeMismatchedPublicationRead); + } + + @Test + void publicationScopeScanAndReceiptReadbackUseOneRepeatableReadSnapshot() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + byte[] concurrentlyCorruptedBytes = receipt.canonicalBytes(); + concurrentlyCorruptedBytes[0] ^= 1; + AtomicBoolean concurrentMutationApplied = new AtomicBoolean(); + dsl.configuration() + .set( + new DefaultExecuteListenerProvider( + new DefaultExecuteListener() { + @Override + public void executeEnd(ExecuteContext context) { + String sql = context.sql(); + if (sql == null + || !sql.toLowerCase(Locale.ROOT) + .contains("from entity_empty_selected_source_association") + || !concurrentMutationApplied.compareAndSet(false, true)) { + return; + } + DSLContext concurrentDsl = DSL.using(dataSource(schema), SQLDialect.POSTGRES); + concurrentDsl.execute( + "ALTER TABLE entity_empty_selected_source_receipt " + + "DISABLE TRIGGER trg_entity_empty_source_receipt_immutable"); + try { + assertThat( + concurrentDsl.execute( + "UPDATE entity_empty_selected_source_receipt " + + "SET receipt_bytes = ? WHERE target_namespace = ? " + + "AND intake_request_id = ?", + concurrentlyCorruptedBytes, + receipt.targetNamespace(), + receipt.intakeRequestId())) + .isEqualTo(1); + } finally { + concurrentDsl.execute( + "ALTER TABLE entity_empty_selected_source_receipt " + + "ENABLE TRIGGER trg_entity_empty_source_receipt_immutable"); + } + } + })); + + EntityEmptySelectedSourceIntakeReceipt read = + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId()); + + assertThat(read.canonicalBytes()).containsExactly(receipt.canonicalBytes()); + assertThat(concurrentMutationApplied).isTrue(); + var storedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes FROM entity_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + assertThat(storedReceipt).isNotNull(); + assertThat(storedReceipt.get(0, byte[].class)).containsExactly(concurrentlyCorruptedBytes); + } + + @Test + void corruptStoredReceiptBytesHaveADistinctRepositoryFailure() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + byte[] corruptBytes = receipt.canonicalBytes(); + corruptBytes[0] ^= 1; + + dsl.execute( + "ALTER TABLE entity_empty_selected_source_receipt " + + "DISABLE TRIGGER trg_entity_empty_source_receipt_immutable"); + try { + assertThat( + dsl.execute( + "UPDATE entity_empty_selected_source_receipt SET receipt_bytes = ? " + + "WHERE target_namespace = ? AND intake_request_id = ?", + corruptBytes, + receipt.targetNamespace(), + receipt.intakeRequestId())) + .isEqualTo(1); + } finally { + dsl.execute( + "ALTER TABLE entity_empty_selected_source_receipt " + + "ENABLE TRIGGER trg_entity_empty_source_receipt_immutable"); + } + + assertThatThrownBy(() -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId())) + .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class) + .hasMessageContaining("Entity stored source receipt is corrupt"); + assertThatThrownBy( + () -> + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId())) + .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); + } + + @Test + void corruptSelectedCommitAndRevisionAssociationFieldsFailReceiptReadback() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + var fields = + List.of( + new AssociationField( + "selected_commit_id", UUID.randomUUID(), receipt.selectedCommitId()), + new AssociationField( + "source_revision_id", UUID.randomUUID(), receipt.sourceRevisionId()), + new AssociationField( + "source_revision_order", + receipt.sourceRevisionOrder().equals("0") ? "1" : "0", + receipt.sourceRevisionOrder())); + byte[] canonicalReceiptBytes = receipt.canonicalBytes(); + + for (AssociationField field : fields) { + updateAssociationField(receipt, field.column(), field.corruptedValue()); + try { + assertThatThrownBy( + () -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId())) + .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class) + .hasMessage("Entity association differs from its immutable receipt"); + } finally { + updateAssociationField(receipt, field.column(), field.receiptValue()); + } + + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association")) + .isEqualTo(1L); + var storedReceipt = + dsl.fetchOne( + "SELECT receipt_bytes FROM entity_empty_selected_source_receipt " + + "WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + assertThat(storedReceipt).isNotNull(); + assertThat(storedReceipt.get(0, byte[].class)).containsExactly(canonicalReceiptBytes); + assertThat( + repository + .read(receipt.targetNamespace(), receipt.intakeRequestId()) + .orElseThrow() + .canonicalBytes()) + .containsExactly(canonicalReceiptBytes); + } + } + + private void updateAssociationField( + EntityEmptySelectedSourceIntakeReceipt receipt, String column, Object value) { + dsl.execute( + "ALTER TABLE entity_empty_selected_source_association " + + "DISABLE TRIGGER trg_entity_empty_source_association_immutable"); + try { + assertThat( + dsl.execute( + "UPDATE entity_empty_selected_source_association SET " + + column + + " = ? WHERE target_namespace = ? AND intake_request_id = ?", + value, + receipt.targetNamespace(), + receipt.intakeRequestId())) + .isEqualTo(1); + } finally { + dsl.execute( + "ALTER TABLE entity_empty_selected_source_association " + + "ENABLE TRIGGER trg_entity_empty_source_association_immutable"); + } + } + + private record AssociationField(String column, Object corruptedValue, Object receiptValue) {} + + @Test + void retainedAuditReferenceWithoutAnItemDeniesFreshGenesis() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute( + "INSERT INTO item_transfer_audits (tenant_id, item_id, quantity, verb, correlation_key, " + + "source_holder_kind, destination_holder_kind) " + + "VALUES (73001, 999999, 1, 'MOVE', 'retained-audit', 'UNKNOWN', 'UNKNOWN')"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("not freshly empty"); + assertNoCanonicalOwnerRecords(); + } + + @Test + void providerWriteFailureRollsBackAssociationKeysAndAllTypedStates() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute( + "ALTER TABLE entity_empty_source_archetype_roots " + + "ADD CONSTRAINT test_force_empty_provider_failure CHECK (FALSE)"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(DataAccessException.class); + assertNoCanonicalOwnerRecords(); + } + + @Test + void absentEmptyOnlyProviderFailsClosedBeforeAnyAssociationIsCommitted() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + dsl.execute("DROP TABLE entity_empty_source_archetype_roots"); + + assertThatThrownBy(() -> repository.retainFresh(fixture.inputs(), requestDigest(fixture))) + .isInstanceOf(DataAccessException.class); + assertNoCanonicalOwnerRecords("entity_empty_source_archetype_roots"); + } + + @Test + void providerConstraintsAndImmutableReadbackRejectUnknownNonemptyOrChangedState() { + var fixture = EntityEmptySelectedSourceIntakePostgresFixture.create("1"); + EntityEmptySelectedSourceIntakeReceipt receipt = + repository.retainFresh(fixture.inputs(), requestDigest(fixture)); + String table = "entity_empty_source_archetype_roots"; + + dsl.execute("ALTER TABLE " + table + " DISABLE TRIGGER USER"); + try { + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + table + " SET row_count = 1 WHERE target_namespace = ?", + receipt.targetNamespace())) + .isInstanceOf(DataAccessException.class); + assertThatThrownBy( + () -> + dsl.execute( + "UPDATE " + table + " SET owner_state = 'UNKNOWN' WHERE target_namespace = ?", + receipt.targetNamespace())) + .isInstanceOf(DataAccessException.class); + dsl.execute( + "DELETE FROM " + table + " WHERE target_namespace = ? AND intake_request_id = ?", + receipt.targetNamespace(), + receipt.intakeRequestId()); + } finally { + dsl.execute("ALTER TABLE " + table + " ENABLE TRIGGER USER"); + } + assertThatThrownBy(() -> repository.read(receipt.targetNamespace(), receipt.intakeRequestId())) + .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class) + .hasMessageContaining("provider readback is missing or differs"); + assertThatThrownBy( + () -> + repository.readPublicationScope( + receipt.targetNamespace(), + receipt.canonicalTenantId(), + fixture.authorization().selected().target().gameDesignVersionRowId())) + .isInstanceOf(EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException.class); + } + + private static String expectedSelectedEmptyDigest( + String domain, + String schemaVersion, + UUID canonicalTenantId, + long gameDesignVersionRowId, + UUID canonicalVersionId, + String canonicalInventoryJson) { + ByteArrayOutputStream preimage = new ByteArrayOutputStream(); + appendDigestSegment(preimage, domain); + appendDigestSegment(preimage, schemaVersion); + appendDigestSegment(preimage, canonicalTenantId.toString()); + appendDigestSegment(preimage, Long.toString(gameDesignVersionRowId)); + appendDigestSegment(preimage, canonicalVersionId.toString()); + appendDigestSegment(preimage, canonicalInventoryJson); + try { + return HexFormat.of() + .formatHex(MessageDigest.getInstance("SHA-256").digest(preimage.toByteArray())); + } catch (NoSuchAlgorithmException impossible) { + throw new AssertionError(impossible); + } + } + + private void seedAssociation( + UUID genesisId, + UUID operationId, + UUID fenceId, + UUID intakeRequestId, + UUID tenantId, + UUID versionId, + long localTenantKey, + long localVersionKey) { + dsl.execute( + "INSERT INTO entity_empty_source_numeric_key_reservation " + + "(key_kind, numeric_key, claim_kind) VALUES " + + "('TENANT', ?, 'CANONICAL_EMPTY_SOURCE'), " + + "('VERSION', ?, 'CANONICAL_EMPTY_SOURCE')", + localTenantKey, + localVersionKey); + String digest = "sha256:" + "a".repeat(64); + dsl.execute( + "INSERT INTO entity_empty_selected_source_association " + + "(target_namespace, genesis_id, operation_id, fence_id, intake_request_id, " + + "canonical_tenant_id, canonical_version_id, selected_commit_id, " + + "source_revision_id, source_revision_order, local_tenant_key, local_version_key, " + + "request_digest, schema_digest, authorization_binding_digest, " + + "selected_source_digest, world_read_request_id, world_read_request_digest, " + + "world_closure_digest, receipt_digest, associated_at) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, '0', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, " + + "CURRENT_TIMESTAMP)", + EntityEmptySelectedSourceIntakePostgresFixture.NAMESPACE, + genesisId, + operationId, + fenceId, + intakeRequestId, + tenantId, + versionId, + UUID.fromString("12121212-1212-4212-8212-121212121212"), + UUID.fromString("13131313-1313-4313-8313-131313131313"), + localTenantKey, + localVersionKey, + digest, + digest, + digest, + digest, + UUID.fromString("14141414-1414-4414-8414-141414141414"), + digest, + digest, + digest); + } + + private static void appendDigestSegment(ByteArrayOutputStream output, String value) { + byte[] bytes = value.getBytes(StandardCharsets.UTF_8); + output.writeBytes(Integer.toString(bytes.length).getBytes(StandardCharsets.US_ASCII)); + output.write(':'); + output.writeBytes(bytes); + } + + private String requestDigest(EntityEmptySelectedSourceIntakePostgresFixture.Fixture fixture) { + return EntityEmptySelectedSourceIntakeReceipt.requestDigest( + fixture.authorization().targetNamespace(), + fixture.authorization(), + fixture.freezeEvidence()); + } + + private long rowCount(String sql) { + var row = Objects.requireNonNull(dsl.fetchOne(sql), "count query returned no row"); + return Objects.requireNonNull(row.get(0, Long.class), "count query returned no value"); + } + + private void assertNoCanonicalOwnerRecords(String... unavailableProviderTables) { + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_association")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_family_state")).isZero(); + assertThat(rowCount("SELECT COUNT(*) FROM entity_empty_selected_source_receipt")).isZero(); + assertThat( + rowCount( + "SELECT COUNT(*) FROM entity_empty_source_numeric_key_reservation " + + "WHERE claim_kind = 'CANONICAL_EMPTY_SOURCE'")) + .isZero(); + for (String table : EMPTY_ONLY_TABLES) { + if (List.of(unavailableProviderTables).contains(table)) continue; + assertThat(rowCount("SELECT COUNT(*) FROM " + table)).as(table).isZero(); + } + } + + private DriverManagerDataSource dataSource(String schemaName) { + DriverManagerDataSource dataSource = new DriverManagerDataSource(); + dataSource.setDriverClassName(postgres.getDriverClassName()); + String baseUrl = postgres.getJdbcUrl(); + dataSource.setUrl( + schemaName == null + ? baseUrl + : baseUrl + (baseUrl.contains("?") ? "&" : "?") + "currentSchema=" + schemaName); + dataSource.setUsername(postgres.getUsername()); + dataSource.setPassword(postgres.getPassword()); + return dataSource; + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java new file mode 100644 index 0000000000..725aced55d --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeRepositoryTest.java @@ -0,0 +1,89 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import org.junit.jupiter.api.Test; + +class EntityEmptySelectedSourceIntakeRepositoryTest { + @Test + void recognizesAllFourteenExplicitFreshEmptyOwnerProviders() { + for (String family : + java.util.List.of( + "ACTOR_BODY_LAYOUT_ASSIGNMENTS", + "ARCHETYPE_ASSIGNMENTS", + "ARCHETYPE_CONSTRAINTS", + "ARCHETYPE_ROOTS", + "BALANCE_CURVE_ATTACHMENTS", + "BALANCE_CURVE_ROOTS", + "EQUIPMENT_ATTACHMENT_RULES", + "EQUIPMENT_CAPABILITIES", + "EQUIPMENT_COMPATIBILITY_RULES", + "EQUIPMENT_OCCUPANCY_RULES", + "INBOUND_LOOT_BINDINGS", + "LOOT_ITEM_MAPPINGS", + "LOOT_TABLE_ROOTS", + "OTHER_ACTOR_TEMPLATE_ROOTS")) { + EntityEmptySelectedSourceIntakeRepository.requireReadableProvider(family); + } + } + + @Test + void recognizesAllNineExistingV1CensusFamilies() { + for (String family : + java.util.List.of( + "ITEM_TEMPLATE_ROOTS", + "NPC_TEMPLATE_ROOTS", + "CRAFTING_RECIPE_ROOTS", + "CRAFTING_RECIPE_RESULT_BINDINGS", + "CRAFTING_INGREDIENT_BINDINGS", + "EQUIPMENT_SLOT_ROOTS", + "EQUIPMENT_SLOT_GROUPS", + "BODY_LAYOUT_ROOTS", + "BODY_LAYOUT_MEMBERSHIPS")) { + EntityEmptySelectedSourceIntakeRepository.requireReadableProvider(family); + } + } + + @Test + void rejectsFamiliesWithNoDeclaredOwnerProvider() { + assertThatThrownBy( + () -> EntityEmptySelectedSourceIntakeRepository.requireReadableProvider("UNKNOWN")) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No readable persisted Entity source provider"); + } + + @Test + void anEmptyFamilyStateCannotCarryRowsOrReferences() { + assertThrows( + IllegalArgumentException.class, + () -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + "ITEM_TEMPLATE_ROOTS", + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, + 0L, + 0L, + 0L, + 0L, + 1L)); + } + + @Test + void rejectsEvidenceKindThatDoesNotMatchFamilyProvider() { + assertThatThrownBy( + () -> + new EntityEmptySelectedSourceIntakeReceipt.FamilyCensus( + "ARCHETYPE_ROOTS", + EntityEmptySelectedSourceIntakeReceipt.FamilyState.EMPTY, + EntityEmptySelectedSourceIntakeReceipt.FamilyEvidenceKind.V1_SOURCE_CENSUS, + 0L, + 0L, + 0L, + 0L, + 0L)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("evidence kind differs"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java new file mode 100644 index 0000000000..8e95b351e4 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityEmptySelectedSourceIntakeServiceTest.java @@ -0,0 +1,47 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationReadClient; +import net.firedevops.firemud.common.publication.SelectedOwnerWorldInventoryReadClient; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; + +class EntityEmptySelectedSourceIntakeServiceTest { + @Test + void rejectsCallerSelectedNamespaceBeforeReceiptReplayOrRemoteReads() { + DSLContext dsl = mock(DSLContext.class); + SelectedOwnerIntakeAuthorizationReadClient authorizationClient = + mock(SelectedOwnerIntakeAuthorizationReadClient.class); + SelectedOwnerWorldInventoryReadClient worldClient = + mock(SelectedOwnerWorldInventoryReadClient.class); + var service = + new EntityEmptySelectedSourceIntakeService( + "configured", + new EntityEmptySelectedSourceIntakeRepository(dsl), + authorizationClient, + worldClient); + + assertThatThrownBy(() -> service.retain("attacker-selected", null, null)) + .isInstanceOf(SecurityException.class) + .hasMessageContaining("configured Entity owner namespace"); + + verifyNoInteractions(dsl, authorizationClient, worldClient); + } + + @Test + void rejectsInvalidConfiguredNamespaceAtConstruction() { + DSLContext dsl = mock(DSLContext.class); + assertThatThrownBy( + () -> + new EntityEmptySelectedSourceIntakeService( + "Invalid_Namespace", + new EntityEmptySelectedSourceIntakeRepository(dsl), + mock(SelectedOwnerIntakeAuthorizationReadClient.class), + mock(SelectedOwnerWorldInventoryReadClient.class))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Configured Entity namespace"); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java new file mode 100644 index 0000000000..de9f583b39 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntityRetainedAuthoredActorCoreSourceServiceTest.java @@ -0,0 +1,264 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.UUID; +import net.firedevops.firemud.common.entity.sourceintake.EntityEmptySelectedSourceIntakeReceipt; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreProjection; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadClient; +import net.firedevops.firemud.common.gamedesign.AuthoredInitialActorCoreReadEvidence; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Association; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.ExactReplay; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Request; +import net.firedevops.firemud.common.gamedesign.StartSessionTemplateAssociationReadEvidence.Result; +import net.firedevops.firemud.common.publication.WorldSelectedPublicationArtifactInventoryEvidence.PublicOwnerScope; +import net.firedevops.firemud.common.tenant.WorldAuthoredSourceIntakeGrpcCodec.PublicReceipt; +import net.firedevops.firemud.gamedesign.v1.ParticipantDigest; +import net.firedevops.firemud.gamedesign.v1.PublishedReleaseBundle; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.junit.jupiter.api.Test; + +class EntityRetainedAuthoredActorCoreSourceServiceTest { + private static final String NAMESPACE = "test"; + private static final String WORKFLOW = "selected-publish-workflow"; + private static final String WORLD_SLUG = "retained-world"; + private static final String ASSOCIATION_DIGEST = "sha256:" + "a".repeat(64); + + @Test + void exactRetryReturnsUnchangedDirectResultAfterIndependentOwnerSnapshotRead() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenReturn(setup.result()); + when(repository.readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId())) + .thenReturn(fixture.receipt()); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + var first = service.read(setup.request()); + var retry = service.read(setup.request()); + + assertThat(first).isSameAs(setup.result()); + assertThat(retry).isSameAs(setup.result()); + var inOrder = inOrder(client, repository); + inOrder.verify(client).read(setup.request()); + inOrder + .verify(repository) + .readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId()); + inOrder.verify(client).read(setup.request()); + inOrder + .verify(repository) + .readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId()); + verifyNoMoreInteractions(client, repository); + } + + @Test + void deniesAReadResultThatSubstitutesTheOriginalOperationBeforeEntitySql() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + var substituted = mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); + when(substituted.request()).thenReturn(mock(Request.class)); + when(client.read(setup.request())).thenReturn(substituted); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact original request"); + + verify(client).read(setup.request()); + verifyNoInteractions(repository); + } + + @Test + void deniesMixedProjectionSourceEvenWhenTheEntityReleaseDigestMatches() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + when(setup.projection().worldSourceOperationId()).thenReturn(UUID.randomUUID()); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenReturn(setup.result()); + when(repository.readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId())) + .thenReturn(fixture.receipt()); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("exact retained source"); + } + + @Test + void deniesReleaseWithDifferentImmutableEntityRecipientDigest() { + Fixture fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + ReadSetup setup = readSetup(fixture); + PublishedReleaseBundle changedRelease = + setup.release().toBuilder() + .clearParticipantDigests() + .addParticipantDigests(entityParticipant(fixture.receipt(), "0".repeat(64))) + .build(); + when(setup.associationRead().releaseBundle()).thenReturn(changedRelease); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenReturn(setup.result()); + when(repository.readPublicationScope( + NAMESPACE, + fixture.receipt().canonicalTenantId(), + fixture.receipt().authorizationBinding().selected().target().gameDesignVersionRowId())) + .thenReturn(fixture.receipt()); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("release Entity digest"); + } + + @Test + void deniesUnavailableAuthenticatedGameDesignEvidenceWithoutLocalRead() { + ReadSetup setup = readSetup(EntitySelectedSourceIntakeTerminalReadFixtures.create()); + AuthoredInitialActorCoreReadClient client = mock(AuthoredInitialActorCoreReadClient.class); + EntityEmptySelectedSourceIntakeRepository repository = + mock(EntityEmptySelectedSourceIntakeRepository.class); + when(client.read(setup.request())).thenThrow(new IllegalStateException("read unavailable")); + var service = new EntityRetainedAuthoredActorCoreSourceService(NAMESPACE, client, repository); + + assertThatThrownBy(() -> service.read(setup.request())) + .isInstanceOf(IllegalStateException.class) + .hasMessage("read unavailable"); + + verifyNoInteractions(repository); + } + + private static ReadSetup readSetup(Fixture fixture) { + EntityEmptySelectedSourceIntakeReceipt receipt = fixture.receipt(); + ExactReplay replay = + new ExactReplay( + receipt.canonicalVersionId(), receipt.selectedCommitId(), WORKFLOW, ASSOCIATION_DIGEST); + Request originalRequest = mock(Request.class); + when(originalRequest.targetNamespace()).thenReturn(NAMESPACE); + when(originalRequest.selection()).thenReturn(replay); + var request = new AuthoredInitialActorCoreReadEvidence.ReadRequest(originalRequest); + + PublicOwnerScope worldOwner = + receipt.inputs().worldInventoryReadEvidence().inventory().publicEvidence().ownerScope(); + Association association = mock(Association.class); + when(association.canonicalTenantId()).thenReturn(receipt.canonicalTenantId()); + when(association.canonicalVersionId()).thenReturn(receipt.canonicalVersionId()); + when(association.selectedCommitId()).thenReturn(receipt.selectedCommitId()); + when(association.publishWorkflowId()).thenReturn(WORKFLOW); + when(association.associationDigest()).thenReturn(ASSOCIATION_DIGEST); + when(association.targetNamespace()).thenReturn(NAMESPACE); + when(association.intakeRequestId()).thenReturn(worldOwner.intakeRequestId()); + when(association.worldOperationId()).thenReturn(worldOwner.intakeOperationId()); + when(association.publicationSelectionDigest()) + .thenReturn( + receipt + .inputs() + .worldInventoryReadEvidence() + .request() + .freezeEvidence() + .request() + .accountBinding() + .input() + .selection() + .digest()); + when(association.sourceOperationId()).thenReturn(worldOwner.sourceOperationId()); + when(association.sourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest()); + when(association.worldSlug()).thenReturn(WORLD_SLUG); + PublicReceipt worldReceipt = mock(PublicReceipt.class); + when(worldReceipt.targetNamespace()).thenReturn(worldOwner.targetNamespace()); + when(worldReceipt.canonicalTenantId()).thenReturn(worldOwner.canonicalTenantId()); + when(worldReceipt.intakeRequestId()).thenReturn(worldOwner.intakeRequestId()); + when(worldReceipt.operationId()).thenReturn(worldOwner.intakeOperationId()); + when(worldReceipt.sourceOperationId()).thenReturn(worldOwner.sourceOperationId()); + when(worldReceipt.sourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest()); + when(worldReceipt.receiptDigest()).thenReturn(worldOwner.intakeReceiptDigest()); + when(association.worldReceipt()).thenReturn(worldReceipt); + + ParticipantDigest entityParticipant = entityParticipant(receipt, null); + PublishedReleaseBundle release = + PublishedReleaseBundle.newBuilder() + .setVersionId( + receipt.authorizationBinding().selected().target().gameDesignVersionRowId()) + .setAttestationSchemaVersion("v4") + .setPublishWorkflowId(WORKFLOW) + .setCanonicalTenantId(receipt.canonicalTenantId().toString()) + .setCanonicalVersionId(receipt.canonicalVersionId().toString()) + .addParticipantDigests(entityParticipant) + .build(); + Result associationRead = mock(Result.class); + when(associationRead.request()).thenReturn(originalRequest); + when(associationRead.association()).thenReturn(association); + when(associationRead.releaseBundle()).thenReturn(release); + + AuthoredInitialActorCoreProjection projection = mock(AuthoredInitialActorCoreProjection.class); + when(projection.canonicalTenantId()).thenReturn(receipt.canonicalTenantId()); + when(projection.canonicalVersionId()).thenReturn(receipt.canonicalVersionId()); + when(projection.selectedCommitId()).thenReturn(receipt.selectedCommitId()); + when(projection.selectedCommitDigest()) + .thenReturn(receipt.authorizationBinding().selected().digest()); + when(projection.worldSourceOperationId()).thenReturn(worldOwner.sourceOperationId()); + when(projection.worldSourceEvidenceDigest()).thenReturn(worldOwner.sourceEvidenceDigest()); + when(projection.worldSlug()).thenReturn(WORLD_SLUG); + when(projection.publicationWorkflowId()).thenReturn(WORKFLOW); + + AuthoredInitialActorCoreReadEvidence.ReadResult result = + mock(AuthoredInitialActorCoreReadEvidence.ReadResult.class); + when(result.request()).thenReturn(originalRequest); + when(result.associationRead()).thenReturn(associationRead); + when(result.projections()).thenReturn(List.of(projection)); + return new ReadSetup(request, result, associationRead, release, projection); + } + + private static ParticipantDigest entityParticipant( + EntityEmptySelectedSourceIntakeReceipt receipt, String replacementDigest) { + var target = receipt.authorizationBinding().selected().target(); + String inventoryJson = + receipt.inputs().ownerSourceInventoryDeclaration().entityInventory().canonicalJson(); + String contentDigest = + EntitySelectedEmptyPublicationDigestService.contentDigest( + receipt.canonicalTenantId(), + target.gameDesignVersionRowId(), + receipt.canonicalVersionId(), + inventoryJson); + return ParticipantDigest.newBuilder() + .setParticipantKey("ENTITY_MANAGEMENT") + .setScopeValue(Long.toString(target.gameDesignVersionRowId())) + .setAppliedCommitId(receipt.selectedCommitId().toString()) + .setContentDigest(replacementDigest == null ? contentDigest : replacementDigest) + .setDigestSchemaVersion(EntitySelectedEmptyPublicationDigestService.DIGEST_SCHEMA_VERSION) + .build(); + } + + private record ReadSetup( + AuthoredInitialActorCoreReadEvidence.ReadRequest request, + AuthoredInitialActorCoreReadEvidence.ReadResult result, + Result associationRead, + PublishedReleaseBundle release, + AuthoredInitialActorCoreProjection projection) {} +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java new file mode 100644 index 0000000000..9959bc29fa --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedEmptyPublicationDigestGrpcReceiverTest.java @@ -0,0 +1,171 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; + +import io.grpc.Context; +import io.grpc.stub.StreamObserver; +import io.micrometer.core.instrument.simple.SimpleMeterRegistry; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.PublicationDigestRequestBinding; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.service.EntityDraftDesignDigestService.EntityDraftDesignDigest; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestRequest; +import net.firedevops.firemud.entitymanagement.v1.GetDraftDesignDigestResponse; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class EntitySelectedEmptyPublicationDigestGrpcReceiverTest { + private static final String NAMESPACE = "test"; + private static final String TENANT = "11111111-1111-4111-8111-111111111111"; + private static final String VERSION_ROW = "23"; + + @AfterEach + void clearSessionContext() { + SessionContext.clear(); + } + + @Test + void exactGameDesignPeerWithoutSessionContextCanReadValidatedFullVersionBinding() { + SessionContext.clear(); + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"); + Mockito.when(digestService.getDraftDesignDigest(any(PublicationDigestRequestBinding.class))) + .thenReturn( + new EntityDraftDesignDigest(TENANT, VERSION_ROW, "selected-commit", "a".repeat(64), 3)); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, request(binding)); + + assertEquals("", response.getError().getCode()); + assertEquals(TENANT, response.getTenantId()); + assertEquals(VERSION_ROW, response.getVersionId()); + assertEquals("selected-commit", response.getAppliedCommitId()); + assertEquals("a".repeat(64), response.getContentDigest()); + assertEquals(3, response.getDigestSchemaVersion()); + verify(digestService).getDraftDesignDigest(any(PublicationDigestRequestBinding.class)); + } + + @Test + void accountOrGlobalOrScopedRoleContextDeniesEvenTheExactGameDesignPeer() { + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + List deniedContexts = + List.of( + () -> SessionContext.setContext("user-1", List.of("player"), Map.of()), + () -> SessionContext.setContext(null, List.of("platformAdmin"), Map.of()), + () -> + SessionContext.setContext( + null, List.of(), Map.of("tenant-1", List.of("designer")))); + for (Runnable setDeniedContext : deniedContexts) { + SessionContext.clear(); + setDeniedContext.run(); + GetDraftDesignDigestResponse response = + invokeAsGameDesign( + receiver, + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7"))); + assertEquals("PERMISSION_DENIED", response.getError().getCode()); + } + verifyNoInteractions(digestService); + } + + @Test + void changedCompleteRequestBindingIsRejectedBeforeReceiptLookup() { + SessionContext.clear(); + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + GetDraftDesignDigestRequest changedRequest = + request(PublicationDigestRequestBinding.full(TENANT, VERSION_ROW, "request-7")).toBuilder() + .setRequestDigest("0".repeat(64)) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, changedRequest); + + assertEquals("INVALID_ARGUMENT", response.getError().getCode()); + verifyNoInteractions(digestService); + } + + @Test + void scriptPatchScopeReturnsUnsupportedBeforeDigestServiceInteraction() { + SessionContext.clear(); + EntitySelectedEmptyPublicationDigestService digestService = + Mockito.mock(EntitySelectedEmptyPublicationDigestService.class); + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver = + new EntitySelectedEmptyPublicationDigestGrpcReceiver( + digestService, NAMESPACE, new SimpleMeterRegistry()); + PublicationDigestRequestBinding binding = + PublicationDigestRequestBinding.patch(TENANT, VERSION_ROW, "patch:1", "request-7"); + GetDraftDesignDigestRequest patchRequest = + GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setBaseVersionId(binding.baseVersionId()) + .setScriptPatchVersion(binding.scriptPatchVersion()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + + GetDraftDesignDigestResponse response = invokeAsGameDesign(receiver, patchRequest); + + assertEquals("UNSUPPORTED_SCOPE", response.getError().getCode()); + verifyNoInteractions(digestService); + } + + private static GetDraftDesignDigestRequest request(PublicationDigestRequestBinding binding) { + return GetDraftDesignDigestRequest.newBuilder() + .setTenantId(binding.tenantId()) + .setVersionId(binding.versionId()) + .setPublishRequestId(binding.publishRequestId()) + .setDerivedWorkflowIdentity(binding.derivedWorkflowIdentity()) + .setRequestDigest(binding.requestDigest()) + .build(); + } + + private static GetDraftDesignDigestResponse invokeAsGameDesign( + EntitySelectedEmptyPublicationDigestGrpcReceiver receiver, + GetDraftDesignDigestRequest request) { + AtomicReference response = new AtomicReference<>(); + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")) + .run( + () -> + receiver.getDraftDesignDigest( + request, + new StreamObserver<>() { + @Override + public void onNext(GetDraftDesignDigestResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + throw new AssertionError(error); + } + + @Override + public void onCompleted() {} + })); + return response.get(); + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java new file mode 100644 index 0000000000..fc3c6d4885 --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeCommandGrpcServiceTest.java @@ -0,0 +1,298 @@ +package unit.net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +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.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding; +import net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationProducerCredentials; +import net.firedevops.firemud.common.authoring.AccountOriginalDraftOrderCredentials; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeCommandGrpcCodec; +import net.firedevops.firemud.common.gamelogic.AccountGameLogicIntakeAuthorizationCredentials; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeEvidence; +import net.firedevops.firemud.common.publication.WorldSelectedDraftPublicationFreezeGrpcCodec; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeRepository; +import net.firedevops.firemud.entitymanagement.sourceintake.EntityEmptySelectedSourceIntakeService; +import net.firedevops.firemud.entitymanagement.sourceintake.EntitySelectedSourceIntakeCommandGrpcService; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceRequest; +import net.firedevops.firemud.entitymanagement.v1.RetainSelectedEntitySourceResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Mocked owner tests verify gates and delegation, not native producer or physical census proof. */ +class EntitySelectedSourceIntakeCommandGrpcServiceTest { + private static final String NAMESPACE = "test"; + private static final String GAME_DESIGN_URI = "spiffe://firemud/ns/test/sa/game-design-service"; + private static Fixture fixture; + + @BeforeAll + static void createSyntheticEntityInputs() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @BeforeEach + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void authenticatedGameDesignGetsExactRetainedReceiptFromOwner() { + var owner = mock(EntityEmptySelectedSourceIntakeService.class); + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var request = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, fixture.authorization(), freeze); + when(owner.retain( + eq(NAMESPACE), + any(SelectedOwnerIntakeAuthorizationBinding.class), + any(WorldSelectedDraftPublicationFreezeEvidence.class))) + .thenReturn(fixture.receipt()); + var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var observedResponse = new AtomicReference(); + var observer = new CapturingObserver(observedResponse); + var accountContext = gameDesignPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + service.retainSelectedEntitySource( + EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request), observer); + } finally { + accountContext.detach(previous); + } + + assertThat(observer.failure()).isNull(); + assertThat(observedResponse.get()).isNotNull(); + assertThat(observedResponse.get().getRequest()) + .isEqualTo(EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(request)); + var evidence = + EntitySelectedSourceIntakeCommandGrpcCodec.fromResponse(request, observedResponse.get()); + assertThat(evidence.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + var authorizationArgument = + ArgumentCaptor.forClass(SelectedOwnerIntakeAuthorizationBinding.class); + var freezeArgument = ArgumentCaptor.forClass(WorldSelectedDraftPublicationFreezeEvidence.class); + verify(owner).retain(eq(NAMESPACE), authorizationArgument.capture(), freezeArgument.capture()); + assertThat(authorizationArgument.getValue().canonicalBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + assertThat( + WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest( + freezeArgument.getValue().request())) + .isEqualTo(WorldSelectedDraftPublicationFreezeGrpcCodec.toRequest(freeze.request())); + assertThat( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse( + freezeArgument.getValue().acknowledgement())) + .isEqualTo( + WorldSelectedDraftPublicationFreezeGrpcCodec.toResponse(freeze.acknowledgement())); + } + + @Test + void rejectsMissingWrongPeerAndWrongNamespaceBeforeDecodeOrOwnerInvocation() { + var owner = mock(EntityEmptySelectedSourceIntakeService.class); + var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + + var missingPeer = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource( + RetainSelectedEntitySourceRequest.getDefaultInstance(), missingPeer); + assertCode(missingPeer.failure(), Status.Code.UNAUTHENTICATED); + + var wrongPeer = gameDesignPeer("other"); + var previous = wrongPeer.attach(); + try { + var denied = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource( + RetainSelectedEntitySourceRequest.getDefaultInstance(), denied); + assertCode(denied.failure(), Status.Code.PERMISSION_DENIED); + } finally { + wrongPeer.detach(previous); + } + + var goodPeer = gameDesignPeer(NAMESPACE); + previous = goodPeer.attach(); + try { + var mismatchedTarget = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource( + RetainSelectedEntitySourceRequest.newBuilder().setTargetNamespace("other").build(), + mismatchedTarget); + assertCode(mismatchedTarget.failure(), Status.Code.PERMISSION_DENIED); + } finally { + goodPeer.detach(previous); + } + verifyNoInteractions(owner); + } + + @Test + void rejectsEndUserSelectedOrderAndAmbientSqlBeforeMalformedEvidenceDecode() { + var owner = mock(EntityEmptySelectedSourceIntakeService.class); + var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var peer = gameDesignPeer(NAMESPACE); + var malformed = RetainSelectedEntitySourceRequest.getDefaultInstance(); + var previous = peer.attach(); + try { + SessionContext.setContext("101", List.of(), Map.of()); + var endUser = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformed, endUser); + assertCode(endUser.failure(), Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + for (Context credentialContext : + List.of( + Context.current() + .withValue( + AccountOriginalDraftOrderCredentials.CONTEXT_KEY, + AccountOriginalDraftOrderCredentials.Credential.of( + "synthetic-original-order")), + Context.current() + .withValue( + SelectedOwnerIntakeAuthorizationProducerCredentials.CONTEXT_KEY, + SelectedOwnerIntakeAuthorizationProducerCredentials.Credential.of( + "synthetic-owner-intake")), + Context.current() + .withValue( + AccountGameLogicIntakeAuthorizationCredentials.CONTEXT_KEY, + AccountGameLogicIntakeAuthorizationCredentials.Credential.of( + "synthetic-logic-intake")))) { + var credentialPrevious = credentialContext.attach(); + try { + var denied = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformed, denied); + assertCode(denied.failure(), Status.Code.PERMISSION_DENIED); + } finally { + credentialContext.detach(credentialPrevious); + } + } + + var malformedEvidence = + RetainSelectedEntitySourceRequest.newBuilder().setTargetNamespace(NAMESPACE).build(); + TransactionSynchronizationManager.setActualTransactionActive(true); + var activeSql = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformedEvidence, activeSql); + assertCode(activeSql.failure(), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clear(); + + TransactionSynchronizationManager.initSynchronization(); + var synchronizedSql = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformedEvidence, synchronizedSql); + assertCode(synchronizedSql.failure(), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clear(); + + var invalidEvidence = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(malformedEvidence, invalidEvidence); + assertCode(invalidEvidence.failure(), Status.Code.INVALID_ARGUMENT); + } finally { + peer.detach(previous); + } + verifyNoInteractions(owner); + } + + @Test + void mapsStorageCorruptionOutagesAndRemoteEchoFailuresToSanitizedStatuses() { + var freeze = fixture.inputs().worldInventoryReadEvidence().request().freezeEvidence(); + var command = + EntitySelectedSourceIntakeCommandEvidence.Request.create( + NAMESPACE, fixture.authorization(), freeze); + var wire = EntitySelectedSourceIntakeCommandGrpcCodec.toRequest(command); + var peer = gameDesignPeer(NAMESPACE); + var previous = peer.attach(); + try { + assertFailure(new DataAccessException("private jOOQ details"), wire, Status.Code.UNAVAILABLE); + assertFailure( + new DataAccessResourceFailureException("private Spring details"), + wire, + Status.Code.UNAVAILABLE); + assertFailure( + new EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException( + "private receipt details"), + wire, + Status.Code.DATA_LOSS); + assertFailure( + new EntityEmptySelectedSourceIntakeRepository.IntakeConflictException( + "private intake conflict details"), + wire, + Status.Code.ALREADY_EXISTS); + assertFailure( + new IllegalStateException("private Account or World echo details"), + wire, + Status.Code.FAILED_PRECONDITION); + } finally { + peer.detach(previous); + } + } + + private static void assertFailure( + RuntimeException failure, + RetainSelectedEntitySourceRequest request, + Status.Code expectedCode) { + var owner = mock(EntityEmptySelectedSourceIntakeService.class); + org.mockito.Mockito.doThrow(failure).when(owner).retain(any(), any(), any()); + var service = new EntitySelectedSourceIntakeCommandGrpcService(owner, NAMESPACE); + var observer = new CapturingObserver(new AtomicReference<>()); + service.retainSelectedEntitySource(request, observer); + + assertThat(observer.failure()).isInstanceOf(StatusRuntimeException.class); + assertThat(Status.fromThrowable(observer.failure()).getCode()).isEqualTo(expectedCode); + var status = (StatusRuntimeException) observer.failure(); + assertThat(status.getStatus().getDescription()).isNull(); + assertThat(status.getCause()).isNull(); + assertThat(status.getTrailers()).isNull(); + } + + private static void assertCode(Throwable error, Status.Code expected) { + assertThat(error).isNotNull(); + assertThat(Status.fromThrowable(error).getCode()).isEqualTo(expected); + } + + private static Context gameDesignPeer(String namespace) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/game-design-service"; + return Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, "game-design-service")); + } + + private static final class CapturingObserver + implements StreamObserver { + private final AtomicReference response; + private final AtomicReference failure = new AtomicReference<>(); + + private CapturingObserver(AtomicReference response) { + this.response = response; + } + + @Override + public void onNext(RetainSelectedEntitySourceResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable error) { + failure.set(error); + } + + @Override + public void onCompleted() {} + + Throwable failure() { + return failure.get(); + } + } +} diff --git a/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java new file mode 100644 index 0000000000..a3e59f65ab --- /dev/null +++ b/services/entity-management-service/src/test/java/unit/net/firedevops/firemud/entitymanagement/sourceintake/EntitySelectedSourceIntakeTerminalReadServiceTest.java @@ -0,0 +1,343 @@ +package net.firedevops.firemud.entitymanagement.sourceintake; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import io.grpc.Context; +import io.grpc.Status; +import io.grpc.StatusRuntimeException; +import io.grpc.stub.StreamObserver; +import java.util.Optional; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadEvidence; +import net.firedevops.firemud.common.entity.sourceintake.EntitySelectedSourceIntakeTerminalReadGrpcCodec; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import net.firedevops.firemud.common.security.SessionContext; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalRequest; +import net.firedevops.firemud.entitymanagement.v1.ReadSelectedSourceIntakeTerminalResponse; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures; +import net.firedevops.firemud.testsupport.entity.EntitySelectedSourceIntakeTerminalReadFixtures.Fixture; +import org.jooq.exception.DataAccessException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.transaction.support.TransactionSynchronizationManager; + +/** Synthetic receipt/peer tests do not establish Entity producer or database proof. */ +class EntitySelectedSourceIntakeTerminalReadServiceTest { + private static final String NAMESPACE = "test"; + private static Fixture fixture; + + @BeforeAll + static void createSyntheticReceiptFixture() { + fixture = EntitySelectedSourceIntakeTerminalReadFixtures.create(); + } + + @BeforeEach + @AfterEach + void clearContexts() { + SessionContext.clear(); + TransactionSynchronizationManager.clear(); + } + + @Test + void exactRetriesReadOnlyTheCommittedReceiptAndUseDistinctReadCorrelations() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var binding = fixture.authorization(); + when(repository.read(NAMESPACE, binding.intakeRequestId())) + .thenReturn(Optional.of(fixture.receipt())); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + var first = service.read(request(binding)); + var retry = service.read(request(binding)); + + assertThat(first.receipt()).isSameAs(fixture.receipt()); + assertThat(retry.receipt()).isSameAs(fixture.receipt()); + assertThat(first.request().readRequestId()).isNotEqualTo(retry.request().readRequestId()); + assertThat(first.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + verify(repository, times(2)).read(NAMESPACE, binding.intakeRequestId()); + } finally { + accountContext.detach(previous); + } + } + + @Test + void grpcReturnsTheExactFullReceiptWithoutRemintingIt() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var binding = fixture.authorization(); + when(repository.read(NAMESPACE, binding.intakeRequestId())) + .thenReturn(Optional.of(fixture.receipt())); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var grpc = new EntitySelectedSourceIntakeTerminalReadGrpcService(service); + var request = request(binding); + var observedResponse = new AtomicReference(); + var observedError = new AtomicReference(); + var observer = responseObserver(observedResponse, observedError); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + grpc.readSelectedSourceIntakeTerminal( + EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request), observer); + } finally { + accountContext.detach(previous); + } + + assertThat(observedError.get()).isNull(); + var response = observedResponse.get(); + assertThat(response).isNotNull(); + assertThat(response.getRequest()) + .isEqualTo(EntitySelectedSourceIntakeTerminalReadGrpcCodec.toRequest(request)); + var decoded = EntitySelectedSourceIntakeTerminalReadGrpcCodec.fromResponse(request, response); + assertThat(decoded.receipt().canonicalBytes()).isEqualTo(fixture.receipt().canonicalBytes()); + assertThat(decoded.receipt().authorizationBindingBytes()) + .isEqualTo(fixture.authorization().canonicalBytes()); + verify(repository).read(NAMESPACE, binding.intakeRequestId()); + } + + @Test + void absentReceiptIsNotConvertedToAnAbortOrAnyTerminalEvidence() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var binding = fixture.authorization(); + when(repository.read(NAMESPACE, binding.intakeRequestId())).thenReturn(Optional.empty()); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + assertStatus(() -> service.read(request(binding)), Status.Code.NOT_FOUND); + } finally { + accountContext.detach(previous); + } + verify(repository).read(NAMESPACE, binding.intakeRequestId()); + } + + @Test + void changedCompleteOriginalAuthorizationIsAlreadyExistsAndCorruptReadbackIsDataLoss() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var changedAuthorization = + EntitySelectedSourceIntakeTerminalReadFixtures.create().authorization(); + assertThat(changedAuthorization.intakeRequestId()) + .isEqualTo(fixture.authorization().intakeRequestId()); + assertThat(changedAuthorization.canonicalBytes()) + .isNotEqualTo(fixture.authorization().canonicalBytes()); + when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId())) + .thenReturn(Optional.of(fixture.receipt())); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + assertStatus(() -> service.read(request(changedAuthorization)), Status.Code.ALREADY_EXISTS); + + when(repository.read(NAMESPACE, fixture.authorization().intakeRequestId())) + .thenThrow( + new EntityEmptySelectedSourceIntakeRepository.CorruptReceiptException( + "corrupt stored Entity receipt")); + assertStatus(() -> service.read(request(fixture.authorization())), Status.Code.DATA_LOSS); + } finally { + accountContext.detach(previous); + } + } + + @Test + void databaseOutagesAreSanitizedAsUnavailable() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var binding = fixture.authorization(); + var terminalRequest = request(binding); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var accountContext = accountPeer(NAMESPACE); + var previous = accountContext.attach(); + try { + for (RuntimeException outage : + java.util.List.of( + new DataAccessException("private jOOQ database detail"), + new DataAccessResourceFailureException("private Spring database detail"))) { + doThrow(outage) + .doReturn(Optional.of(fixture.receipt())) + .when(repository) + .read(NAMESPACE, binding.intakeRequestId()); + + assertThatThrownBy(() -> service.read(terminalRequest)) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + error -> { + var status = Status.fromThrowable(error); + assertThat(status.getCode()).isEqualTo(Status.Code.UNAVAILABLE); + assertThat(status.getDescription()) + .isEqualTo("Entity terminal receipt storage is unavailable"); + assertThat(status.getDescription()) + .doesNotContain("private jOOQ", "private Spring"); + assertThat(((StatusRuntimeException) error).getCause()).isNull(); + assertThat(((StatusRuntimeException) error).getTrailers()).isNull(); + }); + + var recovered = service.read(terminalRequest); + assertThat(recovered.request()).isSameAs(terminalRequest); + assertThat(recovered.receipt()).isSameAs(fixture.receipt()); + assertThat(recovered.receipt().canonicalBytes()) + .isEqualTo(fixture.receipt().canonicalBytes()); + } + } finally { + accountContext.detach(previous); + } + } + + @Test + void rejectsWrongPeerNamespaceOwnerEndUserAndAmbientSqlBeforeRepositoryRead() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var request = request(fixture.authorization()); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + + assertStatus(() -> service.read(request), Status.Code.UNAUTHENTICATED); + + var wrongPeer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")); + var previous = wrongPeer.attach(); + try { + assertStatus(() -> service.read(request), Status.Code.PERMISSION_DENIED); + } finally { + wrongPeer.detach(previous); + } + + var otherNamespaceService = + new EntityEmptySelectedSourceIntakeTerminalReadService(repository, "other"); + var otherAccount = accountPeer("other"); + previous = otherAccount.attach(); + try { + assertStatus(() -> otherNamespaceService.read(request), Status.Code.PERMISSION_DENIED); + } finally { + otherAccount.detach(previous); + } + + assertThatThrownBy( + () -> + EntitySelectedSourceIntakeTerminalReadEvidence.Request.create( + NAMESPACE, fixture.wrongOwnerAuthorization())) + .isInstanceOf(IllegalArgumentException.class); + + var accountContext = accountPeer(NAMESPACE); + previous = accountContext.attach(); + try { + SessionContext.setContext("101", java.util.List.of(), java.util.Map.of()); + assertStatus(() -> service.read(request), Status.Code.PERMISSION_DENIED); + SessionContext.clear(); + + TransactionSynchronizationManager.setActualTransactionActive(true); + assertStatus(() -> service.read(request), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.setActualTransactionActive(false); + + TransactionSynchronizationManager.initSynchronization(); + assertStatus(() -> service.read(request), Status.Code.FAILED_PRECONDITION); + TransactionSynchronizationManager.clearSynchronization(); + } finally { + accountContext.detach(previous); + } + verifyNoInteractions(repository); + } + + @Test + void grpcAuthenticatesBeforeMalformedRequestDecodeOrRepositoryLookup() { + var repository = mock(EntityEmptySelectedSourceIntakeRepository.class); + var service = new EntityEmptySelectedSourceIntakeTerminalReadService(repository, NAMESPACE); + var grpc = new EntitySelectedSourceIntakeTerminalReadGrpcService(service); + + var unauthenticatedError = invokeMalformed(grpc, null); + assertThat(Status.fromThrowable(unauthenticatedError).getCode()) + .isEqualTo(Status.Code.UNAUTHENTICATED); + + var wrongPeer = + Context.current() + .withValue( + GrpcPeerIdentity.CONTEXT_KEY, + new GrpcPeerIdentity( + "spiffe://firemud/ns/test/sa/game-design-service", + NAMESPACE, + "game-design-service")); + var previous = wrongPeer.attach(); + try { + assertThat(Status.fromThrowable(invokeMalformed(grpc, null)).getCode()) + .isEqualTo(Status.Code.PERMISSION_DENIED); + } finally { + wrongPeer.detach(previous); + } + + var accountContext = accountPeer(NAMESPACE); + previous = accountContext.attach(); + try { + assertThat( + Status.fromThrowable( + invokeMalformed( + grpc, ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance())) + .getCode()) + .isEqualTo(Status.Code.INVALID_ARGUMENT); + } finally { + accountContext.detach(previous); + } + verifyNoInteractions(repository); + } + + private static EntitySelectedSourceIntakeTerminalReadEvidence.Request request( + net.firedevops.firemud.common.account.sourceintake.SelectedOwnerIntakeAuthorizationBinding + binding) { + return EntitySelectedSourceIntakeTerminalReadEvidence.Request.create(NAMESPACE, binding); + } + + private static void assertStatus(Runnable action, Status.Code expected) { + assertThatThrownBy(action::run) + .isInstanceOf(StatusRuntimeException.class) + .satisfies( + failure -> assertThat(Status.fromThrowable(failure).getCode()).isEqualTo(expected)); + } + + private static Context accountPeer(String namespace) { + String uri = "spiffe://firemud/ns/" + namespace + "/sa/account-service"; + return Context.ROOT.withValue( + GrpcPeerIdentity.CONTEXT_KEY, new GrpcPeerIdentity(uri, namespace, "account-service")); + } + + private static Throwable invokeMalformed( + EntitySelectedSourceIntakeTerminalReadGrpcService grpc, + ReadSelectedSourceIntakeTerminalRequest request) { + var observedResponse = new AtomicReference(); + var observedError = new AtomicReference(); + grpc.readSelectedSourceIntakeTerminal( + request == null ? ReadSelectedSourceIntakeTerminalRequest.getDefaultInstance() : request, + responseObserver(observedResponse, observedError)); + assertThat(observedResponse.get()).isNull(); + assertThat(observedError.get()).isNotNull(); + return observedError.get(); + } + + private static StreamObserver responseObserver( + AtomicReference response, + AtomicReference error) { + return new StreamObserver<>() { + @Override + public void onNext(ReadSelectedSourceIntakeTerminalResponse value) { + response.set(value); + } + + @Override + public void onError(Throwable failure) { + error.set(failure); + } + + @Override + public void onCompleted() {} + }; + } +}