diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e4cc71d78..f418fd0b12 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -381,6 +381,10 @@ jobs: with: requirements: ${{ (needs.changes.outputs.lightweight_only == 'true' && needs.changes.outputs.design_docs_changed == 'true' && needs.changes.outputs.validation_python_changed != 'true') && 'yaml' || 'ci' }} + - name: Run installation inventory offline vectors + if: ${{ needs.changes.outputs.lightweight_only != 'true' }} + run: python3 dev-tools/deploy/test-runtime-installation-inventory.py + - name: Set up Node for Python Markdown contracts if: ${{ needs.changes.outputs.lightweight_only != 'true' || needs.changes.outputs.validation_python_changed == 'true' }} uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7 @@ -1099,6 +1103,12 @@ jobs: with: requirements: none + - name: Set up Python for installation inventory composition + if: ${{ matrix.module == 'game-design-service' }} + uses: ./.github/actions/setup-python + with: + requirements: yaml + - name: ⚙️ Set Up Java uses: actions/setup-java@b843ebf9b913146b38da2eaa7aeddf76074ae1ad # v6 with: diff --git a/DEVELOPER_SETUP.md b/DEVELOPER_SETUP.md index 4c870684f3..c0e01b9176 100644 --- a/DEVELOPER_SETUP.md +++ b/DEVELOPER_SETUP.md @@ -22,6 +22,10 @@ The following tools are not strictly required to build or run the stack, but the - **Redis CLI (`redis-cli`)** and **RedisInsight** – useful for inspecting transient gameplay/session state in the local Redis instance and browsing keys like `session:*`, `tick:*`, and `timer:*`. - **Kubernetes CLI (`kubectl`)** and optionally **Helm** – install `kubectl` if you work on `k8s/`, Kustomize overlays, or overlay validation CI. Local validation uses `kubectl kustomize`, so this is effectively required for Kubernetes-related changes. +## Game Design Cross-Service Checks + +Local `:game-design-service:crossServiceTest` and `:game-design-service:check` runs require `python3` and PyYAML because the owner-composition test launches the runtime installation inventory producer. From the repository root, activate a Python virtual environment and install the existing pinned YAML profile with `python3 -m pip install --require-hashes -r config/python/yaml-requirements.txt`. Keep that environment active when invoking the [canonical Gradle wrapper](design/developer-workflows/validation-and-runtime-proof.md#local-gradle-execution), so the test can find `python3` and its dependencies. CI installs the same YAML profile through the repository setup action. + ## Windows + WSL Tooling If you develop from Windows, prefer running build and package-management tools inside WSL with Linux-native toolchains. diff --git a/design/architecture/microservices/world-management-service/runtime-and-data.md b/design/architecture/microservices/world-management-service/runtime-and-data.md index 19f8fd5b41..ae6b1e852a 100644 --- a/design/architecture/microservices/world-management-service/runtime-and-data.md +++ b/design/architecture/microservices/world-management-service/runtime-and-data.md @@ -168,11 +168,11 @@ Redis caches hot rooms for active sessions to speed up lookups. Target Class A c ## Owner-local Runtime-family Catalog -The manually composed World runtime-family catalog persists owner-local source evidence under forward [V1046](../../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql) and [V1047](../../../../services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql). The catalog adds only `world_runtime_family_classification`, `world_runtime_family_catalog_epoch` and `world_runtime_family_catalog_snapshot` plus their source functions/guards. Existing World data, authority, lifecycle rows and earlier migrations are not rewritten. Its authenticated read and exact value/transport contract are owned by [World API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read); implementation and focused proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). +The manually composed World runtime-family catalog persists owner-local source evidence under forward [V1046](../../../../services/world-management-service/src/main/resources/db/migration/V1046__world_owner_runtime_family_catalog.sql) and [V1047](../../../../services/world-management-service/src/main/resources/db/migration/V1047__world_catalog_snapshot_exact_frames.sql). Those migrations add `world_runtime_family_classification`, `world_runtime_family_catalog_epoch` and `world_runtime_family_catalog_snapshot` plus their source functions/guards. Forward [V1048](../../../../services/world-management-service/src/main/resources/db/migration/V1048__world_protected_installation_registry.sql) additionally classifies the installation registry and required-owner provenance/control records described below. Existing World data, authority, lifecycle rows and earlier migrations are not rewritten. Its authenticated read and exact value/transport contract are owned by [World API Contracts](./api-contracts.md#owner-local-runtime-family-catalog-read); implementation and focused proof status are tracked in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#world-owner-local-runtime-family-catalog-prerequisite). The migration installs explicit owner metadata for every current World/Saga/history/catalog table, plus the distinct `region_instance.weather` component. `world_runtime_family_catalog_bytes` actually reads the installed service schema through PostgreSQL catalogs and the owning Flyway history. Each table must have a declared table-level disposition, each declared table must exist, and each declared component must resolve to an installed non-dropped column. It also enumerates columns with type/default/nullability/identity/generated/collation facts, constraints, indexes, triggers, routines, sequences, views/rules, types and policies with definition digests. View and materialized-view facts bind both the query definition and installed relation options, including security and storage options; changing an option invalidates the sealed census. Routine and trigger facts include the installed owner guards, including this catalog's own functions. Migration evidence binds installed rank, version, script, checksum and success, excluding installation user/time. Sequence positions, OIDs, statistics and gameplay row contents are not schema facts. The resulting ordered census and classifications are sealed together as exact bytes with a positive durable epoch, initially `1`, and an actual-byte SHA-256 digest; no Java constructor or empty payload query declares the installed inventory complete. -Flyway records each catalog migration's own history row after its migration transaction. The seal therefore includes distinct stable `catalog-installation:1046` and `catalog-installation:1047` markers and the actual installed object definitions, rather than inventing self-history checksums or successful rows inside either transaction. The original V1046 epoch retains its original single-marker census; V1047 replaces the catalog routines and explicitly appends the next monotonic epoch after all routine replacements, preserving every old epoch, snapshot and migration row byte-for-byte. A fresh installation consequently retains epoch `1` and seals current epoch `2`; an upgrade appends the next epoch after its retained history, and old request identities conflict rather than resampling. Flyway's built-in `flyway:table` placeholder binds the actual configured history relation into the census, its explicit classification and the installed-row check; the service's default `public` schema and explicitly configured history names do not require a separate hardcoded table. Both the read owner and the snapshot insertion guard separately require the successful exact V1046 and V1047 script rows through that installed owner function, because their markers cannot establish actual installation success. Every other installed migration row participates in the seal; adding a later migration, changing a prior migration fact, or adding/removing/renaming/changing a schema object or classification invalidates this epoch. A new table with zero rows is still an unclassified family and refuses. Subsequent catalog/schema evolution needs an explicit owning forward migration to install its supported classifications and next exact epoch, including updating the installation-marker/history boundary for that migration. There is no runtime resampling, epoch-advance endpoint or automatic acceptance of a changed census. This seal is owner-local installed-schema evidence, not an external deployment attestation or a substitute for Flyway validation. +Flyway records each catalog migration's own history row after its migration transaction. The seal therefore includes distinct stable `catalog-installation:1046` and `catalog-installation:1047` markers and the actual installed object definitions, rather than inventing self-history checksums or successful rows inside either transaction. The original V1046 epoch retains its original single-marker census; V1047 replaces the catalog routines and explicitly appends the next monotonic epoch after all routine replacements, preserving every old epoch, snapshot and migration row byte-for-byte. V1047 retains epoch `1` and seals epoch `2`; V1048 retains both and seals current epoch `3`, adding its own distinct installation marker and successful exact-script prerequisite; an upgrade appends the next epoch after its retained history, and old request identities conflict rather than resampling. Flyway's built-in `flyway:table` placeholder binds the actual configured history relation into the census, its explicit classification and the installed-row check; the service's default `public` schema and explicitly configured history names do not require a separate hardcoded table. Both the read owner and the snapshot insertion guard separately require the successful exact V1046, V1047 and V1048 script rows through that installed owner function, because their markers cannot establish actual installation success. Every other installed migration row participates in the seal; adding a later migration, changing a prior migration fact, or adding/removing/renaming/changing a schema object or classification invalidates this epoch. A new table with zero rows is still an unclassified family and refuses. Subsequent catalog/schema evolution needs an explicit owning forward migration to install its supported classifications and next exact epoch, including updating the installation-marker/history boundary for that migration. There is no runtime resampling, epoch-advance endpoint or automatic acceptance of a changed census. This seal is owner-local installed-schema evidence, not an external deployment attestation or a substitute for Flyway validation. Epoch rows, classification rows and request snapshots reject UPDATE, DELETE and TRUNCATE. A new epoch insertion must be the next positive epoch and bind the exact current census bytes; a source snapshot insertion must bind the current epoch/digest, unchanged installed census and successful exact catalog installation. The PostgreSQL guard reconstructs the complete canonical `WCR1` request frame from the row's request UUID and namespace and the complete `WCE1` evidence frame from that request, snapshot UUID and sealed catalog digest/bytes. Both stored frames must match those exact bytes, independently of their per-column digest CHECKs, so valid digests over mismatched or arbitrary frames cannot consume a request identity. The request UUID is unique across namespaces. A retained snapshot binds exact request bytes/digest, workload namespace, World snapshot UUID, epoch/catalog digest and complete response bytes/digest. Exact retry and independent committed readback compare all of them; changed requests, missing snapshots and old snapshots under a changed catalog refuse rather than returning absence or updated evidence. Evidence is retained without a new deletion/expiry policy or cleanup job. A caller-visible refusal after capture commit does not erase retained evidence. These source records do not mutate a realm, runtime, canonical pointer or player state. @@ -283,3 +283,19 @@ World event invariants: - Event application must be idempotent through a stable event identity or derived identity tuple. - While the Weather selector is unresolved, `WEATHER_CHANGE` scheduling and application are explicitly deferred/non-mutating: no new `world_event` row is inserted, retained Weather rows remain unprocessed, and no `region_instance.weather` mutation is permitted. The live service now enforces that containment before region lookup or due-event application; it does not turn an old Weather row into an admitted effect or prove its eventual safe disposition. Region-bearing non-Weather events require an exact tenant/game-instance match to the selected runtime region. - Once the selector and typed fenced command are accepted, event application must use the same effect-shaped ambient mutation contract used by tick execution, guarded by `EffectId` and scoped by runtime instance identifiers. + +## Protected Installation Registry and Frozen Required Owners + +World owns the global runtime-family registration and per-instance required-owner snapshot. The exact deployment artifact schema and producer completeness rules belong to [Runtime Ownership Installation Inventory](../../system-architecture-deployment-runbook.md#runtime-ownership-installation-inventory). A workload certificate, successful RPC response, Java service list or local SQL catalog cannot establish that global installation set. The installation identity, full input bindings and immutable catalog/family declarations remain distinct from each owner's actual FRESH initialization and lifecycle evidence. + +The manually composed `WorldRuntimeInstallationRegistry` acquires bytes exclusively from a configured `ProtectedInstallationSource`. Its default source refuses before database access; ordinary requests cannot supply artifact bytes. A supplied `HeldInstallation` must independently verify the exact completed current installation, workload incarnations and every applicable input binding, and prevent their change through the actual World commit. Re-reading an unprotected file or comparing a candidate digest does not implement that authority. The owner strictly parses the closed artifact, retains its original UTF-8 bytes and digest, and requires the configured workload namespace. It serializes registration per namespace, preserves exact-identity retries without rewriting rows, and rejects changed bytes under an existing artifact ID or reinstallation of a historical registration. + +Forward V1048 stores immutable exact artifact bytes and World-generated revisions in `world_runtime_installation_registration`, and the monotonic current revision in `world_runtime_installation_current`. It independently reads the committed registration and checks all identity/digest bindings. Changing the current revision invalidates dependent frozen snapshots by revision/digest equality; it does not rewrite their provenance. These owner-local records preserve earlier catalog epochs, snapshots and Flyway history. The forward migration explicitly classifies all three new relations, includes its own honest installation marker, and seals the next exact World schema epoch after every function and guard is installed. + +`withLaunchOwners` holds the protected installation source, requires a resolved complete runtime-owner set, and freezes that entire set under the canonical game-instance UUID before calling the existing synchronous launch owner. PostgreSQL derives `required_owners` from the retained artifact rather than accepting a caller-selected subset. `world_runtime_required_owner_snapshot` binds the exact namespace, registry revision and artifact digest; exact retries compare the retained complete set, while changed or invalidated requests refuse rather than resampling. Required owner metadata includes each member's catalog sources and families, even when that owner has no runtime payload rows. Unresolved classifications, absent catalog references or cleanup-contract evidence are unavailable. Source/catalog metadata never substitutes for actual selected-build applicability or initialization manifests. + +The storage trigger on `world_instance` requires the exact current frozen owner set before canonical instance insertion, attachment of a canonical identity, or transition into `ACTIVE`. It locks the namespace's current revision through that write transaction; a concurrent registration change cannot pass the write with stale evidence. It preserves historical rows and does not invent cleanup or termination authority. The canonical preparation and protected activation services explicitly compose the installation owner around their existing Account/Game Session held execution authority; constructors without that composition refuse fresh preparation or activation before acquiring the respective Account participation or activation protection. A read-only installation preflight rejects already-unavailable, unresolved or invalidated fresh targets before that acquisition without registering or freezing anything. A narrow local COMMITTED-candidate hint may skip preparation preflight only; it cannot return a result or replace authenticated held-owner and exact retained-result qualification. Preflight releases its source hold and does not guarantee race freedom: the commit-time hold and storage predicates remain authoritative, and later uncertainty still requires exact terminal evidence or a positive fenced abort before Account settlement. After authenticated held-owner and exact-input qualification, an already-COMMITTED preparation returns its immutable retained result before current installation-snapshot qualification; fresh and pending effects remain installation-guarded. Exact retained activation terminals remain historical readback and do not require a new installation snapshot. This adds no runtime registration, private runtime, activation route or gameplay-admission permission. A current durable read is provenance only; the protected installation hold is separately required at a launch commit. + +The package-scoped `WorldLifecycleCommandServiceImpl.prepareRunOwnedFixture` currently has only test callers: the integration `RunOwnedWorldFixtureLifecycleTestFactory` and reflective cross-service compositions. It has no production, RPC or bootstrap caller. Successful physical fixture tests explicitly compose controlled installation facts around that call. Smoke fixture flags do not supply a protected installation source or exempt `RUN_OWNED_FIXTURE` from the canonical launch storage predicate; uncomposed fixture preparation remains held. + +The concrete protected installation delivery/custody implementation and default runtime composition remain unavailable. Internal generation and controlled source fixtures prove only the attributed component boundary; they must not be reported as a genuinely installed external authority. Detailed capability and proof status is recorded in [Realm Routing and Playable State](../../../project-management/implementation-tracking/realm-routing-and-playable-state.md#protected-installation-registry-prerequisite). diff --git a/design/architecture/system-architecture-deployment-runbook.md b/design/architecture/system-architecture-deployment-runbook.md index c8200a3375..9e0657df5c 100644 --- a/design/architecture/system-architecture-deployment-runbook.md +++ b/design/architecture/system-architecture-deployment-runbook.md @@ -228,3 +228,19 @@ If a deployment causes instability: | **Hobby / Self-Hosted** | Resolve target manifests/charts → provide `FIREMUD_PREFLIGHT_RENDER_PATH` and run the canonical operator preflight (`./dev-tools/deploy/preflight.py hobby-self-hosted`), with no stage-overlay fallback, then capture the partial/static-only report → apply manifests/charts from the operator environment with normal steady-state processing; only for first-live or reopen after restore hold normal workloads at zero or behind restore-safe traffic quarantine → verify live state, monitor rollout, and run recovery-safe generic smoke only (no login, session/reconnect, or player-connectivity checks before finalization) → for first-live or reopen events do not treat `PREFLIGHT-BACKUP-003` as traffic authorization; keep traffic closed and follow the canonical [Backup & Disaster Recovery recovery lifecycle](./system-architecture-backup-recovery.md#recovery-controller-continuation) until its owner-defined finalized success state → expose traffic only after that terminal state, then run player-facing connectivity verification and record canonical deployment evidence (`manifestRef`/`chartVersion`, preflight report, rollback reference) | Re-apply previously known-good manifest/chart reference and confirm health only when the prior release remains compatible with the current schema, secret/config contract, mounted file-path contract, and external bindings; if not, follow the documented forward remediation path | Overlay PRs should include a clear deployment intent payload: target environment, service image digests, source commit/tag, rollback digest set (or explicit `roll-forward-only` marker), and (for production) an attestation reference under `design/operations/deployments/production/attestations/`. Attestation schema and validation requirements are defined in `design/architecture/system-architecture-promotion-attestation.md`. CI validates overlay images and preflight policy contracts via [`.github/workflows/validate-kustomize-overlays.yml`](../../.github/workflows/validate-kustomize-overlays.yml) before merge. + +## Runtime Ownership Installation Inventory + +World owns the versioned runtime-family registry and frozen required-owner sets under [ADR 0123](./decisions/adr-0123-database-authoritative-temporal-coordinated-world-lifecycle.md). The deployment/installation boundary supplies a distinct protected exact-installation inventory as its completeness root. This inventory reuses the exact identity and input binding of [ADR 0177](./decisions/adr-0177-exact-plan-authorized-automated-production-deployment.md); it is separate from preflight reports, release manifests, workload certificates and non-authorizing JWT readiness observations. Rendering or hashing a candidate inventory does not authorize installation or registration. The protected current-installation source must independently establish that the exact inventory is the current completed installation and hold that identity through the World commit. Missing, stale, incomplete or mismatched evidence is unavailable. + +The closed UTF-8 JSON artifact schema is `firemud-runtime-installation-inventory/v1`. Its exact root fields are `schema`, `artifactId`, `installationId`, `environment`, `generation`, `clusterUid`, `namespaceUid`, `namespace`, `sourceCommit`, `renderedManifestDigest`, `declarationsDigest`, `executor`, `inputBindings` and `members`. Artifact and installation IDs are non-nil UUIDs; generation and Kubernetes incarnation UIDs are bounded opaque identities, not counters inferred by consumers. Environment uses the existing deployment environment classes. Namespace is the exact workload namespace. The source commit is an immutable full Git SHA; digests use `sha256:` followed by lowercase hexadecimal. `executor` has exactly `identity` and `versionDigest`, binding the protected installation executor and its immutable version. Exact original artifact bytes and their digest are retained; consumers do not replace them with reserialized JSON. + +`inputBindings` has exactly five arrays: `migrations`, `configurations`, `mountedResources`, `secretContracts` and `externalBindings`. Each binding has exactly `name`, `version` and `digest`; names are unique within their category. Empty arrays explicitly declare no relevant input in that category; omitted categories are invalid. Secret references alone do not bind secret-contract versions, and secret contents are not placed in the artifact. The protected installation source must verify every applicable input, including references outside the rendered manifest. + +Each `members` entry identifies one actual ordinary or init container in a rendered workload. Its exact fields are `workloadApiVersion`, `workloadKind`, `workloadNamespace`, `workloadName`, `containerKind`, `containerName`, `image`, `ownerId`, `ownership`, `catalogSources` and `families`. The container kind is `APPLICATION` or `INIT`; images are immutable OCI digest references. Workload/container identities are unique and sorted. Inventory generation enumerates actual Pod specifications in supported Pod, Deployment, StatefulSet, DaemonSet, ReplicaSet, Job and CronJob resources. It must not select only matching image names, omit sidecars/init containers, or infer owners from successful responders. Unknown resource kinds require an explicit supported classification rather than silent omission. Every enumerated container needs an exact protected ownership declaration; missing, duplicate or extra declarations refuse generation. + +Ownership is `RUNTIME_OWNER` or `NO_INSTANCE_STATE`. The latter requires empty catalog and family arrays and grants no ownership over future state. Runtime owners have a nonempty owner ID and catalog sources. Each catalog source has exactly `sourceId`, `contract`, `epoch` and `digest`; IDs are unique within the member and epochs are positive decimal strings. Each family has exactly `familyId`, `catalogSourceId`, `replacementClass` and `cleanupContract`. Family identity is unique across the artifact's owner/family pairs, and its source must resolve in the same member. Replacement class is `S1`, `S2`, `S3` or `UNRESOLVED`. A cleanup contract has exactly `operation`, `requestIdentity`, `acknowledgement` and `retention`, naming versioned owner contracts rather than inventing deletion authority. Unresolved classification or missing cleanup/catalog evidence blocks qualified launch writes; inventory and registry evidence is not FRESH initialization or admission. + +The internal generator takes exact rendered bytes and a distinct closed declaration document, verifies complete rendered container membership and binding formats, hashes the exact rendered/declaration bytes, and emits deterministic candidate artifact bytes. Declared external input facts still require independent verification by the protected installation source. That generator is below the protected installation authority boundary. World registration obtains artifact bytes only from its configured protected current-installation source, never from ordinary registration request payloads. It retains immutable artifact identity, registration revision and exact readback, rejects conflicting retries and changes, and freezes the complete required-owner set before applicable launch writes. Registration and classification changes invalidate dependent snapshots under the owning contracts. The concrete local persistence and write predicates belong to [World Runtime and Data](./microservices/world-management-service/runtime-and-data.md); capability and proof status belongs in [Realm Routing and Playable State](../project-management/implementation-tracking/realm-routing-and-playable-state.md). + +This boundary does not implement or authorize the whole ADR 0177 executor, rollout or recovery programme. Default runtime registration, actual protected installation delivery, signer/custody qualification and activation retain their existing holds. An internal producer or controlled protected-source fixture must not be reported as genuinely installed external authority. diff --git a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md index d089d75608..1dc9b8fd0a 100644 --- a/design/project-management/implementation-tracking/realm-routing-and-playable-state.md +++ b/design/project-management/implementation-tracking/realm-routing-and-playable-state.md @@ -135,6 +135,7 @@ The full direct-text `WORLDS` -> `LOGIN` -> `REALMS` -> conditional `JOIN` -> co ## Active Gaps +- The [protected installation registry prerequisite](#protected-installation-registry-prerequisite) still lacks a protected current-installation source; default and runtime registration remain denied, and all-owner epoch/applicability and FRESH manifest collection remain unavailable. - Later gameplay-state families, especially loadouts, abilities, authored effects, richer resource tables, and any new character-creation or social/runtime consumer, still need explicit adoption of `{tenantId, gameInstanceId, playableStateScope}` before they become live. They must not reopen tenant-wide or bare-character shortcuts. - Entity Management owns actor rows and the Account relationship/projection to those rows remains an evolving Account/Entity seam. Actor rows carry account and tenant identity, but neither membership nor that relationship establishes one implicit gameplay namespace across realms. - Text `JOIN`/`Join & Play` dispatch remains unimplemented; the Account-local explicit writer is separate. Text `PLAY` lifecycle/generation validation is implemented; its outcome rules remain with the canonical owner linked above. Current connect-token issuance remains held before replay and authority reads. Full caller-target/atomic authority, connect-token membership/version reread, `allowNewGameplayBindings`, grant lifecycle/expiry, and lease-commit boundaries remain gaps; no membership is created implicitly. @@ -166,3 +167,15 @@ No competing implementation is recorded for visible realm addressing, world-qual | Social Groups | Live/recent friend-presence projection with realm and playable-state scope | Account-presence/friend-presence contracts | | Game Logic | Preserve and validate complete routing/playable-state attestation for gameplay calls | Authenticated outbound gameplay gRPC | | Logging & Admin | Tenant-guarded pointer audit, cutover, and runtime-state operator reads | REST over Game Session control-plane authority | + +## Protected Installation Registry Prerequisite + +The internal candidate producer, closed World artifact parser, World registration/readback owner and forward V1048 storage predicates are implemented as a receiving boundary. The [deployment owner](../../architecture/system-architecture-deployment-runbook.md#runtime-ownership-installation-inventory) owns the artifact contract and completeness rules; [World Runtime and Data](../../architecture/microservices/world-management-service/runtime-and-data.md#protected-installation-registry-and-frozen-required-owners) owns registry persistence, invalidation and launch predicates. The producer enumerates rendered application and init containers, including unrelated sidecars, and requires exact ownership declarations and explicit resource-kind classification. It binds exact rendered/declaration bytes and all declared input categories. This produces candidate bytes only. + +At `631d9faa38d2b41dc2670ecc38c30546ccdb7995`, all sixteen offline producer tests pass locally and in CI, including an exact-byte interoperability vector also consumed by the World parser. Receiving proof 291 passes owning generation, ten parser units, twelve actual registry PostgreSQL cases and seventeen catalog PostgreSQL cases with no failures, errors or skips (2m10). Proof 293 qualifies the final forward migration and explicit installation composition in preparation/protected activation: 33 units, 42 PostgreSQL cases and nineteen actual Account/Game Session/World mTLS composition cases pass with no failures, errors or skips (11m52). Existing first-JOIN, materialization, activation, retained terminal retry and fixed-preset original-row/xmin assertions remain present. Separate controlled installation facts bound the full owner-chain cases; the isolated launch receiver additionally tests the installed storage predicate without bypassing canonical materialization guards. These results do not establish a genuinely installed external authority, process-death, private FRESH initialization, complete owner cleanup, custody or fresh-image proof. Selected World main/unit/integration/cross-service analysis and formatting pass in proof 296; the aggregate exposed three documentation blank-line failures, corrected and passed in proof 298. Fresh source-built baseline proof 300 built all eleven service jars and the changed World image, but failed because the existing Gateway qualification gate intentionally remained unready, cascading to TCP Proxy readiness. Authenticated teardown completed and independent inspection found no remaining project containers, networks or volumes. This remains a failed baseline. Separately attributed source-built held-admission proof 303 passes at receiving commit a2c3001e: all eleven service jars and the changed World image are rebuilt, Gateway/Telnet deliberate denial and the isolated direct-backend LOGIN → PLAY → LOOK path pass, authenticated teardown completes, and independent inspection finds no remaining project containers, networks or volumes. The Gateway handshake is loopback inside the run-owned container; successful public admission and host-published ingress remain unproved. Attempt 302 refused its malformed capability token before stack startup and supplies no runtime credit. + +Retained receiving proof 383 reports 39 focused World cases: ten artifact/parser, seventeen catalog PostgreSQL and twelve installation-registry PostgreSQL cases, plus selected analysis, formatting and documentation checks. The retained receiving record does not identify its exact source commit, so this report is not exact-head qualification of the current branch. Separately attributed source-built held-admission runtime 334 passed on `5a516b89b6351e649aab90173bf44450f04aa984`: rebuilt images, deliberate public-edge denial, isolated backend LOGIN → PLAY → LOOK and authenticated cleanup. Runtime 334 is not fresh runtime proof of `4213f6607a30250d36b8cf15a83a9e14fec8b19c` or these later fixes. Earlier failed baseline proof remains a failure. + +The package-scoped run-owned fixture preparation path has only integration test-factory and reflective cross-service test callers; successful physical fixtures explicitly compose controlled installation facts. There is no production/RPC caller or fixture-flag-based protected installation source. Uncomposed fixture preparation remains held under the [World data owner](../../architecture/microservices/world-management-service/runtime-and-data.md#protected-installation-registry-and-frozen-required-owners); no SQL exemption or fake default source is provided. + +The real protected current-installation producer/delivery and its authority through commit are unavailable; default source and runtime registration remain denied. This is an open prerequisite, not a capability-rating upgrade. Remaining work includes genuine installed completeness, all-owner epoch/applicability collection, FRESH manifests, private runtime/World materialization and aggregation into the existing canonical CLOSED owner. Production/default registration, signer/custody, activation/first-OPEN and Unit1B holds remain in force. diff --git a/dev-tools/deploy/README.md b/dev-tools/deploy/README.md index 45fb581e4d..b7aed57c2f 100644 --- a/dev-tools/deploy/README.md +++ b/dev-tools/deploy/README.md @@ -39,3 +39,15 @@ They are not generic CI utilities. They enforce the deployment contract for play - [system-architecture-deploy-preflight-policy.md](../../design/architecture/system-architecture-deploy-preflight-policy.md) - [system-architecture-deployment-runbook.md](../../design/architecture/system-architecture-deployment-runbook.md) + +## Internal Runtime Installation Candidate + +`runtime-installation-inventory.py --rendered-manifest PATH --declarations PATH --output PATH` emits deterministic candidate JSON for the [runtime ownership installation inventory](../../design/architecture/system-architecture-deployment-runbook.md#runtime-ownership-installation-inventory). It uses the existing PyYAML dependency, reads and hashes exact original input bytes without changing them, and exclusively creates the output so an existing evidence file is preserved. Retain both original inputs alongside the candidate; the candidate's two digests bind those bytes. + +The closed declaration schema is `firemud-runtime-installation-declarations/v1`: it has the inventory root fields except `renderedManifestDigest` and `declarationsDigest`, plus `nonWorkloadKinds`. Each member has the inventory member fields except `image`, which the producer obtains from the exact rendered container. `nonWorkloadKinds` is a sorted unique array of exact `{apiVersion, kind}` objects explicitly classifying rendered kinds without PodSpecs; every entry must occur in the render. All ordinary/init containers, including unrelated sidecars and restartable init containers, require an exact ownership declaration. Unknown or unsupported workloads, hidden container fields, aliases, duplicate mappings, ambiguous identities, extra/missing declarations, namespace mismatch and mutable images refuse generation. + +Input bindings are explicitly captured name/version/digest facts; this tool does not discover live Secret versions, prove applicable input completeness or establish an installation. The protected installation source must independently verify those facts and every applicable input, establish the current completed installation, and hold its identity through World registration. `UNRESOLVED` family classifications remain in the candidate and cannot support qualified launch writes. Candidate production supplies no installation, registration, admission or cleanup authority, and does not implement the ADR 0177 executor. + +Inputs are bounded to 16 MiB of rendered YAML and 4 MiB of declarations, with at most 1,024 members; emitted JSON is bounded to 4 MiB. The focused offline vectors are `python3 dev-tools/deploy/test-runtime-installation-inventory.py`; they exercise candidate generation and refusal, not protected installation delivery. + +The files under `fixtures/runtime-installation/` are controlled interoperability vectors, including synthetic catalog/input facts. The Python producer reproduces the exact candidate bytes and World’s parser consumes that same vector; they are not installed authority or a deployable enrollment. diff --git a/dev-tools/deploy/fixtures/runtime-installation/candidate.json b/dev-tools/deploy/fixtures/runtime-installation/candidate.json new file mode 100644 index 0000000000..d1b62a82c5 --- /dev/null +++ b/dev-tools/deploy/fixtures/runtime-installation/candidate.json @@ -0,0 +1 @@ +{"artifactId":"e8975b6d-88ca-4b50-8307-e0f8c8cccd53","clusterUid":"captured-cluster-uid","declarationsDigest":"sha256:159ae53792b7be55a9cf4148dc3c3b62b78391c475df3fef025896433d919740","environment":"staging","executor":{"identity":"protected/executor/v1","versionDigest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"generation":"captured-installation-generation","inputBindings":{"configurations":[],"externalBindings":[],"migrations":[],"mountedResources":[],"secretContracts":[]},"installationId":"56b80b22-977d-47bb-89db-6705d84294b1","members":[{"catalogSources":[{"contract":"world/catalog/v1","digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","epoch":"1","sourceId":"world-sql"}],"containerKind":"APPLICATION","containerName":"application","families":[{"catalogSourceId":"world-sql","cleanupContract":{"acknowledgement":"world/ack/v1","operation":"world/cleanup/v1","requestIdentity":"world/request/v1","retention":"world/retention/v1"},"familyId":"world-state","replacementClass":"S1"}],"image":"registry.example/independent/sidecar@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","ownerId":"world","ownership":"RUNTIME_OWNER","workloadApiVersion":"apps/v1","workloadKind":"Deployment","workloadName":"workload-0","workloadNamespace":"firemud"},{"catalogSources":[],"containerKind":"APPLICATION","containerName":"foreign-sidecar","families":[],"image":"registry.example/independent/sidecar@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","ownerId":"","ownership":"NO_INSTANCE_STATE","workloadApiVersion":"apps/v1","workloadKind":"Deployment","workloadName":"workload-0","workloadNamespace":"firemud"},{"catalogSources":[],"containerKind":"INIT","containerName":"initializer","families":[],"image":"registry.example/independent/sidecar@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","ownerId":"","ownership":"NO_INSTANCE_STATE","workloadApiVersion":"apps/v1","workloadKind":"Deployment","workloadName":"workload-0","workloadNamespace":"firemud"}],"namespace":"firemud","namespaceUid":"captured-namespace-uid","renderedManifestDigest":"sha256:5ed61a79dec534322a27b203dbb888b728407216d4cbad965bf129137d540536","schema":"firemud-runtime-installation-inventory/v1","sourceCommit":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"} diff --git a/dev-tools/deploy/fixtures/runtime-installation/declarations.json b/dev-tools/deploy/fixtures/runtime-installation/declarations.json new file mode 100644 index 0000000000..f57186105d --- /dev/null +++ b/dev-tools/deploy/fixtures/runtime-installation/declarations.json @@ -0,0 +1 @@ +{"schema": "firemud-runtime-installation-declarations/v1", "artifactId": "e8975b6d-88ca-4b50-8307-e0f8c8cccd53", "installationId": "56b80b22-977d-47bb-89db-6705d84294b1", "environment": "staging", "generation": "captured-installation-generation", "clusterUid": "captured-cluster-uid", "namespaceUid": "captured-namespace-uid", "namespace": "firemud", "sourceCommit": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "executor": {"identity": "protected/executor/v1", "versionDigest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, "inputBindings": {"externalBindings": [], "migrations": [], "mountedResources": [], "secretContracts": [], "configurations": []}, "nonWorkloadKinds": [], "members": [{"workloadApiVersion": "apps/v1", "workloadKind": "Deployment", "workloadNamespace": "firemud", "workloadName": "workload-0", "containerKind": "APPLICATION", "containerName": "application", "ownerId": "world", "ownership": "RUNTIME_OWNER", "catalogSources": [{"sourceId": "world-sql", "contract": "world/catalog/v1", "epoch": "1", "digest": "sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}], "families": [{"familyId": "world-state", "catalogSourceId": "world-sql", "replacementClass": "S1", "cleanupContract": {"operation": "world/cleanup/v1", "requestIdentity": "world/request/v1", "acknowledgement": "world/ack/v1", "retention": "world/retention/v1"}}]}, {"workloadApiVersion": "apps/v1", "workloadKind": "Deployment", "workloadNamespace": "firemud", "workloadName": "workload-0", "containerKind": "APPLICATION", "containerName": "foreign-sidecar", "ownerId": "", "ownership": "NO_INSTANCE_STATE", "catalogSources": [], "families": []}, {"workloadApiVersion": "apps/v1", "workloadKind": "Deployment", "workloadNamespace": "firemud", "workloadName": "workload-0", "containerKind": "INIT", "containerName": "initializer", "ownerId": "", "ownership": "NO_INSTANCE_STATE", "catalogSources": [], "families": []}]} \ No newline at end of file diff --git a/dev-tools/deploy/fixtures/runtime-installation/rendered.yaml b/dev-tools/deploy/fixtures/runtime-installation/rendered.yaml new file mode 100644 index 0000000000..a897efc9f2 --- /dev/null +++ b/dev-tools/deploy/fixtures/runtime-installation/rendered.yaml @@ -0,0 +1,16 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: workload-0 + namespace: firemud +spec: + template: + spec: + containers: + - image: registry.example/independent/sidecar@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + name: application + - image: registry.example/independent/sidecar@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + name: foreign-sidecar + initContainers: + - image: registry.example/independent/sidecar@sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + name: initializer diff --git a/dev-tools/deploy/runtime-installation-inventory.py b/dev-tools/deploy/runtime-installation-inventory.py new file mode 100644 index 0000000000..2372e51d8d --- /dev/null +++ b/dev-tools/deploy/runtime-installation-inventory.py @@ -0,0 +1,350 @@ +#!/usr/bin/env python3 +"""Produce candidate bytes only; this is not a protected installation authority.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import re +import sys +import uuid +from pathlib import Path +from typing import Any + +import yaml +from yaml.events import AliasEvent + +MAX_BYTES = 4 * 1024 * 1024 +MAX_MANIFEST_BYTES = 16 * 1024 * 1024 +MAX_MEMBERS = 1024 +MAX_BINDINGS = 256 +MAX_FAMILIES = 256 +MAX_SOURCES = 64 +MAX_NODES = 200000 +MAX_DEPTH = 64 +SCHEMA = "firemud-runtime-installation-inventory/v1" +DECLARATIONS_SCHEMA = "firemud-runtime-installation-declarations/v1" +ENVIRONMENTS = { + "local-dev", "pr-preview", "dev-demo-cluster", "hobby-self-hosted", + "staging", "production", +} +BINDING_FIELDS = { + "migrations", "configurations", "mountedResources", "secretContracts", "externalBindings", +} +ROOT_FIELDS = { + "schema", "artifactId", "installationId", "environment", "generation", "clusterUid", + "namespaceUid", "namespace", "sourceCommit", "executor", "inputBindings", "members", +} +MEMBER_FIELDS = { + "workloadApiVersion", "workloadKind", "workloadNamespace", "workloadName", + "containerKind", "containerName", "ownerId", "ownership", "catalogSources", "families", +} +IDENTITY_FIELDS = ( + "workloadApiVersion", "workloadKind", "workloadNamespace", "workloadName", + "containerKind", "containerName", +) +WORKLOAD_PATHS = { + ("v1", "Pod"): ("spec",), + ("apps/v1", "Deployment"): ("spec", "template", "spec"), + ("apps/v1", "StatefulSet"): ("spec", "template", "spec"), + ("apps/v1", "DaemonSet"): ("spec", "template", "spec"), + ("apps/v1", "ReplicaSet"): ("spec", "template", "spec"), + ("batch/v1", "Job"): ("spec", "template", "spec"), + ("batch/v1", "CronJob"): ("spec", "jobTemplate", "spec", "template", "spec"), +} +KNOWN_WORKLOAD_KINDS = {kind for _, kind in WORKLOAD_PATHS} | { + "ReplicationController", "PodTemplate", "List", "DeploymentList", "PodList", + "StatefulSetList", "DaemonSetList", "ReplicaSetList", "JobList", "CronJobList", +} +CONTAINER_KEYS = {"containers", "initContainers", "ephemeralContainers"} +DIGEST = r"sha256:[0-9a-f]{64}" +IMAGE = r"[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}" +DNS_LABEL = r"[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" +DNS_NAME = r"[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?" + + +class InventoryError(ValueError): + """The candidate input is incomplete, ambiguous, or outside the closed contract.""" + + +def require(condition: bool, message: str) -> None: + if not condition: + raise InventoryError(message) + + +def shape(value: Any, fields: set[str], label: str) -> dict: + require(type(value) is dict and set(value) == fields, f"{label}: expected exact fields {sorted(fields)}") + return value + + +def text(value: Any, label: str, maximum: int = 256, empty: bool = False) -> str: + require(type(value) is str, f"{label}: expected string") + require((empty or bool(value)) and len(value.encode("utf-8")) <= maximum, f"{label}: invalid length") + require(value == value.strip() and not any(ord(c) < 32 or ord(c) == 127 for c in value), f"{label}: invalid whitespace/control character") + return value + + +def matched(value: Any, pattern: str, label: str, maximum: int = 256) -> str: + value = text(value, label, maximum) + require(re.fullmatch(pattern, value) is not None, f"{label}: invalid format") + return value + + +def array(value: Any, label: str, maximum: int) -> list: + require(type(value) is list and len(value) <= maximum, f"{label}: expected array with at most {maximum} entries") + return value + + +def unique(items: list, label: str) -> None: + require(len(items) == len(set(items)), f"{label}: duplicate identity") + + +def digest(raw: bytes) -> str: + return "sha256:" + hashlib.sha256(raw).hexdigest() + + +def bounded_tree(value: Any, depth: int = 0, budget: list[int] | None = None) -> None: + if budget is None: + budget = [MAX_NODES] + budget[0] -= 1 + require(depth <= MAX_DEPTH and budget[0] >= 0, "document exceeds structural bounds") + if type(value) is dict: + require(all(type(key) is str for key in value), "mapping keys must be strings") + for item in value.values(): + bounded_tree(item, depth + 1, budget) + elif type(value) is list: + for item in value: + bounded_tree(item, depth + 1, budget) + else: + require(value is None or type(value) in (str, int, float, bool), "unsupported YAML/JSON value type") + + +def json_pairs(pairs: list) -> dict: + result = {} + for key, value in pairs: + require(key not in result, f"duplicate JSON key: {key}") + result[key] = value + return result + + +class ClosedLoader(yaml.SafeLoader): + """Reject aliases, duplicate mappings and expansion/depth abuse before constructing.""" + + def __init__(self, stream: str): + super().__init__(stream) + self.node_count = 0 + self.node_depth = 0 + + def compose_node(self, parent: Any, index: Any) -> Any: + require(not self.check_event(AliasEvent), "YAML aliases are not supported") + self.node_count += 1 + self.node_depth += 1 + require(self.node_count <= MAX_NODES and self.node_depth <= MAX_DEPTH, "manifest exceeds structural bounds") + try: + return super().compose_node(parent, index) + finally: + self.node_depth -= 1 + + def construct_mapping(self, node: Any, deep: bool = False) -> dict: + require(isinstance(node, yaml.MappingNode), "expected YAML mapping") + result = {} + for key_node, value_node in node.value: + key = self.construct_object(key_node, deep=deep) + require(type(key) is str, "YAML mapping keys must be strings") + require(key not in result, f"duplicate YAML mapping key: {key}") + result[key] = self.construct_object(value_node, deep=deep) + return result + + +def identity(member: dict) -> tuple: + return tuple(member[field] for field in IDENTITY_FIELDS) + + +def validate_declarations(declarations: Any) -> dict: + shape(declarations, ROOT_FIELDS | {"nonWorkloadKinds"}, "declarations") + require(declarations["schema"] == DECLARATIONS_SCHEMA, "unsupported declarations schema") + for field in ("artifactId", "installationId"): + value = text(declarations[field], field, 36) + try: + parsed = uuid.UUID(value) + except ValueError as exc: + raise InventoryError(f"{field}: invalid UUID") from exc + require(parsed.int != 0 and str(parsed) == value, f"{field}: expected canonical non-nil UUID") + require(declarations["environment"] in ENVIRONMENTS, "invalid environment") + for field in ("generation", "clusterUid", "namespaceUid"): + text(declarations[field], field) + matched(declarations["namespace"], DNS_LABEL, "namespace", 63) + matched(declarations["sourceCommit"], r"[0-9a-f]{40}", "sourceCommit", 40) + executor = shape(declarations["executor"], {"identity", "versionDigest"}, "executor") + text(executor["identity"], "executor.identity", 512) + matched(executor["versionDigest"], DIGEST, "executor.versionDigest") + bindings = shape(declarations["inputBindings"], BINDING_FIELDS, "inputBindings") + for category, entries in bindings.items(): + for entry in array(entries, category, MAX_BINDINGS): + shape(entry, {"name", "version", "digest"}, category) + text(entry["name"], f"{category}.name") + text(entry["version"], f"{category}.version", 512) + matched(entry["digest"], DIGEST, f"{category}.digest") + unique([entry["name"] for entry in entries], category) + classes = [] + for entry in array(declarations["nonWorkloadKinds"], "nonWorkloadKinds", 256): + shape(entry, {"apiVersion", "kind"}, "nonWorkloadKinds") + text(entry["apiVersion"], "apiVersion", 128) + text(entry["kind"], "kind", 128) + require(entry["kind"] not in KNOWN_WORKLOAD_KINDS, "known workload kind cannot be classified as non-workload") + classes.append((entry["apiVersion"], entry["kind"])) + unique(classes, "nonWorkloadKinds") + require(classes == sorted(classes), "nonWorkloadKinds must be sorted") + owner_families = [] + for member in array(declarations["members"], "members", MAX_MEMBERS): + shape(member, MEMBER_FIELDS, "member") + require((member["workloadApiVersion"], member["workloadKind"]) in WORKLOAD_PATHS, "member: unsupported workload") + require(member["workloadNamespace"] == declarations["namespace"], "member namespace mismatch") + matched(member["workloadName"], DNS_NAME, "workloadName", 253) + matched(member["containerName"], DNS_LABEL, "containerName", 63) + require(member["containerKind"] in {"APPLICATION", "INIT"}, "invalid containerKind") + require(member["ownership"] in {"RUNTIME_OWNER", "NO_INSTANCE_STATE"}, "invalid ownership") + text(member["ownerId"], "ownerId", empty=member["ownership"] == "NO_INSTANCE_STATE") + sources = array(member["catalogSources"], "catalogSources", MAX_SOURCES) + families = array(member["families"], "families", MAX_FAMILIES) + if member["ownership"] == "NO_INSTANCE_STATE": + require(not sources and not families, "NO_INSTANCE_STATE requires empty catalogSources and families") + else: + require(bool(sources), "RUNTIME_OWNER requires catalogSources") + for source in sources: + shape(source, {"sourceId", "contract", "epoch", "digest"}, "catalog source") + text(source["sourceId"], "sourceId") + text(source["contract"], "catalog contract", 512) + matched(source["epoch"], r"[1-9][0-9]{0,18}", "catalog epoch", 19) + matched(source["digest"], DIGEST, "catalog digest") + source_ids = [source["sourceId"] for source in sources] + unique(source_ids, "catalogSources") + for family in families: + shape(family, {"familyId", "catalogSourceId", "replacementClass", "cleanupContract"}, "family") + text(family["familyId"], "familyId") + text(family["catalogSourceId"], "catalogSourceId") + require(family["catalogSourceId"] in source_ids, "family catalogSourceId does not resolve in member") + require(family["replacementClass"] in {"S1", "S2", "S3", "UNRESOLVED"}, "invalid replacementClass") + cleanup = shape(family["cleanupContract"], {"operation", "requestIdentity", "acknowledgement", "retention"}, "cleanupContract") + for field, value in cleanup.items(): + text(value, f"cleanupContract.{field}", 512) + owner_families.append((member["ownerId"], family["familyId"])) + unique(owner_families, "owner/family") + unique([identity(member) for member in declarations["members"]], "members") + return declarations + + +def contains_containers(value: Any, excluded: Any = None) -> bool: + if value is excluded: + return False + if type(value) is dict: + return bool(CONTAINER_KEYS & value.keys()) or any(contains_containers(child, excluded) for child in value.values()) + if type(value) is list: + return any(contains_containers(child, excluded) for child in value) + return False + + +def rendered_containers(documents: list, declarations: dict) -> dict: + classes = {(entry["apiVersion"], entry["kind"]) for entry in declarations["nonWorkloadKinds"]} + observed_classes = set() + workloads = set() + containers = {} + for document in documents: + require(type(document) is dict, "rendered resource must be a mapping") + api = text(document.get("apiVersion"), "resource apiVersion", 128) + kind = text(document.get("kind"), "resource kind", 128) + resource_type = (api, kind) + if resource_type not in WORKLOAD_PATHS: + require(resource_type in classes, f"unclassified rendered kind: {api}/{kind}") + require(not contains_containers(document), "non-workload classification hides a PodSpec/container field") + observed_classes.add(resource_type) + continue + metadata = document.get("metadata") + require(type(metadata) is dict, "workload metadata must be a mapping") + namespace = metadata.get("namespace") + require(namespace == declarations["namespace"], "rendered workload namespace mismatch or missing") + name = matched(metadata.get("name"), DNS_NAME, "rendered workload name", 253) + workload_id = (api, kind, namespace, name) + require(workload_id not in workloads, "duplicate rendered workload") + workloads.add(workload_id) + spec = document + for field in WORKLOAD_PATHS[resource_type]: + require(type(spec) is dict and type(spec.get(field)) is dict, "missing rendered PodSpec") + spec = spec[field] + require(not contains_containers(document, spec), "unsupported additional PodSpec/container field") + require(not spec.get("ephemeralContainers"), "ephemeral containers have no supported inventory classification") + applications = array(spec.get("containers"), "containers", MAX_MEMBERS) + require(bool(applications), "workload requires an application container") + init = array(spec.get("initContainers", []), "initContainers", MAX_MEMBERS) + names = [] + for container_kind, entries in (("APPLICATION", applications), ("INIT", init)): + for container in entries: + require(type(container) is dict, "container must be a mapping") + container_name = matched(container.get("name"), DNS_LABEL, "rendered container name", 63) + names.append(container_name) + image = matched(container.get("image"), IMAGE, "immutable image", 1024) + container_id = workload_id + (container_kind, container_name) + require(container_id not in containers, "duplicate rendered container") + containers[container_id] = image + require(len(containers) <= MAX_MEMBERS, "too many rendered containers") + unique(names, "rendered application/init container names") + require(observed_classes == classes, "extra non-workload classification has no rendered resource") + return containers + + +def produce(rendered_bytes: bytes, declarations_bytes: bytes) -> bytes: + """Bind exact supplied bytes; external input facts and installation remain unverified.""" + require(len(rendered_bytes) <= MAX_MANIFEST_BYTES, "rendered manifest too large") + require(len(declarations_bytes) <= MAX_BYTES, "declarations too large") + try: + declarations = json.loads( + declarations_bytes.decode("utf-8"), object_pairs_hook=json_pairs, + parse_constant=lambda value: (_ for _ in ()).throw(InventoryError(f"invalid JSON constant: {value}")), + ) + bounded_tree(declarations) + validate_declarations(declarations) + documents = [doc for doc in yaml.load_all(rendered_bytes.decode("utf-8"), Loader=ClosedLoader) if doc is not None] + require(bool(documents), "empty rendered manifest") + for document in documents: + bounded_tree(document) + containers = rendered_containers(documents, declarations) + require(set(containers) == {identity(member) for member in declarations["members"]}, "rendered containers and ownership declarations differ") + artifact = {key: value for key, value in declarations.items() if key != "nonWorkloadKinds"} + artifact["schema"] = SCHEMA + artifact["renderedManifestDigest"] = digest(rendered_bytes) + artifact["declarationsDigest"] = digest(declarations_bytes) + artifact["members"] = [dict(member, image=containers[identity(member)]) for member in sorted(declarations["members"], key=identity)] + bounded_tree(artifact) + result = (json.dumps(artifact, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n").encode("utf-8") + require(len(result) <= MAX_BYTES, "candidate artifact too large") + return result + except (UnicodeError, json.JSONDecodeError, yaml.YAMLError, RecursionError, TypeError) as exc: + raise InventoryError(f"invalid input: {exc}") from exc + + +def read_bounded(path: Path, limit: int) -> bytes: + with path.open("rb") as source: + raw = source.read(limit + 1) + require(len(raw) <= limit, f"input exceeds {limit} bytes: {path}") + return raw + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--rendered-manifest", required=True, type=Path) + parser.add_argument("--declarations", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + try: + candidate = produce(read_bounded(args.rendered_manifest, MAX_MANIFEST_BYTES), read_bounded(args.declarations, MAX_BYTES)) + with args.output.open("xb") as output: + output.write(candidate) + return 0 + except (InventoryError, OSError) as exc: + print(f"runtime-installation inventory refused: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/dev-tools/deploy/test-runtime-installation-inventory.py b/dev-tools/deploy/test-runtime-installation-inventory.py new file mode 100644 index 0000000000..838109a0ca --- /dev/null +++ b/dev-tools/deploy/test-runtime-installation-inventory.py @@ -0,0 +1,333 @@ +#!/usr/bin/env python3 +"""Offline candidate-production proof; no installation or authority is exercised.""" + +import copy +import importlib.util +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import yaml + +MODULE_PATH = Path(__file__).with_name("runtime-installation-inventory.py") +SPEC = importlib.util.spec_from_file_location("runtime_installation_inventory", MODULE_PATH) +inventory = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(inventory) +DIGEST = "sha256:" + "a" * 64 +IMAGE = "registry.example/independent/sidecar@" + DIGEST + + +def workload(kind="Deployment", name="world"): + spec = { + "containers": [{"name": "application", "image": IMAGE}, {"name": "foreign-sidecar", "image": IMAGE}], + "initContainers": [{"name": "initializer", "image": IMAGE}], + } + api = "v1" if kind == "Pod" else "batch/v1" if kind in {"Job", "CronJob"} else "apps/v1" + document = {"apiVersion": api, "kind": kind, "metadata": {"name": name, "namespace": "firemud"}} + body = spec + for field in reversed(inventory.WORKLOAD_PATHS[(api, kind)]): + body = {field: body} + document.update(body) + return document + + +def member(document, name, container_kind="APPLICATION"): + return { + "workloadApiVersion": document["apiVersion"], "workloadKind": document["kind"], + "workloadNamespace": "firemud", "workloadName": document["metadata"]["name"], + "containerKind": container_kind, "containerName": name, + "ownerId": "", "ownership": "NO_INSTANCE_STATE", "catalogSources": [], "families": [], + } + + +def fixture(kinds=("Deployment",)): + documents = [workload(kind, "workload-" + str(index)) for index, kind in enumerate(kinds)] + declarations = { + "schema": inventory.DECLARATIONS_SCHEMA, + "artifactId": "e8975b6d-88ca-4b50-8307-e0f8c8cccd53", + "installationId": "56b80b22-977d-47bb-89db-6705d84294b1", + "environment": "staging", "generation": "captured-installation-generation", + "clusterUid": "captured-cluster-uid", "namespaceUid": "captured-namespace-uid", + "namespace": "firemud", "sourceCommit": "b" * 40, + "executor": {"identity": "protected/executor/v1", "versionDigest": DIGEST}, + "inputBindings": {name: [] for name in inventory.BINDING_FIELDS}, + "nonWorkloadKinds": [], + "members": [ + member(document, name, kind) + for document in documents + for name, kind in (("application", "APPLICATION"), ("foreign-sidecar", "APPLICATION"), ("initializer", "INIT")) + ], + } + return documents, declarations + + +def encode(documents, declarations): + return yaml.safe_dump_all(documents).encode(), json.dumps(declarations).encode() + + +def runtime_owner(declarations, replacement="S1"): + owner = declarations["members"][0] + owner.update({ + "ownerId": "world", "ownership": "RUNTIME_OWNER", + "catalogSources": [{"sourceId": "world-sql", "contract": "world/catalog/v1", "epoch": "1", "digest": DIGEST}], + "families": [{ + "familyId": "world-state", "catalogSourceId": "world-sql", "replacementClass": replacement, + "cleanupContract": { + "operation": "world/cleanup/v1", "requestIdentity": "world/request/v1", + "acknowledgement": "world/ack/v1", "retention": "world/retention/v1", + }, + }], + }) + return owner + + +class InventoryTest(unittest.TestCase): + def refuse(self, documents, declarations): + with self.assertRaises(inventory.InventoryError): + inventory.produce(*encode(documents, declarations)) + + def test_checked_in_interoperability_vector_matches_exact_producer_bytes(self): + directory = MODULE_PATH.parent / "fixtures" / "runtime-installation" + self.assertEqual( + inventory.produce((directory / "rendered.yaml").read_bytes(), (directory / "declarations.json").read_bytes()), + (directory / "candidate.json").read_bytes(), + ) + + def test_complete_every_supported_workload_and_container(self): + documents, declarations = fixture(("Pod", "Deployment", "StatefulSet", "DaemonSet", "ReplicaSet", "Job", "CronJob")) + documents[0]["spec"]["initContainers"][0]["restartPolicy"] = "Always" + raw_manifest, raw_declarations = encode(documents, declarations) + artifact = json.loads(inventory.produce(raw_manifest, raw_declarations)) + self.assertEqual(len(artifact["members"]), 21) + self.assertEqual({entry["image"] for entry in artifact["members"]}, {IMAGE}) + self.assertEqual(sum(entry["containerKind"] == "INIT" for entry in artifact["members"]), 7) + self.assertEqual(sum(entry["containerName"] == "foreign-sidecar" for entry in artifact["members"]), 7) + self.assertEqual(set(artifact), inventory.ROOT_FIELDS | {"renderedManifestDigest", "declarationsDigest"}) + + def test_exact_bytes_deterministic_compact_sorted_output(self): + documents, declarations = fixture(("CronJob", "Pod")) + runtime_owner(declarations) + raw_manifest, raw_declarations = encode(documents, declarations) + candidate = inventory.produce(raw_manifest, raw_declarations) + self.assertEqual(candidate, inventory.produce(raw_manifest, raw_declarations)) + artifact = json.loads(candidate) + self.assertEqual(candidate, (json.dumps(artifact, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + "\n").encode()) + self.assertEqual(artifact["renderedManifestDigest"], inventory.digest(raw_manifest)) + self.assertEqual(artifact["declarationsDigest"], inventory.digest(raw_declarations)) + self.assertEqual([inventory.identity(entry) for entry in artifact["members"]], sorted(inventory.identity(entry) for entry in artifact["members"])) + changed_manifest = json.loads(inventory.produce(raw_manifest + b"\n", raw_declarations)) + changed_declarations = json.loads(inventory.produce(raw_manifest, raw_declarations + b"\n")) + self.assertNotEqual(artifact["renderedManifestDigest"], changed_manifest["renderedManifestDigest"]) + self.assertNotEqual(artifact["declarationsDigest"], changed_declarations["declarationsDigest"]) + self.assertEqual(artifact["members"], changed_manifest["members"]) + self.assertEqual(artifact["members"], changed_declarations["members"]) + + def test_explicit_captured_binding_digest_retained_without_secret_inference(self): + documents, declarations = fixture() + declarations["inputBindings"]["secretContracts"] = [{"name": "workload-identity", "version": "captured-v3", "digest": DIGEST}] + artifact = json.loads(inventory.produce(*encode(documents, declarations))) + self.assertEqual(artifact["inputBindings"], declarations["inputBindings"]) + self.assertNotIn("qualified", artifact) + + def test_unresolved_retained_without_claiming_qualified_launch(self): + documents, declarations = fixture() + runtime_owner(declarations, "UNRESOLVED") + artifact = json.loads(inventory.produce(*encode(documents, declarations))) + owner = next(entry for entry in artifact["members"] if entry["ownerId"] == "world") + self.assertEqual(owner["families"][0]["replacementClass"], "UNRESOLVED") + self.assertNotIn("qualified", artifact) + self.assertNotIn("admission", artifact) + + def test_missing_extra_duplicate_container_declarations(self): + for change in ("missing", "extra", "duplicate"): + with self.subTest(change=change): + documents, declarations = fixture() + if change == "missing": + declarations["members"].pop() + elif change == "extra": + declarations["members"].append(member(documents[0], "absent")) + else: + declarations["members"].append(copy.deepcopy(declarations["members"][0])) + self.refuse(documents, declarations) + + def test_non_workload_classification_exact_and_explicit(self): + documents, declarations = fixture() + documents.append({"apiVersion": "v1", "kind": "ConfigMap", "metadata": {"name": "config"}, "data": {"mode": "exact"}}) + self.refuse(documents, declarations) + declarations["nonWorkloadKinds"] = [{"apiVersion": "v1", "kind": "ConfigMap"}] + inventory.produce(*encode(documents, declarations)) + for change in ("extra", "duplicate", "workload", "unknown-field"): + candidate = copy.deepcopy(declarations) + with self.subTest(change=change): + if change == "extra": + candidate["nonWorkloadKinds"].append({"apiVersion": "v1", "kind": "Secret"}) + elif change == "duplicate": + candidate["nonWorkloadKinds"] *= 2 + elif change == "workload": + candidate["nonWorkloadKinds"] = [{"apiVersion": "unsupported/v1", "kind": "Deployment"}] + else: + candidate["nonWorkloadKinds"][0]["trusted"] = True + self.refuse(documents, candidate) + + def test_hidden_podspec_and_unsupported_workloads_refused(self): + for kind in ("CustomWorker", "ReplicationController", "List"): + documents, declarations = fixture() + documents.append({"apiVersion": "custom/v1", "kind": kind, "spec": {"template": {"spec": {"containers": [{"name": "hidden", "image": IMAGE}]}}}}) + declarations["nonWorkloadKinds"] = [{"apiVersion": "custom/v1", "kind": kind}] + with self.subTest(kind=kind): + self.refuse(documents, declarations) + documents, declarations = fixture() + documents[0]["otherTemplate"] = {"spec": {"containers": [{"name": "hidden", "image": IMAGE}]}} + self.refuse(documents, declarations) + + def test_candidate_structural_budget_includes_added_images_and_digests(self): + documents, declarations = fixture() + declarations["inputBindings"]["configurations"] = [ + {"name": f"configuration-{index}", "version": "1", "digest": DIGEST} + for index in range(100) + ] + encoded = encode(documents, declarations) + artifact = json.loads(inventory.produce(*encoded)) + budget = [inventory.MAX_NODES] + inventory.bounded_tree(artifact, budget=budget) + artifact_nodes = inventory.MAX_NODES - budget[0] + with patch.object(inventory, "MAX_NODES", artifact_nodes): + self.assertEqual(json.loads(inventory.produce(*encoded)), artifact) + with patch.object(inventory, "MAX_NODES", artifact_nodes - 1): + inventory.bounded_tree(declarations) + with self.assertRaisesRegex(inventory.InventoryError, "document exceeds structural bounds"): + inventory.produce(*encoded) + + def test_tagged_hidden_podspec_and_non_json_values_refused(self): + documents, declarations = fixture() + declarations["nonWorkloadKinds"] = [{"apiVersion": "v1", "kind": "ConfigMap"}] + raw_manifest, raw_declarations = encode(documents, declarations) + for tagged in ( + b"!!omap [{containers: [{name: hidden, image: ignored}]}]", + b"!!pairs [{containers: [{name: hidden, image: ignored}]}]", + b"!!set {hidden: null}", + ): + manifest = raw_manifest + b"\n---\napiVersion: v1\nkind: ConfigMap\ndata: " + tagged + b"\n" + with self.subTest(tagged=tagged), self.assertRaisesRegex(inventory.InventoryError, "unsupported YAML/JSON value type"): + inventory.produce(manifest, raw_declarations) + + def test_duplicate_yaml_and_json_keys_and_yaml_aliases(self): + documents, declarations = fixture() + raw_manifest, raw_declarations = encode(documents, declarations) + for manifest in ( + raw_manifest + b"\n---\napiVersion: v1\nkind: ConfigMap\nkind: Pod\n", + raw_manifest.replace(b"name: application", b"name: application\n name: repeated"), + b"apiVersion: v1\nkind: Pod\nmetadata: &metadata {name: a}\nspec: *metadata\n", + ): + with self.subTest(manifest=manifest[-80:]), self.assertRaisesRegex(inventory.InventoryError, "duplicate YAML mapping key|aliases"): + inventory.produce(manifest, raw_declarations) + for raw in ( + raw_declarations[:-1] + b',"schema":"firemud-runtime-installation-declarations/v1"}', + raw_declarations.replace(b'"ownerId": ""', b'"ownerId": "", "ownerId": "world"', 1), + ): + with self.assertRaises(inventory.InventoryError): + inventory.produce(raw_manifest, raw) + + def test_namespace_image_mutation_duplicate_workload_and_ephemeral_refused(self): + for change in ("missing-namespace", "wrong-namespace", "mutable-image", "uppercase-digest", "duplicate-container", "duplicate-workload", "ephemeral"): + documents, declarations = fixture(("Pod",)) + with self.subTest(change=change): + if change == "missing-namespace": + del documents[0]["metadata"]["namespace"] + elif change == "wrong-namespace": + documents[0]["metadata"]["namespace"] = "elsewhere" + elif change == "mutable-image": + documents[0]["spec"]["containers"][0]["image"] = "example/world:latest" + elif change == "uppercase-digest": + documents[0]["spec"]["containers"][0]["image"] = IMAGE.upper() + elif change == "duplicate-container": + documents[0]["spec"]["initContainers"][0]["name"] = "application" + elif change == "duplicate-workload": + documents.append(copy.deepcopy(documents[0])) + else: + documents[0]["spec"]["ephemeralContainers"] = [{"name": "debug", "image": IMAGE}] + self.refuse(documents, declarations) + + def test_closed_shapes_types_bounds_and_catalog_cross_references(self): + changes = [ + lambda d: d.update(extra="field"), + lambda d: d.update(artifactId="00000000-0000-0000-0000-000000000000"), + lambda d: d.update(installationId="not-a-uuid"), + lambda d: d.update(environment="unknown"), + lambda d: d.update(generation=1), + lambda d: d.update(clusterUid=""), + lambda d: d.update(namespaceUid="x" * 257), + lambda d: d.update(sourceCommit="main"), + lambda d: d["executor"].update(versionDigest="sha256:no"), + lambda d: d["inputBindings"].pop("migrations"), + lambda d: d["inputBindings"].update(migrations=[{"name": "a", "version": "1", "digest": DIGEST}] * 2), + lambda d: d["members"][0].update(image=IMAGE), + lambda d: d["members"][0].update(containerKind="SIDECAR"), + lambda d: d["members"][0].update(ownership="UNKNOWN"), + lambda d: d["members"][0].update(ownerId=""), + lambda d: d["members"][0].update(catalogSources=[]), + lambda d: d["members"][0]["catalogSources"][0].update(epoch="01"), + lambda d: d["members"][0]["catalogSources"][0].update(epoch="0"), + lambda d: d["members"][0]["catalogSources"][0].update(epoch=1), + lambda d: d["members"][0]["catalogSources"][0].update(digest="sha256:" + "A" * 64), + lambda d: d["members"][0]["families"][0].update(catalogSourceId="absent"), + lambda d: d["members"][0]["families"][0].update(replacementClass="OTHER"), + lambda d: d["members"][0]["families"][0]["cleanupContract"].pop("retention"), + lambda d: d["members"][0]["families"][0]["cleanupContract"].update(operation=""), + lambda d: d["members"][0].update(ownership="NO_INSTANCE_STATE"), + lambda d: d["members"][0]["families"].append(copy.deepcopy(d["members"][0]["families"][0])), + lambda d: d.update(members=d["members"] * (inventory.MAX_MEMBERS + 1)), + ] + for index, change in enumerate(changes): + documents, declarations = fixture() + runtime_owner(declarations) + change(declarations) + with self.subTest(index=index): + self.refuse(documents, declarations) + + def test_owner_family_unique_across_different_containers(self): + documents, declarations = fixture() + owner = runtime_owner(declarations) + declarations["members"][1].update({field: copy.deepcopy(owner[field]) for field in ("ownerId", "ownership", "catalogSources", "families")}) + self.refuse(documents, declarations) + + def test_size_and_structure_bounds(self): + documents, declarations = fixture() + raw_manifest, raw_declarations = encode(documents, declarations) + for manifest, raw in ( + (b" " * (inventory.MAX_MANIFEST_BYTES + 1), raw_declarations), + (raw_manifest, b" " * (inventory.MAX_BYTES + 1)), + (raw_manifest, b"[" * 100 + b"0" + b"]" * 100), + (b"[" * 100 + b"0" + b"]" * 100, raw_declarations), + ): + with self.assertRaises(inventory.InventoryError): + inventory.produce(manifest, raw) + + def test_cli_exclusive_output_creation_and_retained_inputs(self): + documents, declarations = fixture() + raw_manifest, raw_declarations = encode(documents, declarations) + with tempfile.TemporaryDirectory() as directory: + directory = Path(directory) + manifest = directory / "manifest.yaml" + declaration = directory / "declarations.json" + output = directory / "candidate.json" + manifest.write_bytes(raw_manifest) + declaration.write_bytes(raw_declarations) + command = [sys.executable, str(MODULE_PATH), "--rendered-manifest", str(manifest), "--declarations", str(declaration), "--output", str(output)] + first = subprocess.run(command, capture_output=True, check=False) + self.assertEqual(first.returncode, 0, first.stderr) + self.assertEqual(output.read_bytes(), inventory.produce(raw_manifest, raw_declarations)) + output.write_bytes(b"retained-existing-evidence\n") + second = subprocess.run(command, capture_output=True, check=False) + self.assertNotEqual(second.returncode, 0) + self.assertEqual(output.read_bytes(), b"retained-existing-evidence\n") + self.assertEqual(manifest.read_bytes(), raw_manifest) + self.assertEqual(declaration.read_bytes(), raw_declarations) + + +if __name__ == "__main__": + unittest.main() diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index d04ad2cac4..2e68ca069a 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -4,6 +4,7 @@ jackson-2 = "2.22.4" jackson-3 = "3.2.4" tomcat = "11.0.27" jooq = "3.21.9" +jetbrains-annotations = "26.0.2" flyway = "13.12.0" mapstruct = "1.6.3" lombok = "1.18.48" @@ -84,6 +85,7 @@ protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "p protoc = { module = "com.google.protobuf:protoc", version.ref = "protobuf" } spotbugs-annotations = { module = "com.github.spotbugs:spotbugs-annotations", version.ref = "spotbugs" } +jetbrains-annotations = { module = "org.jetbrains:annotations", version.ref = "jetbrains-annotations" } opentelemetry-api = { module = "io.opentelemetry:opentelemetry-api", version.ref = "opentelemetry" } opentelemetry-sdk = { module = "io.opentelemetry:opentelemetry-sdk", version.ref = "opentelemetry" } diff --git a/services/game-design-service/build.gradle.kts b/services/game-design-service/build.gradle.kts index e72218dafb..5a8d8e3fed 100644 --- a/services/game-design-service/build.gradle.kts +++ b/services/game-design-service/build.gradle.kts @@ -81,6 +81,15 @@ val gameDesignClassesProof by configurations.creating { // Composed owner proofs load foreign migrations from disk; classes-only artifacts omit them. tasks.named("crossServiceTest") { + inputs + .file(rootProject.layout.projectDirectory.file("dev-tools/deploy/runtime-installation-inventory.py")) + .withPropertyName("runtimeInstallationInventoryProducer") + inputs + .file(rootProject.layout.projectDirectory.file("dev-tools/deploy/fixtures/runtime-installation/rendered.yaml")) + .withPropertyName("runtimeInstallationRenderedFixture") + inputs + .file(rootProject.layout.projectDirectory.file("dev-tools/deploy/fixtures/runtime-installation/declarations.json")) + .withPropertyName("runtimeInstallationDeclarationsFixture") inputs.dir(rootProject.layout.projectDirectory.dir("services/entity-management-service/src/main/resources/db/migration")) .withPropertyName("entityOwnerMigrations") inputs.dir(rootProject.layout.projectDirectory.dir("services/automation-scripting-service/src/main/resources/db/migration")) diff --git a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java index db5e87639d..bef6b7876e 100644 --- a/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java +++ b/services/game-design-service/src/test/java/crossservice/net/firedevops/firemud/gamedesign/data/RunOwnedFixtureOwnerCompositionCrossServiceTest.java @@ -12,6 +12,7 @@ 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.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.security.cert.CertificateFactory; @@ -52,6 +53,7 @@ import net.firedevops.firemud.worldmanagement.data.RunOwnedWorldFixedPresetResources; import net.firedevops.firemud.worldmanagement.service.impl.WorldLifecycleCommandServiceImpl; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociationRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -91,6 +93,8 @@ }) @Import(NoGrpcServerTestConfiguration.class) class RunOwnedFixtureOwnerCompositionCrossServiceTest extends TestDataSeederIntegrationSupport { + private static final String PREPARE_RUN_OWNED_FIXTURE = "prepareRunOwnedFixture"; + @Container static PostgreSQLContainer composedGameSessionPostgres = new PostgreSQLContainer<>(TestContainerImages.postgres()); @@ -235,6 +239,7 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat .CanonicalGameInstanceLaunchAssociationReadEvidence.CurrentGameInstanceStatus .STARTING); assertThat(starting.rowVersion()).isZero(); + var controlledInstallation = registerControlledInstallation(worldDatabase, testDirectory); var registry = new io.micrometer.core.instrument.simple.SimpleMeterRegistry(); var gsHandler = org.mockito.Mockito.spy(actualGsFixtureReadHandler(registry)); gsHandler.configureRunOwnedFixtureLaunchAssociationReadBoundary( @@ -322,7 +327,11 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat RunOwnedCanonicalWorldLaunchEvidence worldEvidence = withControlledGameSessionPeer(fixture, provider::requireAuthenticatedEvidence); var request = exactPreparedWorldRequest(worldEvidence); - var emptyWorldRows = allComposedOwnerRows(worldDatabase.dsl()); + // Freeze through the actual owner before capturing the no-allocation baseline. These + // controlled installation inputs establish no genuine external installation authority. + var emptyWorldRows = + controlledInstallation.withLaunchOwners( + starting.gameInstanceUuid(), () -> allComposedOwnerRows(worldDatabase.dsl())); org.mockito.Mockito.clearInvocations(authoredWorldSourceRepository); var changedSource = changedPreparedSourceEvidence(receipt.sourceEvidence()); org.mockito.Mockito.doReturn(java.util.Optional.of(changedSource)) @@ -333,8 +342,14 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat withControlledGameSessionPeer( fixture, () -> - ReflectionTestUtils.invokeMethod( - initialCommands, "prepareRunOwnedFixture", request, worldEvidence))) + controlledInstallation.withLaunchOwners( + starting.gameInstanceUuid(), + () -> + ReflectionTestUtils.invokeMethod( + initialCommands, + PREPARE_RUN_OWNED_FIXTURE, + request, + worldEvidence)))) .isInstanceOf(RuntimeException.class); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(emptyWorldRows); org.mockito.Mockito.verify(authoredWorldSourceRepository) @@ -346,9 +361,16 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat withControlledGameSessionPeer( fixture, () -> - (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) - ReflectionTestUtils.invokeMethod( - initialCommands, "prepareRunOwnedFixture", request, worldEvidence)); + controlledInstallation.withLaunchOwners( + starting.gameInstanceUuid(), + () -> + (net.firedevops.firemud.worldmanagement.dto + .WorldInstanceLifecycleSnapshotDto) + ReflectionTestUtils.invokeMethod( + initialCommands, + PREPARE_RUN_OWNED_FIXTURE, + request, + worldEvidence))); assertThat(prepared).isNotNull(); assertThat(prepared.status()).isEqualTo("PREPARING"); assertThat(prepared.lifecycleEpoch()).isEqualTo(1L); @@ -457,7 +479,7 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) ReflectionTestUtils.invokeMethod( initialCommands, - "prepareRunOwnedFixture", + PREPARE_RUN_OWNED_FIXTURE, request, initialProvider.requireAuthenticatedEvidence()))) .isEqualTo(prepared); @@ -495,11 +517,14 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat withControlledGameSessionPeer( fixture, () -> - ReflectionTestUtils.invokeMethod( - initialCommands, - "prepareRunOwnedFixture", - mismatchedRequest, - worldEvidence))) + controlledInstallation.withLaunchOwners( + starting.gameInstanceUuid(), + () -> + ReflectionTestUtils.invokeMethod( + initialCommands, + PREPARE_RUN_OWNED_FIXTURE, + mismatchedRequest, + worldEvidence)))) .isInstanceOf(IllegalArgumentException.class); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); org.mockito.Mockito.verifyNoInteractions(entityClient); @@ -544,9 +569,16 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat withControlledGameSessionPeer( fixture, () -> - (net.firedevops.firemud.worldmanagement.dto.WorldInstanceLifecycleSnapshotDto) - ReflectionTestUtils.invokeMethod( - replayCommands, "prepareRunOwnedFixture", request, replayEvidence))) + controlledInstallation.withLaunchOwners( + starting.gameInstanceUuid(), + () -> + (net.firedevops.firemud.worldmanagement.dto + .WorldInstanceLifecycleSnapshotDto) + ReflectionTestUtils.invokeMethod( + replayCommands, + PREPARE_RUN_OWNED_FIXTURE, + request, + replayEvidence)))) .isEqualTo(prepared); assertThat(allComposedOwnerRows(worldDatabase.dsl())).isEqualTo(worldRows); var reads = @@ -606,6 +638,101 @@ void actualProducerAndCanonicalOwnersComposeOverMutualTlsOwnerReads(@TempDir Pat } } + private WorldRuntimeInstallationRegistry registerControlledInstallation( + ComposedOwnerDatabase database, Path testDirectory) throws Exception { + Path root = Path.of("").toAbsolutePath(); + while (root != null && !Files.exists(root.resolve("settings.gradle.kts"))) { + root = root.getParent(); + } + if (root == null) throw new IllegalStateException("Repository fixture root unavailable"); + Path inputs = root.resolve("dev-tools/deploy/fixtures/runtime-installation"); + Path directory = Files.createDirectory(testDirectory.resolve("controlled-installation")); + Path rendered = directory.resolve("rendered.yaml"); + Path declarations = directory.resolve("declarations.json"); + Path candidate = directory.resolve("candidate.json"); + // Reuse the complete producer interoperability render, including its sidecar and init + // container. Only its controlled namespace/identity metadata changes for this composition. + Files.writeString( + rendered, + Files.readString(inputs.resolve("rendered.yaml"), StandardCharsets.UTF_8) + .replace("namespace: firemud", "namespace: " + NAMESPACE), + StandardCharsets.UTF_8); + var mapper = tools.jackson.databind.json.JsonMapper.builder().build(); + var declaration = + (tools.jackson.databind.node.ObjectNode) + mapper.readTree(Files.readAllBytes(inputs.resolve("declarations.json"))); + declaration.put("namespace", NAMESPACE); + declaration.put("environment", "local-dev"); + declaration.put("generation", "controlled-run-owned-owner-composition"); + declaration.put("clusterUid", "controlled-cluster"); + declaration.put("namespaceUid", "controlled-namespace"); + ((tools.jackson.databind.node.ObjectNode) declaration.get("executor")) + .put("identity", "controlled-run-owned-owner-composition/v1"); + for (var member : declaration.get("members")) { + ((tools.jackson.databind.node.ObjectNode) member).put("workloadNamespace", NAMESPACE); + } + Files.write(declarations, mapper.writeValueAsBytes(declaration)); + Path producerLog = directory.resolve("producer.log"); + Process producer = + new ProcessBuilder( + "python3", + root.resolve("dev-tools/deploy/runtime-installation-inventory.py").toString(), + "--rendered-manifest", + rendered.toString(), + "--declarations", + declarations.toString(), + "--output", + candidate.toString()) + .directory(root.toFile()) + .redirectErrorStream(true) + .redirectOutput(producerLog.toFile()) + .start(); + try { + assertThat(producer.waitFor(30, TimeUnit.SECONDS)) + .as("controlled installation candidate producer completed") + .isTrue(); + assertThat(producer.exitValue()).withFailMessage(Files.readString(producerLog)).isZero(); + } finally { + if (producer.isAlive()) { + producer.destroyForcibly(); + assertThat(producer.waitFor(5, TimeUnit.SECONDS)).isTrue(); + } + } + byte[] exact = Files.readAllBytes(candidate); + String schema = database.dsl().fetchSingle("SELECT current_schema()").get(0, String.class); + // This immutable in-memory hold is controlled test authority only. Candidate production and + // SQL readback do not qualify completed installation, protected delivery, custody or FRESH. + var installation = + new WorldRuntimeInstallationRegistry( + database.dsl(), + database.transactions(), + schema, + NAMESPACE, + () -> + new WorldRuntimeInstallationRegistry.HeldInstallation() { + private boolean closed; + + @Override + public byte[] exactArtifactBytes() { + return exact.clone(); + } + + @Override + public void requireCurrent() { + if (closed) + throw new IllegalStateException("Controlled installation hold is closed"); + } + + @Override + public void close() { + closed = true; + } + }); + installation.register(); + assertThat(installation.current().artifact().exactBytes()).containsExactly(exact); + return installation; + } + private GameSessionControlPlaneGrpcService actualGsFixtureReadHandler( io.micrometer.core.instrument.MeterRegistry registry) throws Exception { // Its public production constructor has package-private legacy parameter types. No fixture diff --git a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java index 599085a1bf..90fdfd7209 100644 --- a/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java +++ b/services/game-session-service/src/test/java/integration/net/firedevops/firemud/gamesession/service/InitialGameplayLoginContextRedisIntegrationTest.java @@ -609,9 +609,15 @@ void actualJournalCleanupRetiresOnlyInsideExactCurrentExclusionAndOldReceiptCann .isEqualTo(original.callerContextId().toString()); return receipt; }); - var owner = cleanup(client(provider, authority, 1), account); + // This positive closure proof allows replica fsync under shared-runner load. + // Insufficient-acknowledgement cases retain their separate short failure deadline. + var owner = + cleanup( + client(provider, authority, new AcknowledgementPolicy(Profile.REPLICATED, 1, 1, 3_000)), + account); owner.reserve(original); assertThat(owner.abandonAndRetire(original).status()) + .as("physical cleanup closure observations: %s", provider.traces) .isEqualTo(InitialGameplayLoginCleanupOwner.Status.ACCOUNT_RETIRED); assertThat(authority.active).isFalse(); authority.condition = "unavailable"; diff --git a/services/world-management-service/build.gradle.kts b/services/world-management-service/build.gradle.kts index a703fd85e0..e1368383af 100644 --- a/services/world-management-service/build.gradle.kts +++ b/services/world-management-service/build.gradle.kts @@ -14,6 +14,8 @@ firemudJooq { dependencies { implementation(project(":common-security")) + // Resolve the annotations declared provided/optional by the pinned jOOQ API during analysis. + compileOnly(libs.jetbrains.annotations) testImplementation(testFixtures(project(":common-platform-core"))) testImplementation(libs.bouncycastle.pkix) testCompileOnly(libs.spotbugs.annotations) @@ -35,6 +37,10 @@ dependencies { add("crossServiceTestImplementation", "io.grpc:grpc-util:${libs.versions.grpc.get()}") } +tasks.named("test") { + inputs.file(rootProject.file("dev-tools/deploy/fixtures/runtime-installation/candidate.json")) +} + // Receiving owner proof uses World classes without its application or Flyway resources. val worldClassesProofJar by tasks.registering(Jar::class) { archiveClassifier.set("classes-proof") diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java index f7232667d1..c542df46e1 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationService.java @@ -2,6 +2,7 @@ import java.util.Objects; import java.util.Optional; +import java.util.UUID; import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; @@ -13,6 +14,7 @@ */ public final class WorldCanonicalInstanceActivationService { private final WorldCanonicalInstanceActivationRepository repository; + private final WorldRuntimeInstallationRegistry installationRegistry; /** * Production-safe default: request-only transports cannot start activation without the distinct @@ -21,6 +23,7 @@ public final class WorldCanonicalInstanceActivationService { public WorldCanonicalInstanceActivationService( WorldCanonicalInstanceActivationRepository repository) { this.repository = Objects.requireNonNull(repository, "repository"); + this.installationRegistry = null; } /** @@ -31,9 +34,19 @@ public WorldCanonicalInstanceActivationService( public WorldCanonicalInstanceActivationService( WorldCanonicalInstanceActivationRepository repository, ActivationAuthorityVerifier ignored) { this.repository = Objects.requireNonNull(repository, "repository"); + this.installationRegistry = null; Objects.requireNonNull(ignored, "verifier"); } + /** Explicit protected installation composition; creates no registered activation route. */ + public WorldCanonicalInstanceActivationService( + WorldCanonicalInstanceActivationRepository repository, + WorldRuntimeInstallationRegistry installationRegistry) { + this.repository = Objects.requireNonNull(repository, "repository"); + this.installationRegistry = + Objects.requireNonNull(installationRegistry, "installationRegistry"); + } + /** * Replays an exact retained legacy result. Request-only fresh activation is denied: it cannot * carry Account's distinct source-protection receipt, and this path intentionally cannot expose @@ -61,8 +74,16 @@ public WorldOriginalStartSessionActivationTerminalEvidence activateProtected( requireNoActiveTransaction(); try (held) { held.requireHeld(); + var retained = repository.readTerminalEvidence(protection); + if (retained.isPresent()) { + held.requireHeld(); + return retained.orElseThrow(); + } + requireInstallationRegistry(); WorldOriginalStartSessionActivationTerminalEvidence terminal = - repository.activateProtected(protection, held); + installationRegistry.withLaunchOwners( + protection.request().worldActivationRequest().canonicalGameInstanceId(), + () -> repository.activateProtected(protection, held)); held.requireHeld(); return terminal; } @@ -90,6 +111,21 @@ public WorldOriginalStartSessionActivationTerminalEvidence abortProtected( return repository.abortProtected(protection, terminalCode); } + /** + * Read-only early refusal; the held installation check at actual commit remains authoritative. + */ + void preflightInstallationRegistry(UUID gameInstanceId) { + requireInstallationRegistry(); + installationRegistry.preflightLaunchOwners(gameInstanceId); + } + + /** Rejects missing composition before the orchestrator acquires durable Account protection. */ + void requireInstallationRegistry() { + if (installationRegistry == null) { + throw new ActivationDeniedException("Protected current-installation registry is unavailable"); + } + } + private static void requireNoActiveTransaction() { if (TransactionSynchronizationManager.isActualTransactionActive() || TransactionSynchronizationManager.isSynchronizationActive()) { diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java index 324bf3042a..2f6cc787a7 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationRepository.java @@ -108,15 +108,77 @@ public WorldCanonicalInstancePreparationRepository( } /** - * Runs the one owner transaction, then independently reads its committed immutable result. The - * Account source-protection handle remains open through the transaction manager's commit path; - * the stored original Game Session lease is checked separately at actual World admission. + * Read-only hint used solely to avoid applying fresh-installation preflight to a historical + * COMMITTED retry. It is not authenticated replay or execution authority: the unchanged held + * verifier and exact participation-bound retained-result read remain mandatory afterward. */ - public Result materialize( + public boolean hasRetainedCommittedCandidate( + Input input, WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput operation) { + Objects.requireNonNull(input, "input"); + Objects.requireNonNull(operation, "operation"); + requireNoActiveTransaction("World committed preparation candidate read"); + String exactInput = inputJson(input); + String inputDigest = digest(exactInput.getBytes(StandardCharsets.UTF_8)); + var evidence = input.gameSessionReadEvidence(); + return Boolean.TRUE.equals( + readTransaction.execute( + status -> { + applyDatabaseTimeouts(); + return dsl.fetchExists( + dsl.selectOne() + .from("world_canonical_instance_execution") + .where( + "target_namespace=? AND canonical_tenant_id=? AND control_plane_request_id=?" + + " AND canonical_game_instance_id=? AND operation_state='COMMITTED'" + + " AND original_post_authorization_tuple=?" + + " AND original_post_authorization_tuple_sha256=?" + + " AND game_session_owner_mutation_id=? AND game_session_owner_attempt_id=?" + + " AND game_session_owner_fence=? AND preparation_input_digest=?" + + " AND preparation_input_json=? AND original_attempt_evidence_bytes IS NOT NULL", + evidence.targetNamespace(), + evidence.canonicalTenantId(), + evidence.controlPlaneRequestId(), + input.canonicalGameInstanceId(), + operation.originalPostAuthorizationTuple(), + HexFormat.of() + .formatHex(sha256(operation.originalPostAuthorizationTuple())), + operation.gameSessionOwnerMutationId(), + operation.gameSessionOwnerAttemptId(), + operation.gameSessionOwnerFence(), + inputDigest, + exactInput)); + })); + } + + /** + * Reads the immutable result only when the exact typed operation is already COMMITTED. This + * read-only historical retry does not require a current installation snapshot; all absent, + * PENDING and ABORTED operations remain on the installation-guarded materialization path. + */ + Optional readRetainedCommittedResult( Input input, WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { + VerifiedPreparationInput verified = + verifyPreparationInput( + input, authority, "Canonical World preparation retained-result read"); + WorldCanonicalInstanceExecutionIdentity executionIdentity = verified.identity(); + + Optional retained = readExactExecution(executionIdentity).operation(); + if (retained.isEmpty() || retained.orElseThrow().state() != ExecutionState.COMMITTED) { + return Optional.empty(); + } + return Optional.of(readCommittedResult(input, retained.orElseThrow())); + } + + private record VerifiedPreparationInput( + WorldCanonicalInstanceExecutionIdentity identity, String inputJson) {} + + private VerifiedPreparationInput verifyPreparationInput( + Input input, + WorldCanonicalInstancePreparationService.HeldCommitAuthority authority, + String operation) { Objects.requireNonNull(input, "input"); Objects.requireNonNull(authority, "authority"); - requireNoActiveTransaction("Canonical World preparation"); + requireNoActiveTransaction(operation); WorldCanonicalInstanceExecutionIdentity executionIdentity = Objects.requireNonNull( authority.executionIdentity(), @@ -126,8 +188,22 @@ public Result materialize( "Fresh World admission requires Account's exact original Game Session attempt observation"); } String inputJson = inputJson(input); - String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); executionIdentity.requireMatches(input, inputJson); + return new VerifiedPreparationInput(executionIdentity, inputJson); + } + + /** + * Runs the one owner transaction, then independently reads its committed immutable result. The + * Account source-protection handle remains open through the transaction manager's commit path; + * the stored original Game Session lease is checked separately at actual World admission. + */ + public Result materialize( + Input input, WorldCanonicalInstancePreparationService.HeldCommitAuthority authority) { + VerifiedPreparationInput verified = + verifyPreparationInput(input, authority, "Canonical World preparation"); + WorldCanonicalInstanceExecutionIdentity executionIdentity = verified.identity(); + String inputJson = verified.inputJson(); + String inputDigest = digest(inputJson.getBytes(StandardCharsets.UTF_8)); ExecutionLookup lookup = readExactExecution(executionIdentity); Optional retained = lookup.operation(); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java index ea5153fc54..8c8765f974 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationService.java @@ -25,17 +25,28 @@ public final class WorldCanonicalInstancePreparationService { private final WorldCanonicalInstancePreparationRepository repository; private final OriginalOperationCommitAuthorityVerifier originalOperationVerifier; private final OriginalOperationRecoveryVerifier recoveryVerifier; + private final WorldRuntimeInstallationRegistry installationRegistry; /** Constructs the production-safe default: all attempts fail closed. */ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository) { - this(repository, null, WorldCanonicalInstancePreparationService::denyRecoveryByDefault, true); + this( + repository, + null, + WorldCanonicalInstancePreparationService::denyRecoveryByDefault, + null, + true); } /** Retained legacy constructor; an untyped verifier cannot authorize a fresh execution. */ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, CommitAuthorityVerifier verifier) { - this(repository, null, WorldCanonicalInstancePreparationService::denyRecoveryByDefault, true); + this( + repository, + null, + WorldCanonicalInstancePreparationService::denyRecoveryByDefault, + null, + true); Objects.requireNonNull(verifier, "verifier"); } @@ -47,6 +58,7 @@ public WorldCanonicalInstancePreparationService( repository, Objects.requireNonNull(verifier, "verifier"), WorldCanonicalInstancePreparationService::denyRecoveryByDefault, + null, true); } @@ -58,7 +70,7 @@ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, CommitAuthorityVerifier verifier, OriginalOperationRecoveryVerifier recoveryVerifier) { - this(repository, null, recoveryVerifier, true); + this(repository, null, recoveryVerifier, null, true); Objects.requireNonNull(verifier, "verifier"); } @@ -67,15 +79,31 @@ public WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, OriginalOperationCommitAuthorityVerifier verifier, OriginalOperationRecoveryVerifier recoveryVerifier) { - this(repository, Objects.requireNonNull(verifier, "verifier"), recoveryVerifier, true); + this(repository, Objects.requireNonNull(verifier, "verifier"), recoveryVerifier, null, true); + } + + /** Explicit installation owner composition; all existing constructors remain default denied. */ + public WorldCanonicalInstancePreparationService( + WorldCanonicalInstancePreparationRepository repository, + OriginalOperationCommitAuthorityVerifier verifier, + OriginalOperationRecoveryVerifier recoveryVerifier, + WorldRuntimeInstallationRegistry installationRegistry) { + this( + repository, + Objects.requireNonNull(verifier, "verifier"), + recoveryVerifier, + Objects.requireNonNull(installationRegistry, "installationRegistry"), + true); } private WorldCanonicalInstancePreparationService( WorldCanonicalInstancePreparationRepository repository, OriginalOperationCommitAuthorityVerifier originalOperationVerifier, OriginalOperationRecoveryVerifier recoveryVerifier, + WorldRuntimeInstallationRegistry installationRegistry, boolean ownerTypedConstructor) { this.repository = Objects.requireNonNull(repository, "repository"); + this.installationRegistry = installationRegistry; if (!ownerTypedConstructor) throw new IllegalArgumentException("Constructor marker is required"); this.originalOperationVerifier = originalOperationVerifier; @@ -136,6 +164,11 @@ public Result prepare( "Canonical World preparation has no authenticated Account participation verifier"); } operationInput.requireMatches(input, input.gameSessionReadEvidence().targetNamespace()); + // This candidate only skips preflight, never Account authentication or the exact retained read. + if (!repository.hasRetainedCommittedCandidate(input, operationInput)) { + requireInstallationRegistry(); + installationRegistry.preflightLaunchOwners(input.canonicalGameInstanceId()); + } HeldCommitAuthority held = Objects.requireNonNull( originalOperationVerifier.verifyAndHold(input, operationInput), @@ -145,7 +178,20 @@ public Result prepare( held.executionIdentity() .requireMatches( input, operationInput, WorldCanonicalInstancePreparationRepository.inputJson(input)); - return repository.materialize(input, held); + Optional retained = repository.readRetainedCommittedResult(input, held); + if (retained.isPresent()) { + return retained.orElseThrow(); + } + requireInstallationRegistry(); + return installationRegistry.withLaunchOwners( + input.canonicalGameInstanceId(), () -> repository.materialize(input, held)); + } + } + + private void requireInstallationRegistry() { + if (installationRegistry == null) { + throw new PreparationDeniedException( + "Protected current-installation registry is unavailable"); } } diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java index e4f7c9d63d..85c61d7053 100644 --- a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationService.java @@ -51,6 +51,9 @@ public WorldOriginalStartSessionActivationTerminalEvidence activate( return readback.terminalEvidence(); } + activationService.preflightInstallationRegistry( + input.worldActivationRequest().canonicalGameInstanceId()); + // The distinct Account protection is acquired before any World writable transaction. This // interface is the authenticated Account workload client; the carrier itself is integrity-only. var protection = accountProtectionClient.acquire(input); diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifact.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifact.java new file mode 100644 index 0000000000..fe7e576ffa --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifact.java @@ -0,0 +1,362 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import com.google.protobuf.ByteString; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.StreamReadFeature; +import tools.jackson.core.json.JsonFactory; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.json.JsonMapper; + +/** + * Closed exact candidate evidence; parsing establishes no installation or registration authority. + */ +public final class WorldRuntimeInstallationArtifact { + public static final int MAX_BYTES = 4 * 1024 * 1024; + private static final String SCHEMA = "firemud-runtime-installation-inventory/v1"; + private static final String DIGEST = "sha256:[0-9a-f]{64}"; + private static final String DNS_LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"; + private static final String DNS_NAME = "[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?"; + private static final Set ENVIRONMENTS = + Set.of( + "local-dev", + "pr-preview", + "dev-demo-cluster", + "hobby-self-hosted", + "staging", + "production"); + private static final Set BINDINGS = + Set.of( + "migrations", + "configurations", + "mountedResources", + "secretContracts", + "externalBindings"); + private static final Set ROOT_FIELDS = + Set.of( + "schema", + "artifactId", + "installationId", + "environment", + "generation", + "clusterUid", + "namespaceUid", + "namespace", + "sourceCommit", + "renderedManifestDigest", + "declarationsDigest", + "executor", + "inputBindings", + "members"); + private static final Set MEMBER_FIELDS = + Set.of( + "workloadApiVersion", + "workloadKind", + "workloadNamespace", + "workloadName", + "containerKind", + "containerName", + "image", + "ownerId", + "ownership", + "catalogSources", + "families"); + private static final List IDENTITY_FIELDS = + List.of( + "workloadApiVersion", + "workloadKind", + "workloadNamespace", + "workloadName", + "containerKind", + "containerName"); + private static final Set> WORKLOADS = + Set.of( + List.of("v1", "Pod"), + List.of("apps/v1", "Deployment"), + List.of("apps/v1", "StatefulSet"), + List.of("apps/v1", "DaemonSet"), + List.of("apps/v1", "ReplicaSet"), + List.of("batch/v1", "Job"), + List.of("batch/v1", "CronJob")); + private static final JsonMapper JSON = + JsonMapper.builder( + JsonFactory.builder() + .streamReadConstraints( + StreamReadConstraints.builder() + .maxNestingDepth(64) + .maxStringLength(MAX_BYTES) + .maxNumberLength(64) + .build()) + .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION) + .build()) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS) + .build(); + + private final ByteString exactBytes; + private final UUID artifactId; + private final UUID installationId; + private final String namespace; + private final boolean resolved; + + private WorldRuntimeInstallationArtifact( + ByteString bytes, UUID artifactId, UUID installationId, String namespace, boolean resolved) { + exactBytes = bytes; + this.artifactId = artifactId; + this.installationId = installationId; + this.namespace = namespace; + this.resolved = resolved; + } + + public byte[] exactBytes() { + return exactBytes.toByteArray(); + } + + public String digest() { + return WorldRuntimeFamilyCatalog.sha256(exactBytes.toByteArray()); + } + + public UUID artifactId() { + return artifactId; + } + + public UUID installationId() { + return installationId; + } + + public String namespace() { + return namespace; + } + + /** Classification prerequisite only; this does not qualify installation, FRESH or admission. */ + public void requireResolved() { + require(resolved, "Complete runtime-owner set with resolved family classifications required"); + } + + /** + * Validate the complete closed artifact and retain its original bytes without reserialization. + */ + public static WorldRuntimeInstallationArtifact parse(byte[] bytes) { + require( + bytes != null && bytes.length > 0 && bytes.length <= MAX_BYTES, + "Artifact byte bound exceeded"); + ByteString retained = ByteString.copyFrom(bytes); + try { + String decoded = + StandardCharsets.UTF_8 + .newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(retained.toByteArray())) + .toString(); + JsonNode root = JSON.readTree(decoded); + boundedTree(root, 0, new int[] {200000}); + fields(root, ROOT_FIELDS); + require(SCHEMA.equals(text(root, "schema", 256, false)), "Unsupported installation schema"); + UUID artifactId = uuid(root, "artifactId"); + UUID installationId = uuid(root, "installationId"); + require(ENVIRONMENTS.contains(text(root, "environment", 256, false)), "Invalid environment"); + for (String field : List.of("generation", "clusterUid", "namespaceUid")) { + text(root, field, 256, false); + } + String namespace = matched(root, "namespace", DNS_LABEL, 63); + matched(root, "sourceCommit", "[0-9a-f]{40}", 40); + matched(root, "renderedManifestDigest", DIGEST, 256); + matched(root, "declarationsDigest", DIGEST, 256); + JsonNode executor = root.get("executor"); + fields(executor, Set.of("identity", "versionDigest")); + text(executor, "identity", 512, false); + matched(executor, "versionDigest", DIGEST, 256); + bindings(root.get("inputBindings")); + JsonNode members = root.get("members"); + array(members, 1024); + List previous = null; + Set> ownerFamilies = new HashSet<>(); + boolean hasRuntimeOwner = false; + boolean allResolved = true; + for (JsonNode member : members) { + fields(member, MEMBER_FIELDS); + require( + WORKLOADS.contains( + List.of( + text(member, "workloadApiVersion", 256, false), + text(member, "workloadKind", 256, false))), + "Unsupported workload"); + require( + namespace.equals(text(member, "workloadNamespace", 256, false)), "Namespace mismatch"); + matched(member, "workloadName", DNS_NAME, 253); + matched(member, "containerName", DNS_LABEL, 63); + require( + Set.of("APPLICATION", "INIT").contains(text(member, "containerKind", 256, false)), + "Unsupported container kind"); + matched(member, "image", "[a-z0-9][a-z0-9./:_-]*@sha256:[0-9a-f]{64}", 1024); + List current = new ArrayList<>(); + for (String field : IDENTITY_FIELDS) current.add(text(member, field, 256, false)); + require( + previous == null || compare(previous, current) < 0, + "Unsorted or duplicate member identity"); + previous = current; + String ownership = text(member, "ownership", 256, false); + require( + Set.of("RUNTIME_OWNER", "NO_INSTANCE_STATE").contains(ownership), "Invalid ownership"); + boolean runtimeOwner = ownership.equals("RUNTIME_OWNER"); + String ownerId = text(member, "ownerId", 256, !runtimeOwner); + JsonNode sources = member.get("catalogSources"); + JsonNode families = member.get("families"); + array(sources, 64); + array(families, 256); + if (runtimeOwner) { + require(!sources.isEmpty(), "Runtime owner requires catalog evidence"); + hasRuntimeOwner = true; + } else { + require( + sources.isEmpty() && families.isEmpty(), "NO_INSTANCE_STATE has ownership evidence"); + } + Set sourceIds = sources(sources); + for (JsonNode family : families) { + fields( + family, Set.of("familyId", "catalogSourceId", "replacementClass", "cleanupContract")); + String familyId = text(family, "familyId", 256, false); + require(ownerFamilies.add(List.of(ownerId, familyId)), "Duplicate owner/family identity"); + require( + sourceIds.contains(text(family, "catalogSourceId", 256, false)), + "Missing member-local catalog source"); + String replacement = text(family, "replacementClass", 256, false); + require( + Set.of("S1", "S2", "S3", "UNRESOLVED").contains(replacement), + "Invalid replacement class"); + allResolved &= !replacement.equals("UNRESOLVED"); + JsonNode cleanup = family.get("cleanupContract"); + Set cleanupFields = + Set.of("operation", "requestIdentity", "acknowledgement", "retention"); + fields(cleanup, cleanupFields); + for (String field : cleanupFields) text(cleanup, field, 512, false); + } + } + return new WorldRuntimeInstallationArtifact( + retained, artifactId, installationId, namespace, hasRuntimeOwner && allResolved); + } catch (java.io.IOException | tools.jackson.core.JacksonException invalid) { + throw new IllegalArgumentException("Invalid closed runtime installation artifact", invalid); + } + } + + private static void bindings(JsonNode node) { + fields(node, BINDINGS); + for (String category : BINDINGS) { + JsonNode entries = node.get(category); + array(entries, 256); + Set names = new HashSet<>(); + for (JsonNode entry : entries) { + fields(entry, Set.of("name", "version", "digest")); + require(names.add(text(entry, "name", 256, false)), "Duplicate input binding"); + text(entry, "version", 512, false); + matched(entry, "digest", DIGEST, 256); + } + } + } + + private static Set sources(JsonNode sources) { + Set ids = new HashSet<>(); + for (JsonNode source : sources) { + fields(source, Set.of("sourceId", "contract", "epoch", "digest")); + require(ids.add(text(source, "sourceId", 256, false)), "Duplicate member catalog source"); + text(source, "contract", 512, false); + matched(source, "epoch", "[1-9][0-9]{0,18}", 19); + matched(source, "digest", DIGEST, 256); + } + return ids; + } + + private static UUID uuid(JsonNode root, String field) { + String value = text(root, field, 36, false); + UUID parsed = UUID.fromString(value); + require( + parsed.toString().equals(value) && !parsed.equals(new UUID(0, 0)), + "Canonical non-nil UUID required"); + return parsed; + } + + private static int compare(List first, List second) { + for (int i = 0; i < first.size(); i++) { + int compared = first.get(i).compareTo(second.get(i)); + if (compared != 0) return compared; + } + return 0; + } + + private static void fields(JsonNode node, Set expected) { + if (node == null || !node.isObject()) { + throw new IllegalArgumentException("Closed object required"); + } + Set actual = new HashSet<>(); + node.propertyNames().forEach(actual::add); + require(actual.equals(expected), "Unknown or missing installation field"); + } + + private static String text(JsonNode node, String field, int maximum, boolean empty) { + JsonNode value = node.get(field); + if (value == null || !value.isTextual()) { + throw new IllegalArgumentException("Text field required: " + field); + } + String result = value.asText(); + require(empty || !result.isEmpty(), "Empty installation field: " + field); + require( + result.isEmpty() + || (!whitespace(result.codePointAt(0)) + && !whitespace(result.codePointBefore(result.length()))), + "Whitespace around installation field: " + field); + for (int i = 0; i < result.length(); i++) { + char character = result.charAt(i); + require(character >= 32 && character != 127, "Control character in installation field"); + if (Character.isHighSurrogate(character)) { + require( + i + 1 < result.length() && Character.isLowSurrogate(result.charAt(i + 1)), + "Invalid Unicode scalar"); + i++; + } else { + require(!Character.isLowSurrogate(character), "Invalid Unicode scalar"); + } + } + require( + result.getBytes(StandardCharsets.UTF_8).length <= maximum, + "Installation field byte bound exceeded"); + return result; + } + + private static boolean whitespace(int value) { + return Character.isWhitespace(value) || Character.isSpaceChar(value) || value == 0x85; + } + + private static String matched(JsonNode node, String field, String pattern, int maximum) { + String value = text(node, field, maximum, false); + require(value.matches(pattern), "Invalid installation field format: " + field); + return value; + } + + private static void array(JsonNode node, int maximum) { + require( + node != null && node.isArray() && node.size() <= maximum, + "Bounded installation array required"); + } + + private static void boundedTree(JsonNode node, int depth, int[] remaining) { + if (node == null || depth > 64 || --remaining[0] < 0) { + throw new IllegalArgumentException("Installation structural bound exceeded"); + } + if (node.isObject() || node.isArray()) { + for (JsonNode child : node) boundedTree(child, depth + 1, remaining); + } + } + + private static void require(boolean valid, String message) { + if (!valid) throw new IllegalArgumentException(message); + } +} diff --git a/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistry.java b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistry.java new file mode 100644 index 0000000000..9ae41a57b6 --- /dev/null +++ b/services/world-management-service/src/main/java/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistry.java @@ -0,0 +1,323 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import java.util.Arrays; +import java.util.Objects; +import java.util.UUID; +import java.util.function.Supplier; +import net.firedevops.firemud.common.grpc.GrpcPeerIdentity; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.springframework.transaction.PlatformTransactionManager; +import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionSynchronizationManager; +import org.springframework.transaction.support.TransactionTemplate; + +/** + * Manually composed World installation owner. Ordinary requests cannot supply inventory bytes. The + * protected source is unavailable by default; no constructor registers a runtime component. + */ +public final class WorldRuntimeInstallationRegistry { + private final DSLContext dsl; + private final String schema; + private final String namespace; + private final ProtectedInstallationSource source; + private final TransactionTemplate write; + private final TransactionTemplate read; + + public WorldRuntimeInstallationRegistry( + DSLContext dsl, PlatformTransactionManager transactions, String schema, String namespace) { + this( + dsl, + transactions, + schema, + namespace, + () -> { + throw new RegistryUnavailableException( + "Protected current-installation source is unavailable"); + }); + } + + public WorldRuntimeInstallationRegistry( + DSLContext dsl, + PlatformTransactionManager transactions, + String schema, + String namespace, + ProtectedInstallationSource source) { + this.dsl = Objects.requireNonNull(dsl, "dsl"); + if (schema == null + || !schema.matches("[a-z][a-z0-9_]{0,62}") + || !GrpcPeerIdentity.isValidNamespace(namespace)) { + throw new IllegalArgumentException("Fixed World schema and namespace required"); + } + this.schema = schema; + this.namespace = namespace; + this.source = Objects.requireNonNull(source, "source"); + write = new TransactionTemplate(Objects.requireNonNull(transactions, "transactions")); + write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + read = new TransactionTemplate(transactions); + read.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); + read.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ); + read.setReadOnly(true); + } + + /** Installs the exact protected current artifact and independently reads its committed bytes. */ + public Registration register() { + independent(); + try (HeldInstallation held = + Objects.requireNonNull(source.acquireCurrent(), "held installation")) { + held.requireCurrent(); + var artifact = artifact(held); + Registration committed = + write.execute( + status -> { + // One namespace serializes registration; source authority remains held through + // commit. + dsl.execute( + "SELECT pg_advisory_xact_lock(hashtextextended(?,0))", + "world-runtime-registry/" + namespace); + Record current = + dsl.fetchOne( + "SELECT * FROM " + + table("world_runtime_installation_current") + + " WHERE target_namespace=? FOR UPDATE", + namespace); + Record old = + dsl.fetchOne( + "SELECT * FROM " + + table("world_runtime_installation_registration") + + " WHERE artifact_id=?", + artifact.artifactId()); + Registration registered; + if (old != null) { + registered = registration(old); + exact(registered.artifact(), artifact); + if (current == null + || registered.revision() != current.get("revision", Long.class)) { + throw new RegistryUnavailableException( + "Historical installation cannot replace the current registration"); + } + } else { + Record inserted = + dsl.fetchSingle( + "INSERT INTO " + + table("world_runtime_installation_registration") + + " (artifact_id,installation_id,target_namespace,artifact_bytes,artifact_digest) VALUES (?,?,?,?,?) RETURNING *", + artifact.artifactId(), + artifact.installationId(), + namespace, + artifact.exactBytes(), + artifact.digest()); + registered = registration(inserted); + dsl.execute( + "INSERT INTO " + + table("world_runtime_installation_current") + + " (target_namespace,revision,artifact_digest) VALUES (?,?,?) ON CONFLICT (target_namespace)" + + " DO UPDATE SET revision=EXCLUDED.revision,artifact_digest=EXCLUDED.artifact_digest", + namespace, + registered.revision(), + artifact.digest()); + } + held.requireCurrent(); + exact(artifact(held), artifact); + return registered; + }); + held.requireCurrent(); + Registration result = current(); + if (committed.revision() != result.revision()) { + throw new RegistryUnavailableException("Registration changed before independent readback"); + } + exact(result.artifact(), artifact); + return result; + } + } + + /** Independent durable readback is provenance, not evidence that the source is currently held. */ + public Registration current() { + independent(); + return read.execute(status -> currentInTransaction(false)); + } + + /** + * Read-only readiness check before acquiring durable Account protection. An absent frozen set is + * allowed; an existing set must match exactly. This is not a race guarantee or launch authority: + * the protected source is released on return and {@link #withLaunchOwners} must still guard the + * actual synchronous launch commit. + */ + public void preflightLaunchOwners(UUID gameInstanceId) { + independent(); + if (gameInstanceId == null || gameInstanceId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil canonical game instance required"); + } + try (HeldInstallation held = + Objects.requireNonNull(source.acquireCurrent(), "held installation")) { + held.requireCurrent(); + var artifact = artifact(held); + artifact.requireResolved(); + read.executeWithoutResult( + status -> { + var registered = currentInTransaction(false); + exact(registered.artifact(), artifact); + if (dsl.fetchExists( + dsl.selectOne() + .from(table("world_runtime_required_owner_snapshot")) + .where("canonical_game_instance_id=?", gameInstanceId))) { + requireFrozen(gameInstanceId, registered); + } + }); + held.requireCurrent(); + exact(artifact(held), artifact); + } + } + + /** + * Freezes the complete set before invoking an existing launch owner and keeps the protected + * installation authority held through that owner's actual synchronous commit. This grants no + * Account, publication, FRESH, lifecycle activation or admission authority. + */ + public T withLaunchOwners(UUID gameInstanceId, Supplier launchOwner) { + independent(); + if (gameInstanceId == null || gameInstanceId.equals(new UUID(0, 0))) { + throw new IllegalArgumentException("Non-nil canonical game instance required"); + } + Objects.requireNonNull(launchOwner, "launchOwner"); + try (HeldInstallation held = + Objects.requireNonNull(source.acquireCurrent(), "held installation")) { + held.requireCurrent(); + var artifact = artifact(held); + artifact.requireResolved(); + write.executeWithoutResult( + status -> { + var registered = currentInTransaction(true); + exact(registered.artifact(), artifact); + dsl.execute( + "INSERT INTO " + + table("world_runtime_required_owner_snapshot") + + " (canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" + + " VALUES (?,?,?,?," + + schema + + ".world_runtime_required_owners(?)) ON CONFLICT (canonical_game_instance_id) DO NOTHING", + gameInstanceId, + namespace, + registered.revision(), + artifact.digest(), + artifact.exactBytes()); + requireFrozen(gameInstanceId, registered); + held.requireCurrent(); + exact(artifact(held), artifact); + }); + read.executeWithoutResult( + status -> requireFrozen(gameInstanceId, currentInTransaction(false))); + held.requireCurrent(); + exact(artifact(held), artifact); + T result = launchOwner.get(); + held.requireCurrent(); + exact(artifact(held), artifact); + return result; + } + } + + private void requireFrozen(UUID id, Registration registration) { + Record frozen = + dsl.fetchOne( + "SELECT * FROM " + + table("world_runtime_required_owner_snapshot") + + " WHERE canonical_game_instance_id=? AND target_namespace=? AND registry_revision=?" + + " AND artifact_digest=? AND required_owners=" + + schema + + ".world_runtime_required_owners(?)", + id, + namespace, + registration.revision(), + registration.artifact().digest(), + registration.artifact().exactBytes()); + if (frozen == null) + throw new RegistryUnavailableException("Frozen required-owner set is absent or invalidated"); + } + + private Registration currentInTransaction(boolean lock) { + Record row = + dsl.fetchOne( + "SELECT r.* FROM " + + table("world_runtime_installation_current") + + " c JOIN " + + table("world_runtime_installation_registration") + + " r ON r.revision=c.revision" + + " AND r.artifact_digest=c.artifact_digest AND r.target_namespace=c.target_namespace" + + " WHERE c.target_namespace=?" + + (lock ? " FOR SHARE OF c" : ""), + namespace); + if (row == null) + throw new RegistryUnavailableException("Current installation registration is unavailable"); + return registration(row); + } + + private Registration registration(Record row) { + var parsed = WorldRuntimeInstallationArtifact.parse(row.get("artifact_bytes", byte[].class)); + if (!namespace.equals(parsed.namespace()) + || !parsed.artifactId().equals(row.get("artifact_id", UUID.class)) + || !parsed.installationId().equals(row.get("installation_id", UUID.class)) + || !parsed.digest().equals(row.get("artifact_digest", String.class))) { + throw new RegistryUnavailableException("Retained installation identity or digest mismatch"); + } + return new Registration(row.get("revision", Long.class), parsed); + } + + private WorldRuntimeInstallationArtifact artifact(HeldInstallation held) { + var artifact = WorldRuntimeInstallationArtifact.parse(held.exactArtifactBytes()); + if (!namespace.equals(artifact.namespace())) + throw new RegistryUnavailableException("Wrong installation namespace"); + return artifact; + } + + private static void exact( + WorldRuntimeInstallationArtifact actual, WorldRuntimeInstallationArtifact expected) { + if (!Arrays.equals(actual.exactBytes(), expected.exactBytes())) { + throw new RegistryUnavailableException("Protected installation bytes changed"); + } + } + + private String table(String name) { + return schema + "." + name; + } + + private static void independent() { + if (TransactionSynchronizationManager.isActualTransactionActive() + || TransactionSynchronizationManager.isSynchronizationActive()) { + throw new IllegalStateException("Installation owner requires independent transactions"); + } + } + + public record Registration(long revision, WorldRuntimeInstallationArtifact artifact) { + public Registration { + if (revision <= 0) + throw new IllegalArgumentException("Positive registration revision required"); + Objects.requireNonNull(artifact, "artifact"); + } + } + + /** Configured protected installation boundary, never an ordinary request deserializer. */ + public interface ProtectedInstallationSource { + HeldInstallation acquireCurrent(); + } + + /** + * The implementation must independently verify completeness, exact completed installation, + * workload incarnations and all input bindings, and prevent their change until close(). Merely + * re-reading a caller file or comparing its digest cannot implement this contract. + */ + public interface HeldInstallation extends AutoCloseable { + byte[] exactArtifactBytes(); + + void requireCurrent(); + + @Override + void close(); + } + + public static final class RegistryUnavailableException extends IllegalStateException { + public RegistryUnavailableException(String message) { + super(message); + } + } +} diff --git a/services/world-management-service/src/main/resources/db/migration/V1048__world_protected_installation_registry.sql b/services/world-management-service/src/main/resources/db/migration/V1048__world_protected_installation_registry.sql new file mode 100644 index 0000000000..a03b2fccef --- /dev/null +++ b/services/world-management-service/src/main/resources/db/migration/V1048__world_protected_installation_registry.sql @@ -0,0 +1,287 @@ +-- Complete protected installation registration; no external authority or runtime wiring is enabled. +CREATE TABLE world_runtime_installation_registration ( + revision BIGSERIAL PRIMARY KEY, + artifact_id UUID NOT NULL UNIQUE CHECK (artifact_id <> '00000000-0000-0000-0000-000000000000'), + installation_id UUID NOT NULL UNIQUE CHECK (installation_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace VARCHAR(63) NOT NULL, + artifact_bytes BYTEA NOT NULL CHECK (octet_length(artifact_bytes) BETWEEN 1 AND 4194304), + artifact_digest VARCHAR(71) NOT NULL CHECK (artifact_digest = 'sha256:' || encode(sha256(artifact_bytes),'hex')), + registered_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + UNIQUE (revision, artifact_digest, target_namespace) +); + +CREATE TABLE world_runtime_installation_current ( + target_namespace VARCHAR(63) PRIMARY KEY, + revision BIGINT NOT NULL, + artifact_digest VARCHAR(71) NOT NULL, + FOREIGN KEY (revision, artifact_digest, target_namespace) + REFERENCES world_runtime_installation_registration(revision, artifact_digest, target_namespace) +); + +CREATE TABLE world_runtime_required_owner_snapshot ( + canonical_game_instance_id UUID PRIMARY KEY CHECK (canonical_game_instance_id <> '00000000-0000-0000-0000-000000000000'), + target_namespace VARCHAR(63) NOT NULL, + registry_revision BIGINT NOT NULL, + artifact_digest VARCHAR(71) NOT NULL, + required_owners JSONB NOT NULL, + frozen_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), + FOREIGN KEY (registry_revision, artifact_digest, target_namespace) + REFERENCES world_runtime_installation_registration(revision, artifact_digest, target_namespace) +); + +INSERT INTO world_runtime_family_classification + (family_id, relation_name, family_role, state_class, fresh_disposition) +VALUES + ('world_runtime_installation_registration','world_runtime_installation_registration','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY'), + ('world_runtime_installation_current','world_runtime_installation_current','CONTROL','NOT_PAYLOAD','CONTROL_ONLY'), + ('world_runtime_required_owner_snapshot','world_runtime_required_owner_snapshot','PROVENANCE','NOT_PAYLOAD','PROVENANCE_ONLY'); + +-- PostgreSQL JSON array predicate is not executable in the jOOQ H2 DDL interpreter. +-- [jooq ignore start] +ALTER TABLE world_runtime_required_owner_snapshot ADD CONSTRAINT world_required_owner_array + CHECK (jsonb_typeof(required_owners)='array' AND jsonb_array_length(required_owners)>0); +CREATE FUNCTION world_runtime_registry_immutable() RETURNS TRIGGER LANGUAGE plpgsql AS $$ +BEGIN + RAISE EXCEPTION 'Runtime installation and required-owner history is immutable' USING ERRCODE='55000'; +END; +$$; +CREATE TRIGGER world_runtime_installation_immutable BEFORE UPDATE OR DELETE ON world_runtime_installation_registration + FOR EACH ROW EXECUTE FUNCTION world_runtime_registry_immutable(); +CREATE TRIGGER world_runtime_installation_no_truncate BEFORE TRUNCATE ON world_runtime_installation_registration + FOR EACH STATEMENT EXECUTE FUNCTION world_runtime_registry_immutable(); +CREATE TRIGGER world_runtime_required_owners_immutable BEFORE UPDATE OR DELETE ON world_runtime_required_owner_snapshot + FOR EACH ROW EXECUTE FUNCTION world_runtime_registry_immutable(); +CREATE TRIGGER world_runtime_required_owners_no_truncate BEFORE TRUNCATE ON world_runtime_required_owner_snapshot + FOR EACH STATEMENT EXECUTE FUNCTION world_runtime_registry_immutable(); + +-- SQL derives the frozen set from exact retained bytes, never a caller-supplied owner subset. +CREATE FUNCTION world_runtime_required_owners(p_bytes BYTEA) RETURNS JSONB +LANGUAGE plpgsql IMMUTABLE AS $$ +DECLARE + artifact JSONB := convert_from(p_bytes,'UTF8')::JSONB; + owners JSONB; +BEGIN + IF artifact->>'schema' IS DISTINCT FROM 'firemud-runtime-installation-inventory/v1' + OR jsonb_typeof(artifact->'members') IS DISTINCT FROM 'array' THEN + RAISE EXCEPTION 'Complete runtime installation artifact required' USING ERRCODE='23514'; + END IF; + IF EXISTS (SELECT 1 FROM jsonb_array_elements(artifact->'members') m + CROSS JOIN LATERAL jsonb_array_elements(m->'families') f + WHERE f->>'replacementClass' IS NULL OR f->>'replacementClass' NOT IN ('S1','S2','S3') + OR jsonb_typeof(f->'cleanupContract') IS DISTINCT FROM 'object' + OR EXISTS (SELECT 1 FROM (VALUES ('operation'),('requestIdentity'),('acknowledgement'),('retention')) k(name) + WHERE coalesce(length(f->'cleanupContract'->>k.name),0)=0)) THEN + RAISE EXCEPTION 'Unresolved runtime family or cleanup contract' USING ERRCODE='23514'; + END IF; + SELECT jsonb_agg(jsonb_build_object('ownerId',m->>'ownerId','catalogSources',m->'catalogSources', + 'families',m->'families','workloadApiVersion',m->>'workloadApiVersion', + 'workloadKind',m->>'workloadKind','workloadName',m->>'workloadName', + 'containerKind',m->>'containerKind','containerName',m->>'containerName') + ORDER BY m->>'ownerId' COLLATE "C",m->>'workloadApiVersion' COLLATE "C", + m->>'workloadKind' COLLATE "C",m->>'workloadName' COLLATE "C", + m->>'containerKind' COLLATE "C",m->>'containerName' COLLATE "C") + INTO owners FROM jsonb_array_elements(artifact->'members') m WHERE m->>'ownership'='RUNTIME_OWNER'; + IF owners IS NULL OR jsonb_array_length(owners)=0 THEN + RAISE EXCEPTION 'Complete runtime required-owner set is unavailable' USING ERRCODE='23514'; + END IF; + RETURN owners; +END; +$$; + +CREATE FUNCTION world_runtime_registration_binding_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}",pg_catalog AS $$ +DECLARE a JSONB := convert_from(NEW.artifact_bytes,'UTF8')::JSONB; +BEGIN + IF (a->>'artifactId')::UUID IS DISTINCT FROM NEW.artifact_id + OR (a->>'installationId')::UUID IS DISTINCT FROM NEW.installation_id + OR a->>'namespace' IS DISTINCT FROM NEW.target_namespace THEN + RAISE EXCEPTION 'Runtime installation identity does not match retained exact bytes' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER world_runtime_registration_binding BEFORE INSERT ON world_runtime_installation_registration + FOR EACH ROW EXECUTE FUNCTION world_runtime_registration_binding_guard(); + +CREATE FUNCTION world_runtime_current_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}",pg_catalog AS $$ +BEGIN + IF TG_OP IN ('DELETE','TRUNCATE') THEN + RAISE EXCEPTION 'Current runtime installation cannot be deleted' USING ERRCODE='55000'; + END IF; + IF TG_OP='UPDATE' AND (NEW.target_namespace IS DISTINCT FROM OLD.target_namespace OR NEW.revision<=OLD.revision) THEN + RAISE EXCEPTION 'Current runtime installation must advance monotonically' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER world_runtime_current_monotonic BEFORE INSERT OR UPDATE OR DELETE ON world_runtime_installation_current + FOR EACH ROW EXECUTE FUNCTION world_runtime_current_guard(); +CREATE TRIGGER world_runtime_current_no_truncate BEFORE TRUNCATE ON world_runtime_installation_current + FOR EACH STATEMENT EXECUTE FUNCTION world_runtime_current_guard(); + +CREATE FUNCTION world_runtime_snapshot_guard() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}",pg_catalog AS $$ +DECLARE r world_runtime_installation_registration%ROWTYPE; +BEGIN + -- Lock the current pointer through the launch transaction; a concurrent change waits. + SELECT registration.* INTO STRICT r FROM world_runtime_installation_current c + JOIN world_runtime_installation_registration registration ON registration.revision=c.revision + WHERE c.target_namespace=NEW.target_namespace FOR SHARE OF c; + IF r.revision IS DISTINCT FROM NEW.registry_revision OR r.artifact_digest IS DISTINCT FROM NEW.artifact_digest + OR world_runtime_required_owners(r.artifact_bytes) IS DISTINCT FROM NEW.required_owners THEN + RAISE EXCEPTION 'Frozen owners must match the complete current installation' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER world_runtime_snapshot_exact BEFORE INSERT ON world_runtime_required_owner_snapshot + FOR EACH ROW EXECUTE FUNCTION world_runtime_snapshot_guard(); + +CREATE FUNCTION world_require_registered_launch_owners() RETURNS TRIGGER LANGUAGE plpgsql +SET search_path = "${serviceSchema}",pg_catalog AS $$ +DECLARE snapshot world_runtime_required_owner_snapshot%ROWTYPE; +BEGIN + IF NEW.canonical_game_instance_id IS NULL THEN RETURN NEW; END IF; + IF TG_OP='UPDATE' AND OLD.canonical_game_instance_id IS NOT DISTINCT FROM NEW.canonical_game_instance_id + AND OLD.canonical_target_namespace IS NOT DISTINCT FROM NEW.canonical_target_namespace + AND NOT (NEW.status='ACTIVE' AND OLD.status IS DISTINCT FROM NEW.status) THEN + RETURN NEW; + END IF; + SELECT s.* INTO snapshot FROM world_runtime_required_owner_snapshot s + JOIN world_runtime_installation_current c ON c.target_namespace=s.target_namespace + AND c.revision=s.registry_revision AND c.artifact_digest=s.artifact_digest + JOIN world_runtime_installation_registration r ON r.revision=c.revision + WHERE s.canonical_game_instance_id=NEW.canonical_game_instance_id + AND s.target_namespace=NEW.canonical_target_namespace + AND s.required_owners=world_runtime_required_owners(r.artifact_bytes) + FOR SHARE OF c; + IF NOT FOUND THEN + RAISE EXCEPTION 'Canonical launch requires complete current frozen runtime owners' USING ERRCODE='23514'; + END IF; + RETURN NEW; +END; +$$; +CREATE TRIGGER world_instance_registered_launch_owners BEFORE INSERT OR UPDATE ON world_instance + FOR EACH ROW EXECUTE FUNCTION world_require_registered_launch_owners(); + +CREATE OR REPLACE FUNCTION world_runtime_family_catalog_installed() RETURNS BOOLEAN +LANGUAGE SQL STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ + SELECT EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1046' AND script='V1046__world_owner_runtime_family_catalog.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1047' AND script='V1047__world_catalog_snapshot_exact_frames.sql' AND success) + AND EXISTS (SELECT 1 FROM "${flyway:table}" + WHERE version='1048' AND script='V1048__world_protected_installation_registry.sql' AND success); +$$; + +CREATE OR REPLACE FUNCTION world_runtime_family_catalog_bytes(p_epoch BIGINT) RETURNS BYTEA +LANGUAGE plpgsql STABLE +SET search_path = "${serviceSchema}", pg_catalog +AS $$ +DECLARE + v_families JSONB; + v_facts JSONB; +BEGIN + IF p_epoch IS NULL OR p_epoch <= 0 THEN + RAISE EXCEPTION 'Positive World catalog epoch required' USING ERRCODE = '23514'; + END IF; + IF EXISTS ( + SELECT c.relname FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' AND c.relkind IN ('r','p','f') + EXCEPT SELECT relation_name FROM world_runtime_family_classification WHERE component_name='' + ) OR EXISTS ( + SELECT 1 FROM world_runtime_family_classification f + LEFT JOIN pg_namespace n ON n.nspname='${serviceSchema}' + LEFT JOIN pg_class c ON c.relnamespace=n.oid AND c.relname=f.relation_name AND c.relkind IN ('r','p','f') + WHERE c.oid IS NULL OR (f.component_name<>'' AND NOT EXISTS ( + SELECT 1 FROM pg_attribute a WHERE a.attrelid=c.oid AND a.attname=f.component_name + AND a.attnum>0 AND NOT a.attisdropped)) + ) THEN + RAISE EXCEPTION 'Unclassified or changed World schema family' USING ERRCODE = '23514'; + END IF; + + SELECT jsonb_agg(jsonb_build_object('familyId',family_id,'relation',relation_name, + 'component',component_name,'role',family_role,'stateClass',state_class, + 'freshDisposition',fresh_disposition) ORDER BY family_id COLLATE "C") + INTO v_families FROM world_runtime_family_classification; + + WITH relations AS ( + SELECT c.* FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname='${serviceSchema}' + ), definitions(kind,identity,definition) AS ( + SELECT 'TABLE',c.relname::TEXT,jsonb_build_array(c.relkind,c.relpersistence, + c.relrowsecurity,c.relforcerowsecurity,c.reloptions,pg_get_partkeydef(c.oid))::TEXT + FROM relations c WHERE c.relkind IN ('r','p','f') + UNION ALL + SELECT 'COLUMN',c.relname||'.'||a.attname,jsonb_build_array(a.attnum, + format_type(a.atttypid,a.atttypmod),a.attnotnull,a.attidentity,a.attgenerated, + pg_get_expr(d.adbin,d.adrelid),co.collname)::TEXT + FROM relations c JOIN pg_attribute a ON a.attrelid=c.oid + LEFT JOIN pg_attrdef d ON d.adrelid=c.oid AND d.adnum=a.attnum + LEFT JOIN pg_collation co ON co.oid=a.attcollation + WHERE c.relkind IN ('r','p','f','v','m') AND a.attnum>0 AND NOT a.attisdropped + UNION ALL + SELECT 'CONSTRAINT',c.relname||'.'||k.conname, + jsonb_build_array(pg_get_constraintdef(k.oid,true),k.convalidated,k.condeferrable,k.condeferred)::TEXT + FROM relations c JOIN pg_constraint k ON k.conrelid=c.oid + UNION ALL + SELECT 'INDEX',c.relname::TEXT,jsonb_build_array(pg_get_indexdef(c.oid),i.indisvalid,i.indisready)::TEXT + FROM relations c JOIN pg_index i ON i.indexrelid=c.oid + UNION ALL + SELECT 'TRIGGER',c.relname||'.'||t.tgname,jsonb_build_array(pg_get_triggerdef(t.oid,true),t.tgenabled)::TEXT + FROM relations c JOIN pg_trigger t ON t.tgrelid=c.oid WHERE NOT t.tgisinternal + UNION ALL + SELECT 'POLICY',c.relname||'.'||p.polname, + jsonb_build_array(p.polcmd,p.polpermissive, + (SELECT jsonb_agg(r.rolname ORDER BY r.rolname COLLATE "C") FROM pg_roles r WHERE r.oid=ANY(p.polroles)), + pg_get_expr(p.polqual,p.polrelid),pg_get_expr(p.polwithcheck,p.polrelid))::TEXT + FROM relations c JOIN pg_policy p ON p.polrelid=c.oid + UNION ALL + SELECT 'RULE',c.relname||'.'||r.rulename,pg_get_ruledef(r.oid,true) + FROM relations c JOIN pg_rewrite r ON r.ev_class=c.oid + UNION ALL + SELECT 'ROUTINE',p.proname||'('||pg_get_function_identity_arguments(p.oid)||')',pg_get_functiondef(p.oid) + FROM pg_proc p JOIN pg_namespace n ON n.oid=p.pronamespace + WHERE n.nspname='${serviceSchema}' AND p.prokind IN ('f','p') + UNION ALL + SELECT 'SEQUENCE',c.relname::TEXT,(to_jsonb(s)-'seqrelid')::TEXT + FROM relations c JOIN pg_sequence s ON s.seqrelid=c.oid + UNION ALL + SELECT 'VIEW',c.relname::TEXT,jsonb_build_array(pg_get_viewdef(c.oid,true),c.reloptions)::TEXT + FROM relations c WHERE c.relkind IN ('v','m') + UNION ALL + SELECT 'TYPE',t.typname::TEXT,jsonb_build_array(t.typtype,t.typnotnull,t.typdefault, + (SELECT jsonb_agg(e.enumlabel ORDER BY e.enumsortorder) FROM pg_enum e WHERE e.enumtypid=t.oid))::TEXT + FROM pg_type t JOIN pg_namespace n ON n.oid=t.typnamespace WHERE n.nspname='${serviceSchema}' + UNION ALL + SELECT 'MIGRATION',installed_rank::TEXT||':'||coalesce(version,'repeatable')||':'||script, + jsonb_build_array(version,type,script,checksum,success)::TEXT + FROM "${flyway:table}" WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' AND version IS DISTINCT FROM '1048' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1046','V1046__world_owner_runtime_family_catalog.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1047','V1047__world_catalog_snapshot_exact_frames.sql' + UNION ALL + SELECT 'MIGRATION','catalog-installation:1048','V1048__world_protected_installation_registry.sql' + ) + SELECT jsonb_agg(jsonb_build_object('kind',kind,'identity',identity, + 'definitionDigest','sha256:'||encode(sha256(convert_to(definition,'UTF8')),'hex')) + ORDER BY (kind||'/'||identity) COLLATE "C") INTO v_facts FROM definitions; + + IF jsonb_array_length(v_families)>512 OR jsonb_array_length(v_facts)>16384 THEN + RAISE EXCEPTION 'Complete World catalog exceeds source bounds' USING ERRCODE = '23514'; + END IF; + RETURN convert_to(jsonb_build_object('schema','world-runtime-family-catalog/v1', + 'owner','world-management-service','catalogEpoch',p_epoch::TEXT, + 'families',v_families,'schemaFacts',v_facts)::TEXT,'UTF8'); +END; +$$; + +INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest) +SELECT next_epoch,bytes,'sha256:'||encode(sha256(bytes),'hex') +FROM (SELECT coalesce(max(catalog_epoch),0)+1 AS next_epoch FROM world_runtime_family_catalog_epoch) next +CROSS JOIN LATERAL (SELECT world_runtime_family_catalog_bytes(next.next_epoch) AS bytes) seal; +-- [jooq ignore stop] diff --git a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java index 4df4d24379..bf74dc929e 100644 --- a/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java +++ b/services/world-management-service/src/test/java/crossservice/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionPreparationOwnerCompositionCrossServiceTest.java @@ -284,7 +284,8 @@ * stable Redis deployment-incarnation evidence, and loopback PKI remain controlled test inputs; * this does not establish genuine Human issuer/environment authority, production PKI, registered * endpoint activation, or runtime admission. The small test-only World socket invokes the typed - * preparation owner directly, not assembly. + * preparation owner directly, not assembly. The exact runtime installation artifact and held source + * below are synthetic fixtures, not genuine external installation/custody evidence. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -350,6 +351,20 @@ void actualOwnersPrepareAndReplayOneExactOriginalOperation( compose(Refusal.NONE, reservationClaimFence, proofDirectory); } + @Test + void actualCommittedPreparationRetryReturnsAfterInstallationRegistryAdvances() throws Exception { + compose( + Refusal.NONE, + 9_007_199_254_740_993L, + temporary, + ActivationFailure.NONE, + false, + false, + false, + false, + true); + } + @Test void mismatchedOwnerAttemptCannotAcquireParticipationOrMutateWorld() throws Exception { compose(Refusal.MISMATCHED_ATTEMPT); @@ -536,6 +551,29 @@ private void compose( boolean abortCanonicalInitialAdmission, boolean playerCreatedPlacement) throws Exception { + compose( + refusal, + reservationClaimFence, + proofDirectory, + activationFailure, + exerciseCanonicalInitialAdmissionHold, + exerciseCoupledCanonicalInitialAdmission, + abortCanonicalInitialAdmission, + playerCreatedPlacement, + false); + } + + private void compose( + Refusal refusal, + long reservationClaimFence, + Path proofDirectory, + ActivationFailure activationFailure, + boolean exerciseCanonicalInitialAdmissionHold, + boolean exerciseCoupledCanonicalInitialAdmission, + boolean abortCanonicalInitialAdmission, + boolean playerCreatedPlacement, + boolean advanceInstallationBeforeRetry) + throws Exception { if (abortCanonicalInitialAdmission && !exerciseCoupledCanonicalInitialAdmission) { throw new IllegalArgumentException("Admission abort proof requires the coupled owner path"); } @@ -893,7 +931,8 @@ public ServerCall.Listener interceptCall( return held; }, new WorldCanonicalInstanceOriginalOperationRecoveryVerifier( - historicalAccount, historicalGs)); + historicalAccount, historicalGs), + world.installationRegistry()); var result = new AtomicReference(); var ownerRefusal = new AtomicReference(); var recovering = new AtomicBoolean(); @@ -961,7 +1000,9 @@ public ServerCall.Listener interceptCall( world.dsl(), activationTransactionFault == null ? world.manager() : activationTransactionFault, lifecycleRepository); - var activationService = new WorldCanonicalInstanceActivationService(activationRepository); + var activationService = + new WorldCanonicalInstanceActivationService( + activationRepository, world.installationRegistry()); var acquiredActivationProtection = new AtomicReference(); var accountProtectionRowsAfterAcquisition = @@ -1027,7 +1068,10 @@ public ServerCall.Listener interceptCall( "world_canonical_instance_association", "world_canonical_instance_preparation", "world_canonical_instance_execution", - "world_canonical_instance_activation_fence"); + "world_canonical_instance_activation_fence", + "world_runtime_installation_registration", + "world_runtime_installation_current", + "world_runtime_required_owner_snapshot"); Map> accountBefore = rows( issuer.sourceDsl(), @@ -1123,9 +1167,73 @@ public ServerCall.Listener interceptCall( .startLocation()); assertThat(prepared.runtimeRoomInstanceId()).isPositive(); assertThat(prepared.runtimeRoomInstanceId()).isGreaterThan(127L); + assertThat( + world + .dsl() + .fetchSingle( + "SELECT s.required_owners=" + + "world_runtime_required_owners(r.artifact_bytes)" + + " AND s.registry_revision=c.revision" + + " AND s.artifact_digest=r.artifact_digest" + + " AND jsonb_array_length(s.required_owners)=1" + + " AND s.required_owners->0->>'ownerId'='world-management-service'" + + " FROM world_runtime_required_owner_snapshot s" + + " JOIN world_runtime_installation_current c" + + " ON c.target_namespace=s.target_namespace" + + " JOIN world_runtime_installation_registration r ON r.revision=c.revision" + + " WHERE s.canonical_game_instance_id=?", + input.canonicalGameInstanceId()) + .get(0, Boolean.class)) + .as( + "complete exact synthetic installation owner fixture frozen before materialization") + .isTrue(); var after = rows(world.dsl(), worldBefore.keySet().toArray(String[]::new)); var protectedAccount = rows(issuer.sourceDsl(), accountBefore.keySet().toArray(String[]::new)); + if (advanceInstallationBeforeRetry) { + long firstRevision = + world + .dsl() + .fetchSingle( + "SELECT revision FROM world_runtime_installation_current WHERE target_namespace=?", + NAMESPACE) + .get(0, Long.class); + long frozenRevision = + world + .dsl() + .fetchSingle( + "SELECT registry_revision FROM world_runtime_required_owner_snapshot WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId()) + .get(0, Long.class); + assertThat(frozenRevision).isEqualTo(firstRevision); + + var advancedRegistration = advanceInstallationRegistry(world); + assertThat(advancedRegistration.revision()).isGreaterThan(firstRevision); + assertThat( + world + .dsl() + .fetchSingle( + "SELECT revision FROM world_runtime_installation_current WHERE target_namespace=?", + NAMESPACE) + .get(0, Long.class)) + .isEqualTo(advancedRegistration.revision()); + assertThat( + world + .dsl() + .fetchSingle( + "SELECT registry_revision FROM world_runtime_required_owner_snapshot WHERE canonical_game_instance_id=?", + input.canonicalGameInstanceId()) + .get(0, Long.class)) + .isEqualTo(firstRevision); + var afterAdvance = rows(world.dsl(), worldBefore.keySet().toArray(String[]::new)); + assertThat(afterAdvance.get("world_runtime_installation_registration")) + .hasSize(after.get("world_runtime_installation_registration").size() + 1); + assertThat(afterAdvance.get("world_runtime_installation_current")) + .isNotEqualTo(after.get("world_runtime_installation_current")); + assertThat(afterAdvance.get("world_runtime_required_owner_snapshot")) + .isEqualTo(after.get("world_runtime_required_owner_snapshot")); + after = afterAdvance; + } ClientCalls.blockingUnaryCall( channel, method, @@ -1151,6 +1259,9 @@ public ServerCall.Listener interceptCall( assertThat( repository.readExactExecution(identity.get()).operation().orElseThrow().state()) .isEqualTo(WorldCanonicalInstancePreparationRepository.ExecutionState.COMMITTED); + if (advanceInstallationBeforeRetry) { + return; + } var evidence = input.gameSessionReadEvidence(); var lifecycleReadRequest = new WorldCanonicalInstanceLifecycleEvidence.Request( @@ -1470,12 +1581,24 @@ public void close() {} }; if (activationFailure == ActivationFailure.TRANSIENT_ROLLBACK_ALWAYS_FINAL_READBACK_FAILURE) { - assertThatThrownBy(() -> activationRepository.activateProtected(protection, held)) + assertThatThrownBy( + () -> + world + .installationRegistry() + .withLaunchOwners( + activationRequest.canonicalGameInstanceId(), + () -> activationRepository.activateProtected(protection, held))) .isInstanceOfSatisfying( TransientDataAccessResourceException.class, failure -> assertSuppressedTerminalReadbackFailure(failure)); } else { - assertThatThrownBy(() -> activationRepository.activateProtected(protection, held)) + assertThatThrownBy( + () -> + world + .installationRegistry() + .withLaunchOwners( + activationRequest.canonicalGameInstanceId(), + () -> activationRepository.activateProtected(protection, held))) .isInstanceOfSatisfying( IllegalStateException.class, failure -> { @@ -4653,18 +4776,142 @@ private static Database database(PostgreSQLContainer postgres, String service var write = new TransactionTemplate(manager); write.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); write.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); - return new Database( + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + WorldRuntimeInstallationRegistry installation = null; + if ("world-management-service".equals(service)) { + // This is a stipulated one-workload installation solely for this receiving-owner proof. + // Real Account/GS/mTLS behavior remains exercised independently; none supplies global + // installed membership, deployment completeness or production source custody. + byte[] artifact = controlledInstallationArtifact(schema); + installation = + new WorldRuntimeInstallationRegistry( + dsl, + manager, + schema, + NAMESPACE, + () -> + new WorldRuntimeInstallationRegistry.HeldInstallation() { + private boolean closed; + + @Override + public byte[] exactArtifactBytes() { + return artifact.clone(); + } + + @Override + public void requireCurrent() { + if (closed) + throw new IllegalStateException("Synthetic installation hold is closed"); + } + + @Override + public void close() { + closed = true; + } + }); + installation.register(); + } + return new Database(schema, dsl, manager, write, installation); + } + + private static WorldRuntimeInstallationRegistry.Registration advanceInstallationRegistry( + Database world) { + byte[] artifact = controlledInstallationArtifact(world.schema(), "synthetic-installation-v2"); + var advancedRegistry = + new WorldRuntimeInstallationRegistry( + world.dsl(), + world.manager(), + world.schema(), + NAMESPACE, + () -> + new WorldRuntimeInstallationRegistry.HeldInstallation() { + @Override + public byte[] exactArtifactBytes() { + return artifact.clone(); + } + + @Override + public void requireCurrent() {} + + @Override + public void close() {} + }); + return advancedRegistry.register(); + } + + private static byte[] controlledInstallationArtifact(String schema) { + return controlledInstallationArtifact( + schema, "synthetic-installation-v1", schema + ":artifact", schema + ":installation"); + } + + private static byte[] controlledInstallationArtifact(String schema, String generation) { + return controlledInstallationArtifact( schema, - DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES), - manager, - write); + generation, + schema + ":" + generation + ":artifact", + schema + ":" + generation + ":installation"); + } + + private static byte[] controlledInstallationArtifact( + String schema, String generation, String artifactName, String installationName) { + var artifact = JSON.createObjectNode(); + artifact.put("schema", "firemud-runtime-installation-inventory/v1"); + artifact.put( + "artifactId", + UUID.nameUUIDFromBytes(artifactName.getBytes(StandardCharsets.UTF_8)).toString()); + artifact.put( + "installationId", + UUID.nameUUIDFromBytes(installationName.getBytes(StandardCharsets.UTF_8)).toString()); + artifact.put("environment", "local-dev"); + artifact.put("generation", generation); + artifact.put("clusterUid", "synthetic-cluster"); + artifact.put("namespaceUid", "synthetic-namespace"); + artifact.put("namespace", NAMESPACE); + artifact.put("sourceCommit", "a".repeat(40)); + artifact.put("renderedManifestDigest", "sha256:" + "a".repeat(64)); + artifact.put("declarationsDigest", "sha256:" + "b".repeat(64)); + var executor = artifact.putObject("executor"); + executor.put("identity", "synthetic-world-receiving-fixture/v1"); + executor.put("versionDigest", "sha256:" + "c".repeat(64)); + var bindings = artifact.putObject("inputBindings"); + for (String category : + List.of( + "migrations", + "configurations", + "mountedResources", + "secretContracts", + "externalBindings")) bindings.putArray(category); + var member = artifact.putArray("members").addObject(); + member.put("workloadApiVersion", "v1"); + member.put("workloadKind", "Pod"); + member.put("workloadNamespace", NAMESPACE); + member.put("workloadName", "synthetic-world"); + member.put("containerKind", "APPLICATION"); + member.put("containerName", "world"); + member.put("image", "registry.example/synthetic/world@sha256:" + "d".repeat(64)); + member.put("ownerId", "world-management-service"); + member.put("ownership", "RUNTIME_OWNER"); + var source = member.putArray("catalogSources").addObject(); + source.put("sourceId", "synthetic-world-sql"); + source.put("contract", "synthetic/world/catalog/v1"); + source.put("epoch", "1"); + source.put("digest", "sha256:" + "e".repeat(64)); + var family = member.putArray("families").addObject(); + family.put("familyId", "synthetic-world-state"); + family.put("catalogSourceId", "synthetic-world-sql"); + family.put("replacementClass", "S3"); + var cleanup = family.putObject("cleanupContract"); + for (String field : List.of("operation", "requestIdentity", "acknowledgement", "retention")) + cleanup.put(field, "synthetic/world/" + field + "/v1"); + return JSON.writeValueAsBytes(artifact); } private record Database( String schema, DSLContext dsl, DataSourceTransactionManager manager, - TransactionTemplate write) + TransactionTemplate write, + WorldRuntimeInstallationRegistry installationRegistry) implements AutoCloseable { @Override public void close() { diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java index edf6f8d3a1..fb0dba3d72 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/data/RunOwnedWorldFixedPresetResourcesPostgresIntegrationTest.java @@ -59,6 +59,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCompleteLaunchBindingRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceEvidence.OwnerBinding; import net.firedevops.firemud.worldmanagement.tenant.WorldDesignPublicationFenceRepository; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; import org.flywaydb.core.Flyway; import org.jooq.DSLContext; import org.jooq.SQLDialect; @@ -78,6 +79,7 @@ import org.springframework.test.context.bean.override.mockito.MockitoBean; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionDefinition; +import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionSynchronizationManager; import org.springframework.transaction.support.TransactionTemplate; import org.testcontainers.containers.GenericContainer; @@ -90,7 +92,9 @@ * Native PostgreSQL PREPARING-only World owner proof with controlled upstream wire inputs. * *

GDS/GS values and certificate commitments are stipulated constructor data. This proves actual - * World owner allocation, materialization and readback, not authenticated producers or TLS. + * World owner allocation, materialization and readback, not authenticated producers or TLS. The + * installation artifact and its held source are synthetic receiving-fixture prerequisites, not + * evidence of genuine external installation completeness or custody. */ @Testcontainers(disabledWithoutDocker = true) @SuppressWarnings("resource") @@ -293,6 +297,7 @@ static void configure(DynamicPropertyRegistry registry) { private Context controlledPeerContext; private Context previousPeerContext; + private WorldRuntimeInstallationRegistry controlledInstallation; @BeforeEach void attachControlledGsContext() { @@ -309,6 +314,7 @@ void attachControlledGsContext() { "game-session-service")) .withValue(GrpcPeerCertificateEvidence.CONTEXT_KEY, certificate); previousPeerContext = controlledPeerContext.attach(); + controlledInstallation = registerControlledInstallation(); } @AfterEach @@ -394,8 +400,7 @@ void packageOwnerRejectsMissingWrongNamespaceServiceAndLeafBeforeUpstreamOrSqlEf @Test void packageOwnerPreparationRestartAndFreshObservationRetainAllRowsAndXmin() { var evidence = controlledEvidence(); - var prepared = - RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(evidence), evidence); + var prepared = prepareWithInstallation(nativeService(evidence), evidence); assertThat(prepared.status()).isEqualTo("PREPARING"); assertThat(prepared.lifecycleEpoch()).isEqualTo(1L); var gameSession = evidence.gameSessionAssociation(); @@ -427,7 +432,7 @@ void packageOwnerPreparationRestartAndFreshObservationRetainAllRowsAndXmin() { assertPresetContent(association); var original = allRows(dsl); var fresh = RunOwnedWorldFixtureEvidenceTestFixtures.freshObservation(evidence); - var replay = RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(fresh), fresh); + var replay = prepareWithInstallation(nativeService(fresh), fresh); assertThat(replay).isEqualTo(prepared); assertThat(replay.tenantId()).isEqualTo(gameSession.gameSessionTenantId()); assertThat(replay.gameInstanceId()).isEqualTo(gameSession.gameInstanceId()); @@ -458,8 +463,7 @@ void packageOwnerPreparationRestartAndFreshObservationRetainAllRowsAndXmin() { @Test void fixtureAssociationRejectsEveryWorldCopyMismatchThroughTheOwnerTransaction() { var retainedEvidence = controlledEvidence(); - RunOwnedWorldFixtureLifecycleTestFactory.prepare( - nativeService(retainedEvidence), retainedEvidence); + prepareWithInstallation(nativeService(retainedEvidence), retainedEvidence); var evidence = controlledEvidence(); var sourceRepository = new WorldAuthoredSourceIntakeRepository(dsl); @@ -573,6 +577,8 @@ CREATE FUNCTION __test_function__() RETURNS TRIGGER assertThat(beforeInsertTriggers.indexOf(triggerName)) .isLessThan(beforeInsertTriggers.indexOf(ownerCopyValidator)); + controlledInstallation.withLaunchOwners( + evidence.gameSessionAssociation().gameInstanceUuid(), () -> null); var originalRows = allRows(dsl); for (String field : List.of( @@ -588,7 +594,7 @@ CREATE FUNCTION __test_function__() RETURNS TRIGGER "remap_set_id")) { assertSqlState( () -> - ownerTransaction() + ownerTransaction(evidence) .executeWithoutResult( status -> { dsl.fetchOne( @@ -625,8 +631,7 @@ void racingActualPackageOwnersConvergeOneOriginalAllocation() throws Exception { () -> { ready.countDown(); await(release); - return RunOwnedWorldFixtureLifecycleTestFactory.prepare( - firstOwner, evidence); + return prepareWithInstallation(firstOwner, evidence); })); Future second = executor.submit( @@ -635,8 +640,7 @@ void racingActualPackageOwnersConvergeOneOriginalAllocation() throws Exception { () -> { ready.countDown(); await(release); - return RunOwnedWorldFixtureLifecycleTestFactory.prepare( - secondOwner, evidence); + return prepareWithInstallation(secondOwner, evidence); })); assertThat(ready.await(10, TimeUnit.SECONDS)).isTrue(); release.countDown(); @@ -684,10 +688,12 @@ void actualOwnerRollbackLeavesNoAllocationTopologyResultOrManifest() { VersionLifecycleState.VERSION_LIFECYCLE_STATE_PUBLISHED, evidence.launchDescriptor().versionStateEpoch()); var version = ownerTransaction().execute(status -> versionOwner.acceptFresh(intake, state)); + controlledInstallation.withLaunchOwners( + evidence.gameSessionAssociation().gameInstanceUuid(), () -> null); var original = allRows(dsl); assertThatThrownBy( () -> - ownerTransaction() + ownerTransaction(evidence) .executeWithoutResult( status -> { new WorldDesignPublicationFenceRepository(dsl, sourceOwner) @@ -747,7 +753,7 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { var fixtureFence = new WorldDesignPublicationFenceRepository(dsl, sourceOwner); var fixtureRequest = RunOwnedWorldFixtureEvidenceTestFixtures.request(evidence); var allocatedFixture = - ownerTransaction() + ownerTransaction(evidence) .execute( status -> { fixtureFence.lockOpen(binding(intake, version)); @@ -762,7 +768,7 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { savepoint.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); var materialized = - ownerTransaction() + ownerTransaction(evidence) .execute( status -> { var result = @@ -814,7 +820,7 @@ void actualFixtureMaterializationRetainsUnderOwnerSavepoint() { void fixturePreparingCannotActivateAcquireHoldsPlaceActorsOrReuseConsumedManifests() throws Exception { var evidence = controlledEvidence(); - RunOwnedWorldFixtureLifecycleTestFactory.prepare(nativeService(evidence), evidence); + prepareWithInstallation(nativeService(evidence), evidence); var association = associationRepository() .readRunOwnedFixtureAssociation( @@ -1456,12 +1462,22 @@ void installed34ThroughParent40ToDefaultFrontierRetainsRowsXminAndStableLegacyUp connection .fetchSingle("SELECT count(*) FROM world_runtime_family_catalog_epoch") .get(0, Long.class)) - .isEqualTo(2L); + .isEqualTo(3L); assertThat( connection .fetchSingle("SELECT count(*) FROM world_runtime_family_catalog_snapshot") .get(0, Long.class)) .isZero(); + for (String addedRegistry : + List.of( + "world_runtime_installation_registration", + "world_runtime_installation_current", + "world_runtime_required_owner_snapshot")) { + assertThat(retainedRowsAtDefaultFrontierOriginalColumns.remove(addedRegistry)) + .as("new additive registry table %s is installed and empty", addedRegistry) + .isNotNull() + .isEmpty(); + } assertThat(retainedRowsAtDefaultFrontierOriginalColumns) .as("all retained original row values and xmin from V1042.8 through the V1042.11 repairs") .isEqualTo(retainedRowsAt10428); @@ -1867,7 +1883,7 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() descriptor.versionStateEpoch(), null); WorldCanonicalInstanceAssociation allocated = - ownerTransaction() + ownerTransaction(evidence) .execute( status -> { fenceRepository.lockOpen(binding); @@ -2028,7 +2044,7 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() assertThat(resourceCount()).isEqualTo(before); var result = - ownerTransaction() + ownerTransaction(evidence) .execute( status -> { fenceRepository.lockOpen(binding); @@ -2191,7 +2207,7 @@ void realWorldOwnersMaterializeSixFixtureMappingsAndReplayExactCommittedBytes() "SELECT to_jsonb(p)::text || p.xmin::text FROM world_canonical_instance_preparation p WHERE world_instance_id = ?", worldId); var replayResult = - ownerTransaction() + ownerTransaction(evidence) .execute( status -> { fenceRepository.lockOpen(binding); @@ -3163,6 +3179,7 @@ private static List remainingVersions() { versions.add("1045"); versions.add("1046"); versions.add("1047"); + versions.add("1048"); return List.copyOf(versions); } @@ -3258,6 +3275,112 @@ private TransactionTemplate ownerTransaction() { return transaction; } + /** Hold only the explicit synthetic installation while the existing actual owner commits. */ + private TransactionTemplate ownerTransaction(RunOwnedCanonicalWorldLaunchEvidence evidence) { + TransactionTemplate transaction = + new TransactionTemplate(transactionManager) { + @Override + public T execute(TransactionCallback action) { + return controlledInstallation.withLaunchOwners( + evidence.gameSessionAssociation().gameInstanceUuid(), () -> super.execute(action)); + } + }; + transaction.setIsolationLevel(TransactionDefinition.ISOLATION_READ_COMMITTED); + return transaction; + } + + private WorldInstanceLifecycleSnapshotDto prepareWithInstallation( + WorldLifecycleCommandServiceImpl service, RunOwnedCanonicalWorldLaunchEvidence evidence) { + return controlledInstallation.withLaunchOwners( + evidence.gameSessionAssociation().gameInstanceUuid(), + () -> RunOwnedWorldFixtureLifecycleTestFactory.prepare(service, evidence)); + } + + private WorldRuntimeInstallationRegistry registerControlledInstallation() { + String schema = dsl.fetchSingle("SELECT current_schema()").get(0, String.class); + var artifact = objectMapper.createObjectNode(); + artifact.put("schema", "firemud-runtime-installation-inventory/v1"); + artifact.put( + "artifactId", + UUID.nameUUIDFromBytes((schema + ":synthetic-artifact").getBytes(StandardCharsets.UTF_8)) + .toString()); + artifact.put( + "installationId", + UUID.nameUUIDFromBytes( + (schema + ":synthetic-installation").getBytes(StandardCharsets.UTF_8)) + .toString()); + artifact.put("environment", "local-dev"); + artifact.put("generation", "synthetic-fixture-installation-v1"); + artifact.put("clusterUid", "synthetic-cluster"); + artifact.put("namespaceUid", "synthetic-namespace"); + artifact.put("namespace", "dev"); + artifact.put("sourceCommit", "a".repeat(40)); + artifact.put("renderedManifestDigest", "sha256:" + "a".repeat(64)); + artifact.put("declarationsDigest", "sha256:" + "b".repeat(64)); + var executor = artifact.putObject("executor"); + executor.put("identity", "synthetic-world-fixed-preset-fixture/v1"); + executor.put("versionDigest", "sha256:" + "c".repeat(64)); + var bindings = artifact.putObject("inputBindings"); + for (String category : + List.of( + "migrations", + "configurations", + "mountedResources", + "secretContracts", + "externalBindings")) bindings.putArray(category); + var member = artifact.putArray("members").addObject(); + member.put("workloadApiVersion", "v1"); + member.put("workloadKind", "Pod"); + member.put("workloadNamespace", "dev"); + member.put("workloadName", "synthetic-world"); + member.put("containerKind", "APPLICATION"); + member.put("containerName", "world"); + member.put("image", "registry.example/synthetic/world@sha256:" + "d".repeat(64)); + member.put("ownerId", "world-management-service"); + member.put("ownership", "RUNTIME_OWNER"); + var source = member.putArray("catalogSources").addObject(); + source.put("sourceId", "synthetic-world-sql"); + source.put("contract", "synthetic/world/catalog/v1"); + source.put("epoch", "1"); + source.put("digest", "sha256:" + "e".repeat(64)); + var family = member.putArray("families").addObject(); + family.put("familyId", "synthetic-world-state"); + family.put("catalogSourceId", "synthetic-world-sql"); + family.put("replacementClass", "S3"); + var cleanup = family.putObject("cleanupContract"); + for (String field : List.of("operation", "requestIdentity", "acknowledgement", "retention")) + cleanup.put(field, "synthetic/world/" + field + "/v1"); + byte[] exact = objectMapper.writeValueAsBytes(artifact); + var registry = + new WorldRuntimeInstallationRegistry( + dsl, + transactionManager, + schema, + "dev", + () -> + new WorldRuntimeInstallationRegistry.HeldInstallation() { + private boolean closed; + + @Override + public byte[] exactArtifactBytes() { + return exact.clone(); + } + + @Override + public void requireCurrent() { + if (closed) + throw new IllegalStateException("Synthetic installation hold is closed"); + } + + @Override + public void close() { + closed = true; + } + }); + registry.register(); + return registry; + } + private void assertFixedPresetReadbackMode( String mode, RunOwnedWorldFixedPresetResources.FixedPresetPlan plan, diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java index e8ddc57358..f2917a9060 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldGraphApplicationReceiptDigestPostgresIntegrationTest.java @@ -199,7 +199,7 @@ void forwardMigrationBindsSemanticReceiptDigestOnFreshAndUpgradedSchemas() throw probeCurrent.validate(); assertThat(probeCurrent.info().pending()).isEmpty(); - assertThat(latestVersion(upgradeDsl)).isEqualTo("1047"); + assertThat(latestVersion(upgradeDsl)).isEqualTo("1048"); assertThat(latestVersion(freshDsl)).isEqualTo(latestVersion(upgradeDsl)); assertThat(latestVersion(probeDsl)).isEqualTo(latestVersion(upgradeDsl)); assertThat(migrationHistory(upgradeDsl, "1012")).isEqualTo(history1012Before); diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java index ab6bc31562..9012199151 100644 --- a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeFamilyCatalogPostgresIntegrationTest.java @@ -75,7 +75,7 @@ void actualCompleteCurrentCensusIncludesEmptyRuntimeAndNonPayloadFamilies() thro try (Fixture f = fixture(null)) { var evidence = f.owner().read(request()); var catalog = evidence.catalog(); - assertThat(catalog.catalogEpoch()).isEqualTo(2); + assertThat(catalog.catalogEpoch()).isEqualTo(3); assertThat( catalog.schemaFacts().stream() .filter(fact -> fact.kind() == FactKind.TABLE) @@ -207,7 +207,7 @@ void additiveForwardMigrationRetainsLegacyPayloadAndPriorMigrationHistoryExactly assertThat( f.dsl .fetch( - "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' ORDER BY installed_rank") + "SELECT to_jsonb(h)::text FROM flyway_schema_history_world_management_service h WHERE version IS DISTINCT FROM '1046' AND version IS DISTINCT FROM '1047' AND version IS DISTINCT FROM '1048' ORDER BY installed_rank") .getValues(0, String.class)) .isEqualTo(historyBefore); f.owner().read(request()); @@ -316,7 +316,7 @@ void installedViewAndMaterializedViewOptionsInvalidateTheSealWithoutResampling() migration(f.source, f.schema, null).migrate(); Request read = request(); var original = f.owner().read(read); - assertThat(original.catalog().catalogEpoch()).isEqualTo(2); + assertThat(original.catalog().catalogEpoch()).isEqualTo(3); assertThat(original.catalog().schemaFacts()) .anyMatch( fact -> @@ -368,7 +368,7 @@ void removalAndClassificationChangeAreExplicitlyInvalidating() throws Exception .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(request())) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); - assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(2); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(3); } } @@ -396,7 +396,7 @@ void oldMigrationFactChangeInvalidatesTheSealAndMissingOwnerEpochNeverMeansCompl void directSnapshotInsertRequiresBothSuccessfulExactCatalogMigrationRows() throws Exception { try (Fixture f = fixture(null)) { var catalog = f.owner().read(request()).catalog(); - for (String version : List.of("1046", "1047")) { + for (String version : List.of("1046", "1047", "1048")) { for (String column : List.of("success", "script")) { Request read = request(); var evidence = new Evidence(read, UUID.randomUUID(), catalog); @@ -506,18 +506,18 @@ void forwardFrameGuardUpgradeRetainsOldEpochSnapshotAndHistoryWithoutResampling( migration(f.source, f.schema, null).migrate(); assertThat(f.retainedRows("world_runtime_family_catalog_epoch")) .containsAll(epochs) - .hasSize(2); + .hasSize(3); assertThat(f.retainedRows("world_runtime_family_catalog_snapshot")).isEqualTo(snapshots); assertThat(f.retainedRows("flyway_schema_history_world_management_service")) .containsAll(history) - .hasSize(history.size() + 1); + .hasSize(history.size() + 2); assertThatThrownBy(() -> f.owner().readExact(read)) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(read)) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThat(f.retainedRows("world_runtime_family_catalog_snapshot")).isEqualTo(snapshots); var current = f.owner().read(request()); - assertThat(current.catalog().catalogEpoch()).isEqualTo(2); + assertThat(current.catalog().catalogEpoch()).isEqualTo(3); assertThat(current.catalog().digest()).isNotEqualTo(original.catalog().digest()); assertThat(current.catalog().schemaFacts()) .anyMatch( @@ -527,7 +527,11 @@ void forwardFrameGuardUpgradeRetainsOldEpochSnapshotAndHistoryWithoutResampling( .anyMatch( fact -> fact.kind() == FactKind.MIGRATION - && fact.identity().equals("catalog-installation:1047")); + && fact.identity().equals("catalog-installation:1047")) + .anyMatch( + fact -> + fact.kind() == FactKind.MIGRATION + && fact.identity().equals("catalog-installation:1048")); assertThat(f.count("world_runtime_family_catalog_snapshot")).isEqualTo(2); migration(f.source, f.schema, null).validate(); } @@ -545,8 +549,8 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidenc + " ('region_instance.name','region_instance','name','RUNTIME_PAYLOAD','S3','REQUIRED_TOPOLOGY')"); f.dsl.execute( "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 3,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM" - + " (SELECT world_runtime_family_catalog_bytes(3) AS bytes) revised"); + + " SELECT 4,bytes,'sha256:'||encode(sha256(bytes),'hex') FROM" + + " (SELECT world_runtime_family_catalog_bytes(4) AS bytes) revised"); assertThatThrownBy(() -> f.owner().readExact(read)) .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); assertThatThrownBy(() -> f.owner().read(read)) @@ -559,9 +563,9 @@ void explicitOwnerEpochAdvanceInvalidatesOldRequestsWithoutRewritingTheirEvidenc .get(0, byte[].class)) .isEqualTo(WorldRuntimeFamilyCatalogCodec.evidenceBytes(original)); var revised = f.owner().read(request()); - assertThat(revised.catalog().catalogEpoch()).isEqualTo(3); + assertThat(revised.catalog().catalogEpoch()).isEqualTo(4); assertThat(revised.catalog().digest()).isNotEqualTo(original.catalog().digest()); - assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(3); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(4); } } @@ -591,7 +595,7 @@ void epochMetadataAndSnapshotsAreRetainedAndWrongSealsCannotBeInserted() throws () -> f.dsl.execute( "INSERT INTO world_runtime_family_catalog_epoch(catalog_epoch,catalog_bytes,catalog_digest)" - + " SELECT 3,catalog_bytes,catalog_digest FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=2")) + + " SELECT 4,catalog_bytes,catalog_digest FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=3")) .hasMessageContaining("exact classified installed schema"); } } diff --git a/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryPostgresIntegrationTest.java b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryPostgresIntegrationTest.java new file mode 100644 index 0000000000..ecd25042db --- /dev/null +++ b/services/world-management-service/src/test/java/integration/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryPostgresIntegrationTest.java @@ -0,0 +1,604 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static net.firedevops.firemud.worldmanagement.WorldPostgresMigrationTestSupport.migration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog.Request; +import net.firedevops.firemud.test.TestContainerImages; +import org.jooq.DSLContext; +import org.jooq.SQLDialect; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; +import org.springframework.jdbc.datasource.DriverManagerDataSource; +import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; +import org.testcontainers.containers.PostgreSQLContainer; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +/** + * Actual World/Saga migration and PostgreSQL receiving-owner proof. The held installation source, + * workload/catalog/input facts and launch callbacks are explicitly controlled synthetic fixtures. + * These cases establish no genuine protected installation delivery, materialization or admission. + */ +@Testcontainers(disabledWithoutDocker = false) +@SuppressWarnings("resource") +class WorldRuntimeInstallationRegistryPostgresIntegrationTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final String NAMESPACE = "test"; + private static final String HISTORY = "flyway_schema_history_world_management_service"; + + @Container + static PostgreSQLContainer postgres = + new PostgreSQLContainer<>(TestContainerImages.postgres()); + + @Test + void unavailableDefaultSourceRefusesBeforeAnyRegistrationSnapshotOrCallback() { + try (Fixture f = fixture(null)) { + var registry = new WorldRuntimeInstallationRegistry(f.dsl, f.manager, f.schema, NAMESPACE); + AtomicInteger calls = new AtomicInteger(); + assertThatThrownBy(registry::register) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class); + assertThatThrownBy(() -> registry.withLaunchOwners(UUID.randomUUID(), calls::incrementAndGet)) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class); + assertThatThrownBy(registry::current) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class); + assertThat(calls.get()).isZero(); + assertThat(f.count("world_runtime_installation_registration")).isZero(); + assertThat(f.count("world_runtime_installation_current")).isZero(); + assertThat(f.count("world_runtime_required_owner_snapshot")).isZero(); + assertThat(f.count("world_instance")).isZero(); + } + } + + @Test + void exactRegistrationIndependentReadbackAndRetryRetainBytesAndXmin() { + try (Fixture f = fixture(null)) { + byte[] original = artifact(); + var source = new ControlledInstallationSource(original); + var registry = f.registry(source); + var registered = registry.register(); + var retained = f.retainedRows("world_runtime_installation_registration"); + var pointer = f.retainedRows("world_runtime_installation_current"); + var independent = f.registry(source).current(); + assertThat(registered.revision()).isPositive(); + assertThat(independent.revision()).isEqualTo(registered.revision()); + assertThat(independent.artifact().exactBytes()).isEqualTo(original); + assertThat(independent.artifact().digest()) + .isEqualTo(WorldRuntimeFamilyCatalog.sha256(original)); + assertThat( + f.dsl + .fetchSingle("SELECT artifact_bytes FROM world_runtime_installation_registration") + .get(0, byte[].class)) + .isEqualTo(original); + assertThat(registry.register().revision()).isEqualTo(registered.revision()); + assertThat(f.retainedRows("world_runtime_installation_registration")).isEqualTo(retained); + assertThat(f.retainedRows("world_runtime_installation_current")).isEqualTo(pointer); + assertThat(f.count("world_runtime_installation_registration")).isEqualTo(1); + assertThat(source.closed.get()).isEqualTo(2); + } + } + + @Test + void concurrentExactRegistrationsConvergeWithoutRewritingTheRetainedRow() throws Exception { + try (Fixture f = fixture(null); + var workers = Executors.newFixedThreadPool(2)) { + var source = new ControlledInstallationSource(artifact()); + var first = workers.submit(() -> f.registry(source).register()); + var second = workers.submit(() -> f.registry(source).register()); + var firstResult = first.get(30, TimeUnit.SECONDS); + var secondResult = second.get(30, TimeUnit.SECONDS); + assertThat(firstResult.revision()).isEqualTo(secondResult.revision()); + assertThat(firstResult.artifact().exactBytes()) + .isEqualTo(secondResult.artifact().exactBytes()); + assertThat(f.count("world_runtime_installation_registration")).isEqualTo(1); + assertThat(f.count("world_runtime_installation_current")).isEqualTo(1); + } + } + + @Test + void conflictingExactBytesUnderTheSameArtifactIdentityRefuseWithoutMutation() { + try (Fixture f = fixture(null)) { + byte[] original = artifact(); + var source = new ControlledInstallationSource(original); + var registry = f.registry(source); + registry.register(); + var registrations = f.retainedRows("world_runtime_installation_registration"); + var pointers = f.retainedRows("world_runtime_installation_current"); + ObjectNode changed = (ObjectNode) JSON.readTree(original); + changed.put("generation", "changed-generation"); + source.replace(JSON.writeValueAsBytes(changed)); + assertThatThrownBy(registry::register) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) + .hasMessageContaining("changed"); + assertThat(f.retainedRows("world_runtime_installation_registration")) + .isEqualTo(registrations); + assertThat(f.retainedRows("world_runtime_installation_current")).isEqualTo(pointers); + assertThat(registry.current().artifact().exactBytes()).isEqualTo(original); + } + } + + @Test + void frozenOwnersAreCompleteAndNewInstallationInvalidatesOldFreezeWithoutResampling() { + try (Fixture f = fixture(null)) { + var source = new ControlledInstallationSource(artifact()); + var registry = f.registry(source); + var first = registry.register(); + UUID gameInstanceId = UUID.randomUUID(); + AtomicInteger calls = new AtomicInteger(); + registry.preflightLaunchOwners(gameInstanceId); + assertThat(f.count("world_runtime_required_owner_snapshot")).isZero(); + assertThat(registry.withLaunchOwners(gameInstanceId, calls::incrementAndGet)).isEqualTo(1); + assertThat( + f.dsl + .fetchSingle( + "SELECT jsonb_array_length(required_owners) FROM world_runtime_required_owner_snapshot") + .get(0, Integer.class)) + .isEqualTo(2); + assertThat( + f.dsl + .fetchSingle( + "SELECT required_owners=world_runtime_required_owners(?) FROM world_runtime_required_owner_snapshot", + first.artifact().exactBytes()) + .get(0, Boolean.class)) + .isTrue(); + var frozen = f.retainedRows("world_runtime_required_owner_snapshot"); + registry.preflightLaunchOwners(gameInstanceId); + assertThat(f.retainedRows("world_runtime_required_owner_snapshot")).isEqualTo(frozen); + assertThat(registry.withLaunchOwners(gameInstanceId, calls::incrementAndGet)).isEqualTo(2); + assertThat(f.retainedRows("world_runtime_required_owner_snapshot")).isEqualTo(frozen); + + source.replace(artifact()); + var second = registry.register(); + assertThat(second.revision()).isGreaterThan(first.revision()); + assertThatThrownBy(() -> registry.preflightLaunchOwners(gameInstanceId)) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) + .hasMessageContaining("Frozen required-owner set is absent or invalidated"); + assertThat(f.retainedRows("world_runtime_required_owner_snapshot")).isEqualTo(frozen); + assertThatThrownBy(() -> registry.withLaunchOwners(gameInstanceId, calls::incrementAndGet)) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class); + assertThat(calls.get()).isEqualTo(2); + assertThat(f.retainedRows("world_runtime_required_owner_snapshot")).isEqualTo(frozen); + assertThat(registry.withLaunchOwners(UUID.randomUUID(), calls::incrementAndGet)).isEqualTo(3); + assertThat(f.count("world_runtime_required_owner_snapshot")).isEqualTo(2); + assertThat(f.count("world_instance")).isZero(); + } + } + + @Test + void missingCatalogAndUnresolvedClassificationPreventSnapshotAndCallback() { + try (Fixture f = fixture(null)) { + ObjectNode unresolved = (ObjectNode) JSON.readTree(artifact()); + ((ObjectNode) unresolved.get("members").get(0).get("families").get(0)) + .put("replacementClass", "UNRESOLVED"); + var source = new ControlledInstallationSource(JSON.writeValueAsBytes(unresolved)); + var registry = f.registry(source); + registry.register(); + AtomicInteger calls = new AtomicInteger(); + assertThatThrownBy(() -> registry.withLaunchOwners(UUID.randomUUID(), calls::incrementAndGet)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(f.count("world_runtime_required_owner_snapshot")).isZero(); + assertThat(calls.get()).isZero(); + + ObjectNode missing = (ObjectNode) JSON.readTree(artifact()); + ((ObjectNode) missing.get("members").get(0)).putArray("catalogSources"); + source.replace(JSON.writeValueAsBytes(missing)); + assertThatThrownBy(registry::register).isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> registry.withLaunchOwners(UUID.randomUUID(), calls::incrementAndGet)) + .isInstanceOf(IllegalArgumentException.class); + assertThat(f.count("world_runtime_installation_registration")).isEqualTo(1); + assertThat(f.count("world_runtime_required_owner_snapshot")).isZero(); + assertThat(calls.get()).isZero(); + } + } + + @Test + void heldSourceChangingInsideRegistrationRollsBackRowsAndCurrentPointer() { + try (Fixture f = fixture(null)) { + var source = new ControlledInstallationSource(artifact()); + source.changeOnCheck = 2; + source.replacement = artifact(); + assertThatThrownBy(() -> f.registry(source).register()) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class); + assertThat(f.count("world_runtime_installation_registration")).isZero(); + assertThat(f.count("world_runtime_installation_current")).isZero(); + assertThat(f.count("world_runtime_required_owner_snapshot")).isZero(); + assertThat(source.closed.get()).isEqualTo(1); + } + } + + @Test + void directSqlCannotFreezeACallerSelectedSubsetOrForeignRevision() { + try (Fixture f = fixture(null)) { + var registration = f.registry(new ControlledInstallationSource(artifact())).register(); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO world_runtime_required_owner_snapshot" + + "(canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" + + " SELECT ?,target_namespace,revision,artifact_digest," + + " jsonb_build_array(world_runtime_required_owners(artifact_bytes)->0)" + + " FROM world_runtime_installation_registration WHERE revision=?", + UUID.randomUUID(), + registration.revision())) + .hasMessageContaining("complete current installation"); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO world_runtime_required_owner_snapshot" + + "(canonical_game_instance_id,target_namespace,registry_revision,artifact_digest,required_owners)" + + " VALUES (?,?,?,?,world_runtime_required_owners(?))", + UUID.randomUUID(), + NAMESPACE, + registration.revision() + 1, + registration.artifact().digest(), + registration.artifact().exactBytes())) + .hasMessageContaining("Frozen owners must match the complete current installation") + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("23514")); + assertThat(f.count("world_runtime_required_owner_snapshot")).isZero(); + } + } + + @Test + void immutableRegistrationAndFrozenHistoryRejectUpdatesDeletesAndTruncate() { + try (Fixture f = fixture(null)) { + var registry = f.registry(new ControlledInstallationSource(artifact())); + registry.register(); + registry.withLaunchOwners(UUID.randomUUID(), () -> "controlled callback"); + for (String table : + List.of( + "world_runtime_installation_registration", "world_runtime_required_owner_snapshot")) { + var retained = f.retainedRows(table); + String column = + table.equals("world_runtime_installation_registration") + ? "artifact_digest" + : "required_owners"; + String truncate = "TRUNCATE " + table; + if (table.equals("world_runtime_installation_registration")) { + // Registration is FK-referenced by the current pointer and frozen snapshots. + truncate += " CASCADE"; + } + for (String statement : + List.of( + "UPDATE " + table + " SET " + column + "=" + column, + "DELETE FROM " + table, + truncate)) { + assertThatThrownBy(() -> f.dsl.execute(statement)) + .hasMessageContaining("Runtime installation and required-owner history is immutable") + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("55000")); + assertThat(f.retainedRows(table)).isEqualTo(retained); + } + } + } + } + + @Test + void currentPointerOnlyAdvancesAndHistoricalRegistrationCannotBeReinstalled() { + try (Fixture f = fixture(null)) { + byte[] firstBytes = artifact(); + var source = new ControlledInstallationSource(firstBytes); + var registry = f.registry(source); + var first = registry.register(); + source.replace(artifact()); + var second = registry.register(); + var pointer = f.retainedRows("world_runtime_installation_current"); + for (long revision : List.of(first.revision(), second.revision())) { + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE world_runtime_installation_current SET revision=?,artifact_digest=? WHERE target_namespace=?", + revision, + revision == first.revision() + ? first.artifact().digest() + : second.artifact().digest(), + NAMESPACE)) + .hasMessageContaining("monotonically"); + } + for (String statement : + List.of( + "DELETE FROM world_runtime_installation_current", + "TRUNCATE world_runtime_installation_current")) { + assertThatThrownBy(() -> f.dsl.execute(statement)) + .hasMessageContaining("Current runtime installation cannot be deleted") + .satisfies(failure -> assertThat(sqlState(failure)).isEqualTo("55000")); + } + source.replace(firstBytes); + assertThatThrownBy(registry::register) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) + .hasMessageContaining("Historical"); + assertThat(f.retainedRows("world_runtime_installation_current")).isEqualTo(pointer); + assertThat(f.count("world_runtime_installation_registration")).isEqualTo(2); + assertThat(registry.current().revision()).isEqualTo(second.revision()); + } + } + + @Test + void installedLaunchPredicateRequiresTheExactCurrentFreezeOnControlledReceiverOnly() { + try (Fixture f = fixture(null)) { + assertThat( + f.dsl + .fetchSingle( + "SELECT count(*) FROM pg_trigger t JOIN pg_class c ON c.oid=t.tgrelid" + + " JOIN pg_namespace n ON n.oid=c.relnamespace" + + " WHERE n.nspname=? AND c.relname='world_instance'" + + " AND t.tgname='world_instance_registered_launch_owners' AND NOT t.tgisinternal", + f.schema) + .get(0, Long.class)) + .isEqualTo(1); + // Separate schema avoids changing the genuine World catalog. This table exercises only + // the installed predicate; no canonical materialization guards are removed or bypassed. + String receiver = f.probeSchema() + ".launch_receiver"; + f.dsl.execute("CREATE SCHEMA " + f.probeSchema()); + f.dsl.execute( + "CREATE TABLE " + + receiver + + "(canonical_game_instance_id UUID PRIMARY KEY,canonical_target_namespace TEXT,status TEXT)"); + f.dsl.execute( + "CREATE TRIGGER controlled_launch_predicate BEFORE INSERT OR UPDATE ON " + + receiver + + " FOR EACH ROW EXECUTE FUNCTION " + + f.schema + + ".world_require_registered_launch_owners()"); + var source = new ControlledInstallationSource(artifact()); + var registry = f.registry(source); + registry.register(); + UUID instanceId = UUID.randomUUID(); + assertThatThrownBy( + () -> + f.dsl.execute( + "INSERT INTO " + receiver + " VALUES (?,?,'PREPARING')", + instanceId, + NAMESPACE)) + .hasMessageContaining("complete current frozen runtime owners"); + registry.withLaunchOwners( + instanceId, + () -> + f.dsl.execute( + "INSERT INTO " + receiver + " VALUES (?,?,'PREPARING')", instanceId, NAMESPACE)); + source.replace(artifact()); + registry.register(); + assertThatThrownBy( + () -> + f.dsl.execute( + "UPDATE " + + receiver + + " SET status='ACTIVE' WHERE canonical_game_instance_id=?", + instanceId)) + .hasMessageContaining("complete current frozen runtime owners"); + assertThat(f.dsl.fetchSingle("SELECT status FROM " + receiver).get(0, String.class)) + .isEqualTo("PREPARING"); + assertThat(f.count("world_instance")).isZero(); + assertThat(f.count("world_canonical_instance_preparation")).isZero(); + assertThat(f.count("character_location")).isZero(); + } + } + + @Test + void forward1048Preserves1047EpochsSnapshotsAndHistoryAndSealsEpochThree() { + try (Fixture f = fixture("1047")) { + var catalogOwner = + new WorldRuntimeFamilyCatalogRepository(f.dsl, f.manager, f.schema, NAMESPACE); + Request oldRequest = new Request(UUID.randomUUID(), NAMESPACE); + var oldSnapshot = catalogOwner.read(oldRequest); + assertThat(oldSnapshot.catalog().catalogEpoch()).isEqualTo(2); + var epochs = f.retainedRows("world_runtime_family_catalog_epoch"); + var snapshots = f.retainedRows("world_runtime_family_catalog_snapshot"); + var history = f.retainedRows(HISTORY); + assertThat(f.count("saga_instance")).isZero(); + + migration(f.source, f.schema, null).migrate(); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text AS value" + + " FROM world_runtime_family_catalog_epoch t WHERE catalog_epoch<=2 ORDER BY value") + .getValues(0, String.class)) + .isEqualTo(epochs); + assertThat(f.retainedRows("world_runtime_family_catalog_snapshot")).isEqualTo(snapshots); + assertThat( + f.dsl + .fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text AS value FROM " + + HISTORY + + " t WHERE version IS DISTINCT FROM '1048' ORDER BY value") + .getValues(0, String.class)) + .isEqualTo(history); + assertThat(f.count("world_runtime_family_catalog_epoch")).isEqualTo(3); + assertThatThrownBy(() -> catalogOwner.readExact(oldRequest)) + .isInstanceOf(WorldRuntimeFamilyCatalogRepository.CatalogConflictException.class); + var current = catalogOwner.read(new Request(UUID.randomUUID(), NAMESPACE)).catalog(); + assertThat(current.catalogEpoch()).isEqualTo(3); + assertThat(current.families()) + .anyMatch(family -> family.familyId().equals("world_runtime_installation_registration")); + assertThat( + f.dsl + .fetchSingle( + "SELECT catalog_bytes=world_runtime_family_catalog_bytes(catalog_epoch)" + + " FROM world_runtime_family_catalog_epoch WHERE catalog_epoch=3") + .get(0, Boolean.class)) + .isTrue(); + assertThat(f.count("world_runtime_installation_registration")).isZero(); + migration(f.source, f.schema, null).validate(); + } + } + + private static byte[] artifact() { + ObjectNode root = JSON.createObjectNode(); + root.put("schema", "firemud-runtime-installation-inventory/v1"); + root.put("artifactId", UUID.randomUUID().toString()); + root.put("installationId", UUID.randomUUID().toString()); + root.put("environment", "staging"); + root.put("generation", "controlled-installation-generation"); + root.put("clusterUid", "controlled-cluster-uid"); + root.put("namespaceUid", "controlled-namespace-uid"); + root.put("namespace", NAMESPACE); + root.put("sourceCommit", "b".repeat(40)); + root.put("renderedManifestDigest", DIGEST); + root.put("declarationsDigest", DIGEST); + ObjectNode executor = root.putObject("executor"); + executor.put("identity", "controlled-synthetic-protected-source/v1"); + executor.put("versionDigest", DIGEST); + ObjectNode bindings = root.putObject("inputBindings"); + for (String category : + List.of( + "migrations", + "configurations", + "mountedResources", + "secretContracts", + "externalBindings")) { + bindings.putArray(category); + } + ArrayNode members = root.putArray("members"); + members.add(member("entity", "entity-management-service", "APPLICATION")); + members.add(member("world", "world-management-service", "APPLICATION")); + members.add(member("foreign-sidecar", "", "INIT")); + return JSON.writeValueAsBytes(root); + } + + private static ObjectNode member(String name, String owner, String kind) { + ObjectNode member = JSON.createObjectNode(); + member.put("workloadApiVersion", "v1"); + member.put("workloadKind", "Pod"); + member.put("workloadNamespace", NAMESPACE); + member.put("workloadName", "controlled-runtime"); + member.put("containerKind", kind); + member.put("containerName", name); + member.put("image", "registry.example/controlled/" + name + "@" + DIGEST); + member.put("ownerId", owner); + member.put("ownership", owner.isEmpty() ? "NO_INSTANCE_STATE" : "RUNTIME_OWNER"); + ArrayNode sources = member.putArray("catalogSources"); + ArrayNode families = member.putArray("families"); + if (!owner.isEmpty()) { + ObjectNode source = sources.addObject(); + source.put("sourceId", owner + "-sql"); + source.put("contract", owner + "/catalog/v1"); + source.put("epoch", "1"); + source.put("digest", DIGEST); + ObjectNode family = families.addObject(); + family.put("familyId", name + "-state"); + family.put("catalogSourceId", owner + "-sql"); + family.put("replacementClass", "S3"); + ObjectNode cleanup = family.putObject("cleanupContract"); + for (String field : List.of("operation", "requestIdentity", "acknowledgement", "retention")) { + cleanup.put(field, owner + "/" + field + "/v1"); + } + } + return member; + } + + /** + * Synthetic hold only: production custody/completeness and external installation are unproved. + */ + private static final class ControlledInstallationSource + implements WorldRuntimeInstallationRegistry.ProtectedInstallationSource { + private final AtomicReference current; + private final AtomicInteger closed = new AtomicInteger(); + private int changeOnCheck = -1; + private byte[] replacement; + + private ControlledInstallationSource(byte[] initial) { + current = new AtomicReference<>(initial.clone()); + } + + private void replace(byte[] value) { + current.set(value.clone()); + } + + @Override + public WorldRuntimeInstallationRegistry.HeldInstallation acquireCurrent() { + byte[] held = current.get().clone(); + return new WorldRuntimeInstallationRegistry.HeldInstallation() { + private int checks; + + @Override + public byte[] exactArtifactBytes() { + return held.clone(); + } + + @Override + public void requireCurrent() { + if (++checks == changeOnCheck) replace(replacement); + if (!Arrays.equals(held, current.get())) { + throw new WorldRuntimeInstallationRegistry.RegistryUnavailableException( + "Controlled held installation changed"); + } + } + + @Override + public void close() { + closed.incrementAndGet(); + } + }; + } + } + + private static Fixture fixture(String target) { + String schema = "world_registry_" + UUID.randomUUID().toString().replace("-", ""); + var source = + new DriverManagerDataSource( + postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + source.setSchema(schema); + var dsl = DSL.using(new TransactionAwareDataSourceProxy(source), SQLDialect.POSTGRES); + try { + migration(source, schema, target).migrate(); + return new Fixture(schema, source, dsl, new DataSourceTransactionManager(source)); + } catch (RuntimeException failed) { + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + throw failed; + } + } + + private static String sqlState(Throwable failure) { + for (Throwable current = failure; current != null; current = current.getCause()) { + if (current instanceof SQLException sqlException) return sqlException.getSQLState(); + } + return null; + } + + private record Fixture( + String schema, + DriverManagerDataSource source, + DSLContext dsl, + DataSourceTransactionManager manager) + implements AutoCloseable { + WorldRuntimeInstallationRegistry registry(ControlledInstallationSource source) { + return new WorldRuntimeInstallationRegistry(dsl, manager, schema, NAMESPACE, source); + } + + String probeSchema() { + return schema + "_probe"; + } + + long count(String table) { + return dsl.fetchSingle("SELECT count(*) FROM " + table).get(0, Long.class); + } + + List retainedRows(String table) { + return dsl.fetch( + "SELECT to_jsonb(t)::text||':'||xmin::text AS value FROM " + + table + + " t ORDER BY value") + .getValues(0, String.class); + } + + @Override + public void close() { + dsl.execute("DROP SCHEMA IF EXISTS " + probeSchema() + " CASCADE"); + dsl.execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE"); + } + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java index 747cef5e7e..86d4755582 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstanceActivationServiceTest.java @@ -12,13 +12,16 @@ import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; import net.firedevops.firemud.common.account.startsession.AccountStartSessionActivationProtectionEvidence; import net.firedevops.firemud.common.world.WorldCanonicalInstanceActivation; import net.firedevops.firemud.common.world.WorldCanonicalInstanceLifecycleEvidence; import net.firedevops.firemud.common.world.WorldOriginalStartSessionActivationTerminalEvidence; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -99,8 +102,27 @@ void retainedRequestOnlyVerifierCannotAuthorizeFreshActivation() { @Test void protectedOperationHoldsItsDistinctAuthorityAroundTheOwnerCas() { var repository = mock(WorldCanonicalInstanceActivationRepository.class); - var protection = mock(AccountStartSessionActivationProtectionEvidence.class); + var protection = + mock( + AccountStartSessionActivationProtectionEvidence.class, + org.mockito.Mockito.RETURNS_DEEP_STUBS); var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + UUID gameInstanceId = UUID.fromString("bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"); + when(protection.request().worldActivationRequest().canonicalGameInstanceId()) + .thenReturn(gameInstanceId); + var installation = mock(WorldRuntimeInstallationRegistry.class); + var installationHeld = new AtomicBoolean(); + when(installation.withLaunchOwners(eq(gameInstanceId), any())) + .thenAnswer( + call -> { + Supplier owner = call.getArgument(1); + installationHeld.set(true); + try { + return owner.get(); + } finally { + installationHeld.set(false); + } + }); var heldChecks = new AtomicInteger(); var closed = new java.util.concurrent.atomic.AtomicBoolean(); var held = @@ -115,16 +137,59 @@ public void close() { closed.set(true); } }; - when(repository.activateProtected(eq(protection), any())).thenReturn(terminal); - var service = new WorldCanonicalInstanceActivationService(repository); + when(repository.readTerminalEvidence(protection)).thenReturn(Optional.empty()); + when(repository.activateProtected(eq(protection), any())) + .thenAnswer( + call -> { + assertThat(installationHeld).isTrue(); + assertThat(closed).isFalse(); + return terminal; + }); + var service = new WorldCanonicalInstanceActivationService(repository, installation); assertThat(service.activateProtected(protection, held)).isSameAs(terminal); assertThat(heldChecks).hasValue(2); assertThat(closed.get()).isTrue(); + assertThat(installationHeld).isFalse(); + verify(installation).withLaunchOwners(eq(gameInstanceId), any()); verify(repository).activateProtected(eq(protection), eq(held)); } + @Test + void protectedFreshOperationWithoutInstallationRefusesBeforeTheOwnerCasAndClosesLocalHold() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var protection = mock(AccountStartSessionActivationProtectionEvidence.class); + var held = mock(WorldCanonicalInstanceActivationService.HeldActivationAuthority.class); + when(repository.readTerminalEvidence(protection)).thenReturn(Optional.empty()); + var service = new WorldCanonicalInstanceActivationService(repository); + + assertThatThrownBy(() -> service.activateProtected(protection, held)) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) + .hasMessageContaining("current-installation registry is unavailable"); + + verify(repository).readTerminalEvidence(protection); + verify(repository, never()).activateProtected(any(), any()); + verify(held).requireHeld(); + verify(held).close(); + } + + @Test + void exactProtectedTerminalReplaysWithoutCurrentInstallationOrAnotherCas() { + var repository = mock(WorldCanonicalInstanceActivationRepository.class); + var protection = mock(AccountStartSessionActivationProtectionEvidence.class); + var held = mock(WorldCanonicalInstanceActivationService.HeldActivationAuthority.class); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + when(repository.readTerminalEvidence(protection)).thenReturn(Optional.of(terminal)); + var service = new WorldCanonicalInstanceActivationService(repository); + + assertThat(service.activateProtected(protection, held)).isSameAs(terminal); + + verify(repository, never()).activateProtected(any(), any()); + verify(held, org.mockito.Mockito.times(2)).requireHeld(); + verify(held).close(); + } + private static WorldCanonicalInstanceActivation.Request request() { var lifecycleRequest = mock(WorldCanonicalInstanceLifecycleEvidence.Request.class); when(lifecycleRequest.canonicalGameInstanceId()) diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPreflightTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPreflightTest.java new file mode 100644 index 0000000000..71923509f7 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationPreflightTest.java @@ -0,0 +1,207 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +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.doThrow; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.mockStatic; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.HeldCommitAuthority; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.OriginalOperationCommitAuthorityVerifier; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier; +import org.junit.jupiter.api.Test; + +/** Mock-only early-refusal and historical-replay ordering; no installed authority is implied. */ +class WorldCanonicalInstancePreparationPreflightTest { + private final WorldCanonicalInstancePreparationRepository repository = + mock(WorldCanonicalInstancePreparationRepository.class); + private final WorldRuntimeInstallationRegistry registry = + mock(WorldRuntimeInstallationRegistry.class); + private final OriginalOperationCommitAuthorityVerifier verifier = + mock(OriginalOperationCommitAuthorityVerifier.class); + private final WorldCanonicalInstancePreparation.Input input = + mock(WorldCanonicalInstancePreparation.Input.class); + private final WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput operation = + mock(WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput.class); + private final UUID instanceId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + + @Test + void unavailableInstallationRefusesBeforeAccountParticipationAcquisition() { + var service = service(); + doThrow(new WorldRuntimeInstallationRegistry.RegistryUnavailableException("unavailable source")) + .when(registry) + .preflightLaunchOwners(instanceId); + + assertThatThrownBy(() -> service.prepare(input, operation)) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) + .hasMessage("unavailable source"); + + var order = inOrder(repository, registry); + order.verify(repository).hasRetainedCommittedCandidate(input, operation); + order.verify(registry).preflightLaunchOwners(instanceId); + verifyNoInteractions(verifier); + } + + @Test + void committedCandidateStillRequiresAuthenticationBeforeAnyHistoricalReturn() { + var service = service(); + when(repository.hasRetainedCommittedCandidate(input, operation)).thenReturn(true); + when(verifier.verifyAndHold(input, operation)).thenThrow(new SecurityException("denied")); + + assertThatThrownBy(() -> service.prepare(input, operation)) + .isInstanceOf(SecurityException.class) + .hasMessage("denied"); + + verifyNoInteractions(registry); + verify(repository, never()).readRetainedCommittedResult(eq(input), any()); + } + + @Test + void exactCommittedReplayKeepsHeldQualificationAndBypassesCurrentInstallation() { + var service = service(); + var held = mock(HeldCommitAuthority.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var result = mock(WorldCanonicalInstancePreparation.Result.class); + when(repository.hasRetainedCommittedCandidate(input, operation)).thenReturn(true); + when(verifier.verifyAndHold(input, operation)).thenReturn(held); + when(held.executionIdentity()).thenReturn(identity); + when(repository.readRetainedCommittedResult(input, held)).thenReturn(Optional.of(result)); + + try (var inputEncoding = mockStatic(WorldCanonicalInstancePreparationRepository.class)) { + inputEncoding + .when(() -> WorldCanonicalInstancePreparationRepository.inputJson(input)) + .thenReturn("{}"); + assertThat(service.prepare(input, operation)).isSameAs(result); + } + + var order = inOrder(repository, verifier, held, identity); + order.verify(repository).hasRetainedCommittedCandidate(input, operation); + order.verify(verifier).verifyAndHold(input, operation); + order.verify(held).requireHeld(); + order.verify(held).executionIdentity(); + order.verify(identity).requireMatches(input, operation, "{}"); + order.verify(repository).readRetainedCommittedResult(input, held); + order.verify(held).close(); + verifyNoInteractions(registry); + } + + @Test + void exactCommittedReplayWithoutRegistryStillRequiresHeldAuthentication() { + var service = service(false); + var held = mock(HeldCommitAuthority.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + var result = mock(WorldCanonicalInstancePreparation.Result.class); + when(repository.hasRetainedCommittedCandidate(input, operation)).thenReturn(true); + when(verifier.verifyAndHold(input, operation)).thenReturn(held); + when(held.executionIdentity()).thenReturn(identity); + when(repository.readRetainedCommittedResult(input, held)).thenReturn(Optional.of(result)); + + try (var inputEncoding = mockStatic(WorldCanonicalInstancePreparationRepository.class)) { + inputEncoding + .when(() -> WorldCanonicalInstancePreparationRepository.inputJson(input)) + .thenReturn("{}"); + assertThat(service.prepare(input, operation)).isSameAs(result); + } + + var order = inOrder(repository, verifier, held, identity); + order.verify(repository).hasRetainedCommittedCandidate(input, operation); + order.verify(verifier).verifyAndHold(input, operation); + order.verify(held).requireHeld(); + order.verify(held).executionIdentity(); + order.verify(identity).requireMatches(input, operation, "{}"); + order.verify(repository).readRetainedCommittedResult(input, held); + order.verify(held).close(); + verifyNoInteractions(registry); + verify(repository, never()).materialize(input, held); + } + + @Test + void falseCommittedCandidateWithoutRegistryDeniesAfterHeldQualificationAndExactRead() { + var service = service(false); + var held = mock(HeldCommitAuthority.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + when(repository.hasRetainedCommittedCandidate(input, operation)).thenReturn(true); + when(verifier.verifyAndHold(input, operation)).thenReturn(held); + when(held.executionIdentity()).thenReturn(identity); + when(repository.readRetainedCommittedResult(input, held)).thenReturn(Optional.empty()); + + try (var inputEncoding = mockStatic(WorldCanonicalInstancePreparationRepository.class)) { + inputEncoding + .when(() -> WorldCanonicalInstancePreparationRepository.inputJson(input)) + .thenReturn("{}"); + assertThatThrownBy(() -> service.prepare(input, operation)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessage("Protected current-installation registry is unavailable"); + } + + var order = inOrder(repository, verifier, held, identity); + order.verify(repository).hasRetainedCommittedCandidate(input, operation); + order.verify(verifier).verifyAndHold(input, operation); + order.verify(held).requireHeld(); + order.verify(held).executionIdentity(); + order.verify(identity).requireMatches(input, operation, "{}"); + order.verify(repository).readRetainedCommittedResult(input, held); + order.verify(held).close(); + verifyNoInteractions(registry); + verify(repository, never()).materialize(input, held); + } + + @Test + void candidateWithoutExactRetainedResultStillRequiresCommitTimeInstallationGuard() { + var service = service(); + var held = mock(HeldCommitAuthority.class); + var identity = mock(WorldCanonicalInstanceExecutionIdentity.class); + when(repository.hasRetainedCommittedCandidate(input, operation)).thenReturn(true); + when(verifier.verifyAndHold(input, operation)).thenReturn(held); + when(held.executionIdentity()).thenReturn(identity); + when(repository.readRetainedCommittedResult(input, held)).thenReturn(Optional.empty()); + when(registry.withLaunchOwners(eq(instanceId), any())) + .thenThrow( + new WorldRuntimeInstallationRegistry.RegistryUnavailableException( + "changed installation")); + + try (var inputEncoding = mockStatic(WorldCanonicalInstancePreparationRepository.class)) { + inputEncoding + .when(() -> WorldCanonicalInstancePreparationRepository.inputJson(input)) + .thenReturn("{}"); + assertThatThrownBy(() -> service.prepare(input, operation)) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) + .hasMessage("changed installation"); + } + + verify(registry, never()).preflightLaunchOwners(instanceId); + verify(registry).withLaunchOwners(eq(instanceId), any()); + verify(held).close(); + verify(repository, never()).materialize(input, held); + } + + private WorldCanonicalInstancePreparationService service() { + return service(true); + } + + private WorldCanonicalInstancePreparationService service(boolean withRegistry) { + var evidence = mock(WorldCanonicalInstanceAssociation.GameSessionReadEvidence.class); + var topology = mock(WorldCanonicalInstanceTopologyPlan.class); + when(input.gameSessionReadEvidence()).thenReturn(evidence); + when(evidence.targetNamespace()).thenReturn("firemud"); + when(input.canonicalGameInstanceId()).thenReturn(instanceId); + when(input.topologyPlan()).thenReturn(topology); + when(topology.generationRules()).thenReturn(List.of()); + when(topology.spawnBindings()).thenReturn(List.of()); + var recoveryVerifier = mock(OriginalOperationRecoveryVerifier.class); + return withRegistry + ? new WorldCanonicalInstancePreparationService( + repository, verifier, recoveryVerifier, registry) + : new WorldCanonicalInstancePreparationService(repository, verifier, recoveryVerifier); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java index df476a7925..65a562297e 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldCanonicalInstancePreparationServiceTest.java @@ -11,12 +11,15 @@ import static org.mockito.Mockito.when; import java.util.Optional; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceAssociation; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceExecutionIdentity; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparation; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionLookup; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionOperation; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationRepository.ExecutionState; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstancePreparationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceTopologyPlan; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -149,6 +152,40 @@ void freshPreparationWithoutTypedOriginalOwnerInputDeniesEvenWithLegacyVerifier( verifyNoInteractions(repository, commitVerifier, input); } + @Test + void missingInstallationRegistryDeniesBeforeAcquiringAccountParticipation() { + var repository = mock(WorldCanonicalInstancePreparationRepository.class); + var input = mock(WorldCanonicalInstancePreparation.Input.class); + var evidence = mock(WorldCanonicalInstanceAssociation.GameSessionReadEvidence.class); + var topology = mock(WorldCanonicalInstanceTopologyPlan.class); + when(input.gameSessionReadEvidence()).thenReturn(evidence); + when(evidence.targetNamespace()).thenReturn("test"); + when(input.topologyPlan()).thenReturn(topology); + when(topology.generationRules()).thenReturn(java.util.List.of()); + when(topology.spawnBindings()).thenReturn(java.util.List.of()); + + var operationInput = + mock(WorldCanonicalInstancePreparation.OriginalStartSessionOperationInput.class); + var verifier = + mock( + WorldCanonicalInstancePreparationService.OriginalOperationCommitAuthorityVerifier + .class); + var service = + new WorldCanonicalInstancePreparationService( + repository, + verifier, + mock(WorldCanonicalInstancePreparationService.OriginalOperationRecoveryVerifier.class)); + + assertThatThrownBy(() -> service.prepare(input, operationInput)) + .isInstanceOf(WorldCanonicalInstancePreparationService.PreparationDeniedException.class) + .hasMessage("Protected current-installation registry is unavailable"); + + verify(operationInput).requireMatches(input, "test"); + verify(repository).hasRetainedCommittedCandidate(input, operationInput); + verifyNoMoreInteractions(repository); + verifyNoInteractions(verifier); + } + @Test void exactRecoveryAuthenticatesThenReturnsTheUnchangedReadOnlyLookup() { var repository = mock(WorldCanonicalInstancePreparationRepository.class); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java index 2790aeb3af..ffad688ece 100644 --- a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldOriginalStartSessionProtectedActivationServiceTest.java @@ -5,6 +5,8 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -21,6 +23,7 @@ import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationRepository; import net.firedevops.firemud.worldmanagement.tenant.WorldCanonicalInstanceActivationService; import net.firedevops.firemud.worldmanagement.tenant.WorldOriginalStartSessionProtectedActivationService; +import net.firedevops.firemud.worldmanagement.tenant.WorldRuntimeInstallationRegistry; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.support.TransactionSynchronizationManager; @@ -147,6 +150,77 @@ void accountReceiptChangingOriginalTupleIsDeniedBeforeWorldWrite() { verify(activation, never()).activateProtected(any(), any()); } + @Test + void missingInstallationDeniesFreshActivationBeforeAcquiringAccountProtection() { + var input = matchingInput(); + when(repository.readProtectedActivationByAcquisitionInput(input)).thenReturn(Optional.empty()); + var defaultDenied = + new WorldOriginalStartSessionProtectedActivationService( + repository, + new WorldCanonicalInstanceActivationService(repository), + account, + "world-runtime"); + + assertThatThrownBy(() -> defaultDenied.activate(input)) + .isInstanceOf(WorldCanonicalInstanceActivationService.ActivationDeniedException.class) + .hasMessageContaining("current-installation registry is unavailable"); + + verifyNoInteractions(account, activation); + verify(repository, never()).readTerminalEvidence(any()); + verify(repository, never()).activateProtected(any(), any()); + } + + @Test + void missingInstallationStillReplaysRetainedTerminalBeforeAcquiringAccountProtection() { + var input = matchingInput(); + var terminal = mock(WorldOriginalStartSessionActivationTerminalEvidence.class); + when(repository.readProtectedActivationByAcquisitionInput(input)) + .thenReturn( + Optional.of( + new WorldCanonicalInstanceActivationRepository.ProtectedActivationReadback( + false, terminal))); + var defaultDenied = + new WorldOriginalStartSessionProtectedActivationService( + repository, + new WorldCanonicalInstanceActivationService(repository), + account, + "world-runtime"); + + assertThat(defaultDenied.activate(input)).isSameAs(terminal); + + verifyNoInteractions(account, activation); + verify(repository, never()).readTerminalEvidence(any()); + verify(repository, never()).activateProtected(any(), any()); + } + + @Test + void unavailableProtectedSourceRefusesBeforeAccountAcquisition() { + var input = matchingInput(); + var instanceId = UUID.fromString("88888888-8888-4888-8888-888888888888"); + when(input.worldActivationRequest().canonicalGameInstanceId()).thenReturn(instanceId); + when(repository.readProtectedActivationByAcquisitionInput(input)).thenReturn(Optional.empty()); + var registry = mock(WorldRuntimeInstallationRegistry.class); + doThrow(new WorldRuntimeInstallationRegistry.RegistryUnavailableException("source unavailable")) + .when(registry) + .preflightLaunchOwners(instanceId); + var composed = + new WorldOriginalStartSessionProtectedActivationService( + repository, + new WorldCanonicalInstanceActivationService(repository, registry), + account, + "world-runtime"); + + assertThatThrownBy(() -> composed.activate(input)) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) + .hasMessage("source unavailable"); + + var order = inOrder(repository, registry); + order.verify(repository).readProtectedActivationByAcquisitionInput(input); + order.verify(registry).preflightLaunchOwners(instanceId); + verifyNoInteractions(account); + verify(repository, never()).activateProtected(any(), any()); + } + private static AccountStartSessionActivationProtectionAcquisitionInput matchingInput() { var input = mock(AccountStartSessionActivationProtectionAcquisitionInput.class); var request = mock(WorldCanonicalInstanceActivation.Request.class); diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifactTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifactTest.java new file mode 100644 index 0000000000..abfe1e11cb --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationArtifactTest.java @@ -0,0 +1,367 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; + +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.UUID; +import java.util.function.Consumer; +import net.firedevops.firemud.common.world.WorldRuntimeFamilyCatalog; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import tools.jackson.databind.json.JsonMapper; +import tools.jackson.databind.node.ArrayNode; +import tools.jackson.databind.node.ObjectNode; + +class WorldRuntimeInstallationArtifactTest { + private static final JsonMapper JSON = JsonMapper.builder().build(); + private static final String DIGEST = "sha256:" + "a".repeat(64); + private static final String IMAGE = "registry.example/world@" + DIGEST; + private static final String FIXTURE = + """ + { + "schema":"firemud-runtime-installation-inventory/v1", + "artifactId":"e8975b6d-88ca-4b50-8307-e0f8c8cccd53", + "installationId":"56b80b22-977d-47bb-89db-6705d84294b1", + "environment":"staging", + "generation":"captured-generation", + "clusterUid":"captured-cluster-uid", + "namespaceUid":"captured-namespace-uid", + "namespace":"firemud", + "sourceCommit":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "renderedManifestDigest":"DIGEST", + "declarationsDigest":"DIGEST", + "executor":{"identity":"protected/executor/v1","versionDigest":"DIGEST"}, + "inputBindings":{ + "migrations":[],"configurations":[],"mountedResources":[], + "secretContracts":[{"name":"identity","version":"captured-v3","digest":"DIGEST"}], + "externalBindings":[] + }, + "members":[ + { + "workloadApiVersion":"v1","workloadKind":"Pod", + "workloadNamespace":"firemud","workloadName":"world", + "containerKind":"APPLICATION","containerName":"application","image":"IMAGE", + "ownerId":"world-management-service","ownership":"RUNTIME_OWNER", + "catalogSources":[{"sourceId":"world-sql","contract":"world/catalog/v1","epoch":"1","digest":"DIGEST"}], + "families":[{ + "familyId":"world-state","catalogSourceId":"world-sql","replacementClass":"S3", + "cleanupContract":{ + "operation":"world/cleanup/v1","requestIdentity":"world/request/v1", + "acknowledgement":"world/ack/v1","retention":"world/retention/v1" + } + }] + }, + { + "workloadApiVersion":"v1","workloadKind":"Pod", + "workloadNamespace":"firemud","workloadName":"world", + "containerKind":"INIT","containerName":"foreign-sidecar","image":"IMAGE", + "ownerId":"","ownership":"NO_INSTANCE_STATE","catalogSources":[],"families":[] + } + ] + } + """ + .replace("IMAGE", IMAGE) + .replace("DIGEST", DIGEST); + + @Test + void acceptsTheActualPythonProducerInteroperabilityVectorWithoutReserialization() + throws Exception { + java.nio.file.Path root = java.nio.file.Path.of("").toAbsolutePath(); + while (root != null && !java.nio.file.Files.exists(root.resolve("settings.gradle.kts"))) { + root = root.getParent(); + } + if (root == null) throw new IllegalStateException("Repository fixture root unavailable"); + byte[] emitted = + java.nio.file.Files.readAllBytes( + root.resolve("dev-tools/deploy/fixtures/runtime-installation/candidate.json")); + var artifact = WorldRuntimeInstallationArtifact.parse(emitted); + artifact.requireResolved(); + assertThat(artifact.exactBytes()).isEqualTo(emitted); + assertThat(artifact.namespace()).isEqualTo("firemud"); + assertThat(artifact.digest()).isEqualTo(WorldRuntimeFamilyCatalog.sha256(emitted)); + } + + @Test + void retainsWholeExactArtifactIdentityAndCatalogEvidence() { + byte[] bytes = bytes(FIXTURE); + var artifact = WorldRuntimeInstallationArtifact.parse(bytes); + + artifact.requireResolved(); + assertThat(artifact.artifactId()) + .isEqualTo(UUID.fromString("e8975b6d-88ca-4b50-8307-e0f8c8cccd53")); + assertThat(artifact.installationId()) + .isEqualTo(UUID.fromString("56b80b22-977d-47bb-89db-6705d84294b1")); + assertThat(artifact.namespace()).isEqualTo("firemud"); + assertThat(artifact.exactBytes()).isEqualTo(bytes); + assertThat(artifact.digest()).isEqualTo(WorldRuntimeFamilyCatalog.sha256(bytes)); + assertThat(new String(artifact.exactBytes(), StandardCharsets.UTF_8)) + .contains("world/catalog/v1", "world/cleanup/v1", "captured-v3", "foreign-sidecar"); + } + + @Test + void sourceAndReturnedArraysCannotMutateRetainedEvidence() { + byte[] original = bytes(FIXTURE); + byte[] supplied = original.clone(); + var artifact = WorldRuntimeInstallationArtifact.parse(supplied); + String digest = artifact.digest(); + supplied[0] = 0; + byte[] returned = artifact.exactBytes(); + returned[1] = 0; + + assertThat(artifact.exactBytes()).isEqualTo(original); + assertThat(artifact.digest()).isEqualTo(digest); + } + + @Test + void changedExactBytesAndInputDigestsChangeArtifactDigest() { + var original = WorldRuntimeInstallationArtifact.parse(bytes(FIXTURE)); + var whitespace = WorldRuntimeInstallationArtifact.parse(bytes(FIXTURE + "\n")); + var manifest = + WorldRuntimeInstallationArtifact.parse( + changed(root -> root.put("renderedManifestDigest", "sha256:" + "b".repeat(64)))); + var declarations = + WorldRuntimeInstallationArtifact.parse( + changed(root -> root.put("declarationsDigest", "sha256:" + "c".repeat(64)))); + + assertThat(whitespace.artifactId()).isEqualTo(original.artifactId()); + assertThat(whitespace.digest()).isNotEqualTo(original.digest()); + assertThat(manifest.digest()).isNotEqualTo(original.digest()); + assertThat(declarations.digest()).isNotEqualTo(original.digest()); + } + + @Test + void rejectsDuplicatesTrailingTokensInvalidUtf8AndNullRoots() { + List invalid = + List.of( + bytes(FIXTURE.replace("\"schema\":", "\"schema\":\"duplicate\",\"schema\":")), + bytes(FIXTURE.replace("\"epoch\":\"1\"", "\"epoch\":\"1\",\"epoch\":\"2\"")), + bytes(FIXTURE + " {}"), + bytes(FIXTURE + " null"), + bytes("null"), + bytes("[]"), + bytes(""), + new byte[] {(byte) 0xc3, (byte) 0x28}, + bytes(FIXTURE.replace("captured-generation", "\\uD800"))); + for (byte[] value : invalid) { + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldRuntimeInstallationArtifact.parse(value)); + } + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldRuntimeInstallationArtifact.parse(null)); + } + + @Test + void rejectsUnknownMissingNullAndWrongTypedClosedFields() { + List> mutations = + List.of( + root -> root.put("authority", "installed"), + root -> root.remove("declarationsDigest"), + root -> root.putNull("artifactId"), + root -> root.put("generation", 1), + root -> object(root, "executor").put("credential", "unknown"), + root -> object(root, "inputBindings").remove("mountedResources"), + root -> object(root, "inputBindings").put("migrations", "missing"), + root -> object(root, "inputBindings").putArray("unknown"), + root -> owner(root).put("extra", true), + root -> source(root).remove("contract"), + root -> family(root).put("unknown", "field"), + root -> object(family(root), "cleanupContract").remove("retention"), + root -> object(family(root), "cleanupContract").putNull("acknowledgement"), + root -> object(family(root), "cleanupContract").put("requestIdentity", "")); + for (Consumer mutation : mutations) refuses(mutation); + } + + @Test + void enforcesFormatsEnumsAndExplicitOwnerEvidence() { + List> mutations = + List.of( + root -> root.put("schema", "firemud-runtime-installation-inventory/v2"), + root -> root.put("artifactId", "00000000-0000-0000-0000-000000000000"), + root -> root.put("installationId", "56B80B22-977D-47BB-89DB-6705D84294B1"), + root -> root.put("environment", "unknown"), + root -> root.put("sourceCommit", "main"), + root -> root.put("namespace", "FireMUD"), + root -> root.put("renderedManifestDigest", "sha256:" + "A".repeat(64)), + root -> root.put("generation", "\u00a0captured"), + root -> owner(root).put("workloadNamespace", "elsewhere"), + root -> owner(root).put("workloadKind", "Unknown"), + root -> owner(root).put("workloadApiVersion", "apps/v1"), + root -> owner(root).put("containerKind", "SIDECAR"), + root -> owner(root).put("image", "world:latest"), + root -> owner(root).put("ownership", "UNKNOWN"), + root -> owner(root).put("ownerId", ""), + root -> owner(root).putArray("catalogSources"), + root -> owner(root).put("ownership", "NO_INSTANCE_STATE"), + root -> source(root).put("epoch", "01"), + root -> source(root).put("epoch", "0"), + root -> source(root).put("epoch", 1), + root -> family(root).put("catalogSourceId", "missing"), + root -> family(root).put("replacementClass", "S4")); + for (Consumer mutation : mutations) refuses(mutation); + } + + @Test + void rejectsUnsortedMembersAndDuplicateCrossReferences() { + refuses( + root -> { + owner(root).put("containerKind", "INIT"); + owner(root).put("containerName", "z-last"); + }); + refuses(root -> members(root).set(1, owner(root).deepCopy())); + refuses( + root -> { + ArrayNode sources = (ArrayNode) owner(root).get("catalogSources"); + sources.add(source(root).deepCopy()); + }); + refuses( + root -> { + ArrayNode families = (ArrayNode) owner(root).get("families"); + families.add(family(root).deepCopy()); + }); + refuses( + root -> { + ObjectNode second = (ObjectNode) members(root).get(1); + second.put("ownerId", "world-management-service"); + second.put("ownership", "RUNTIME_OWNER"); + second.set("catalogSources", owner(root).get("catalogSources").deepCopy()); + second.set("families", owner(root).get("families").deepCopy()); + }); + refuses( + root -> { + ArrayNode bindings = (ArrayNode) root.get("inputBindings").get("secretContracts"); + bindings.add(bindings.get(0).deepCopy()); + }); + } + + @Test + void unresolvedAndMissingOwnerSetsRemainParseableButBlockQualification() { + var unresolved = + WorldRuntimeInstallationArtifact.parse( + changed(root -> family(root).put("replacementClass", "UNRESOLVED"))); + assertThat(new String(unresolved.exactBytes(), StandardCharsets.UTF_8)).contains("UNRESOLVED"); + assertThatIllegalArgumentException().isThrownBy(unresolved::requireResolved); + + var noOwner = + WorldRuntimeInstallationArtifact.parse( + changed( + root -> { + owner(root).put("ownership", "NO_INSTANCE_STATE"); + owner(root).put("ownerId", ""); + owner(root).putArray("catalogSources"); + owner(root).putArray("families"); + })); + assertThatIllegalArgumentException().isThrownBy(noOwner::requireResolved); + var empty = WorldRuntimeInstallationArtifact.parse(changed(root -> root.putArray("members"))); + assertThatIllegalArgumentException().isThrownBy(empty::requireResolved); + } + + @Test + void enforcesArtifactFieldAndArrayCeilings() { + byte[] oversized = + bytes( + FIXTURE + + " " + .repeat( + WorldRuntimeInstallationArtifact.MAX_BYTES + 1 - bytes(FIXTURE).length)); + assertThat(oversized).hasSize(WorldRuntimeInstallationArtifact.MAX_BYTES + 1); + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldRuntimeInstallationArtifact.parse(oversized)) + .withMessage("Artifact byte bound exceeded"); + refuses(root -> root.put("generation", "x".repeat(257))); + refuses(root -> root.put("generation", "\u00e9".repeat(129))); + refuses(root -> object(root, "executor").put("identity", "x".repeat(513))); + refuses(root -> source(root).put("epoch", "1".repeat(20))); + refusesWithMessage( + root -> { + ArrayNode entries = members(root); + ObjectNode noStateMember = ((ObjectNode) entries.get(1)).deepCopy(); + for (int index = 0; index < 1023; index++) { + ObjectNode member = noStateMember.deepCopy(); + member.put("workloadName", "z-member-%04d".formatted(index)); + entries.add(member); + } + assertThat(entries.size()).isEqualTo(1025); + }, + "Bounded installation array required"); + refusesWithMessage( + root -> { + ArrayNode sources = (ArrayNode) owner(root).get("catalogSources"); + ObjectNode template = source(root).deepCopy(); + for (int index = 1; index <= 64; index++) { + ObjectNode additional = template.deepCopy(); + additional.put("sourceId", "world-sql-" + index); + sources.add(additional); + } + assertThat(sources.size()).isEqualTo(65); + }, + "Bounded installation array required"); + refusesWithMessage( + root -> { + ArrayNode families = (ArrayNode) owner(root).get("families"); + ObjectNode template = family(root).deepCopy(); + for (int index = 1; index <= 256; index++) { + ObjectNode additional = template.deepCopy(); + additional.put("familyId", "world-state-" + index); + families.add(additional); + } + assertThat(families.size()).isEqualTo(257); + }, + "Bounded installation array required"); + byte[] tooDeepObjectRoot = bytes("{\"nested\":".repeat(65) + "null" + "}".repeat(65)); + IllegalArgumentException depthFailure = + Assertions.assertThrows( + IllegalArgumentException.class, + () -> WorldRuntimeInstallationArtifact.parse(tooDeepObjectRoot)); + assertThat(depthFailure) + .hasMessage("Invalid closed runtime installation artifact") + .hasCauseInstanceOf(tools.jackson.core.exc.StreamConstraintsException.class); + assertThat(depthFailure.getCause()) + .hasMessageContaining("Document nesting depth") + .hasMessageContaining("exceeds the maximum allowed (64"); + } + + private static void refuses(Consumer mutation) { + byte[] value = changed(mutation); + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldRuntimeInstallationArtifact.parse(value)); + } + + private static void refusesWithMessage(Consumer mutation, String message) { + byte[] value = changed(mutation); + assertThatIllegalArgumentException() + .isThrownBy(() -> WorldRuntimeInstallationArtifact.parse(value)) + .withMessage(message); + } + + private static byte[] changed(Consumer mutation) { + ObjectNode root = (ObjectNode) JSON.readTree(FIXTURE); + mutation.accept(root); + return JSON.writeValueAsBytes(root); + } + + private static byte[] bytes(String text) { + return text.getBytes(StandardCharsets.UTF_8); + } + + private static ObjectNode object(ObjectNode node, String field) { + return (ObjectNode) node.get(field); + } + + private static ArrayNode members(ObjectNode root) { + return (ArrayNode) root.get("members"); + } + + private static ObjectNode owner(ObjectNode root) { + return (ObjectNode) members(root).get(0); + } + + private static ObjectNode source(ObjectNode root) { + return (ObjectNode) owner(root).get("catalogSources").get(0); + } + + private static ObjectNode family(ObjectNode root) { + return (ObjectNode) owner(root).get("families").get(0); + } +} diff --git a/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryTest.java b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryTest.java new file mode 100644 index 0000000000..e016b0c983 --- /dev/null +++ b/services/world-management-service/src/test/java/unit/net/firedevops/firemud/worldmanagement/tenant/WorldRuntimeInstallationRegistryTest.java @@ -0,0 +1,28 @@ +package net.firedevops.firemud.worldmanagement.tenant; + +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; + +import java.util.UUID; +import org.jooq.DSLContext; +import org.junit.jupiter.api.Test; +import org.springframework.transaction.PlatformTransactionManager; + +class WorldRuntimeInstallationRegistryTest { + @Test + void unavailableDefaultSourceRefusesPreflightWithoutAnyDatabaseAccess() { + var dsl = mock(DSLContext.class); + var transactions = mock(PlatformTransactionManager.class); + var registry = new WorldRuntimeInstallationRegistry(dsl, transactions, "world", "firemud"); + + assertThatThrownBy( + () -> + registry.preflightLaunchOwners( + UUID.fromString("88888888-8888-4888-8888-888888888888"))) + .isInstanceOf(WorldRuntimeInstallationRegistry.RegistryUnavailableException.class) + .hasMessage("Protected current-installation source is unavailable"); + + verifyNoInteractions(dsl, transactions); + } +}