From 778d83c6413693c106587d701455b37c81f58259 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 14:34:16 +0000 Subject: [PATCH 01/37] docs(plans): register the repository interrogation corrective batch Five subsystem corrective addenda and nine implementation milestones, plus ADR-0007 (proposed) and the registry/roadmap registrations. Planning-only change: no source, script, manifest, or workflow is touched. plans/000-003 are unmodified. --- .../ADR-0007-resource-scoped-authorization.md | 165 +++++ ...004-shared-protocol-contract-corrective.md | 339 ++++++++++ ...er-request-validation-parity-corrective.md | 212 ++++++ ...perator-surface-truthfulness-corrective.md | 267 ++++++++ ...ocumentation-single-sourcing-corrective.md | 315 +++++++++ ...aded-isolation-observability-corrective.md | 266 ++++++++ ...ox-helper-environment-parity-corrective.md | 306 +++++++++ ...esource-scoped-authorization-corrective.md | 323 +++++++++ ...artifact-capture-fail-closed-corrective.md | 613 ++++++++++++++++++ ...-preview-and-store-ownership-corrective.md | 585 +++++++++++++++++ plans/registry.md | 54 +- .../control-plane-protocol-roadmap.md | 28 +- ...col-shared-contract-corrective-addendum.md | 301 +++++++++ ...-request-validation-corrective-addendum.md | 144 ++++ .../foundation-execution-core-roadmap.md | 28 +- ...erator-truthfulness-corrective-addendum.md | 213 ++++++ .../operations-distribution-roadmap.md | 54 +- ...lation-truthfulness-corrective-addendum.md | 226 +++++++ .../security-isolation-resource-roadmap.md | 80 ++- ...ransport-data-plane-corrective-addendum.md | 391 +++++++++++ .../workspace-artifact-transport-roadmap.md | 54 +- 21 files changed, 4954 insertions(+), 10 deletions(-) create mode 100644 plans/adrs/ADR-0007-resource-scoped-authorization.md create mode 100644 plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md create mode 100644 plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md create mode 100644 plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md create mode 100644 plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md create mode 100644 plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md create mode 100644 plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md create mode 100644 plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md create mode 100644 plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md create mode 100644 plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md create mode 100644 plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md create mode 100644 plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md create mode 100644 plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md create mode 100644 plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md create mode 100644 plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md diff --git a/plans/adrs/ADR-0007-resource-scoped-authorization.md b/plans/adrs/ADR-0007-resource-scoped-authorization.md new file mode 100644 index 0000000..4a72d20 --- /dev/null +++ b/plans/adrs/ADR-0007-resource-scoped-authorization.md @@ -0,0 +1,165 @@ +# ADR-0007: Resource-Scoped Authorization — Implement the Boundary or Remove the Hook + +Status: proposed — **not yet accepted**. This ADR records a decision that has not been made. No implementation work may be handed off on the strength of this document. + +Date: 2026-10-23 + +Decision owners: project maintainers + +Related authority: + +- `plans/adrs/ADR-0001-fixed-target-scheduler-free-execution.md` +- `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` +- `plans/adrs/README.md` +- `plans/000-long-term-specification.md` +- `plans/security/threat-model.md` +- `architecture/overview.md` — divergence #4 +- `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` — finding SI-3 +- `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` — the implementation plan, **blocked** on this ADR +- `plans/003-planning-process.md` §4 (dependency discipline) and §8 (architecture changes) + +## Context + +Eggwork's node service authorizes every request against a per-principal grant list. The grant list is operation-scoped: a principal holds `execute`, `observe`, `blob-read`, and so on. + +The server also contains a resource-aware authorization mechanism, and it is fully built. `crates/eggwork-server/src/lib.rs` defines: + +- `pub enum ResourceId { Execution, Blob, Workspace, Artifact }` — a typed resource identifier; +- `pub struct OperationRequest { operation, resource: Option }`; +- `fn resource_for_path(operation, path) -> Option`, which maps a request path segment to a typed resource; +- the public trait `Authorizer`, whose `fn authorize_request(&self, principal, request: &OperationRequest) -> bool` has a default implementation that delegates to the operation-level `fn authorize(&self, principal, operation) -> bool`; +- `fn authorize_resource(state, principal, operation, resource) -> bool`, the resource-scoped call helper, invoked at six handler sites — the blob-find-missing handler (`BlobRead`/`Blob`), the blob-prepare handler (`BlobWrite`/`Blob`), the workspace-create handler (`WorkspaceCreate`/`Workspace`), the workspace-derive handler (`WorkspaceCreate`/`Workspace`), and the execute handler twice (`Execute`/`Execution`, and `Execute`/`Workspace` when the request names one). The `dispatch` function additionally calls `authorize_request` with a `resource_for_path`-derived resource for every routed request. + +The production authorizer does not use any of it. `crates/eggwork-server/src/operations.rs` defines `pub struct GrantAuthorizer(HashMap>)` and implements **only** `authorize`. The trait's default `authorize_request` therefore applies on every production path, and the typed `ResourceId` is constructed, passed, and discarded. The only exerciser of the resource-scoped path is a unit test that asserts `resource_for_path` maps a path segment to a `ResourceId`. + +This is not a new observation. `architecture/overview.md` records it as divergence #4 — *"`GrantAuthorizer` implements only `Authorizer::authorize`, **not** the resource-aware `authorize_request` hook. Resource-scoped authorization is therefore inert on the real deployment path; ownership is enforced only in the store, by `principal_id` comparison."* — and `plans/security/threat-model.md` states the same as an open remaining boundary for the "Authenticated unauthorized principal" actor: *"Broad BlobRead capability permits any known digest unless resource-scoped policy is configured."* + +What is actually enforced today: + +- The store's `principal_id` fences, not the authorizer. `ExecutionStore::load_snapshot_for_principal` selects by `(execution_id, principal_id)`; the artifact store's `load` selects by `(artifact_id, principal_id)` and its list by `(execution_id, generation, principal_id)`; the workspace store's `lookup_manifest` selects by `(principal_id, manifest_digest)` and `WorkspaceStore::materialize` rejects a conflicting materialization whose `principal_id` differs. +- Blob storage has **no** owner fence. It is content-addressed and shared, so the same digest is the same bytes for every principal. A principal holding `BlobRead` may read any digest the node knows. + +The decision this ADR must make is therefore: **does the node gain a per-resource authorization boundary, or does it lose the appearance of one?** + +The decision is durable and consequential in both directions. Implementing the boundary changes what a per-principal grant means and adds a configuration surface. Removing the hook changes the public API of a published crate and removes a mechanism that a future implementer, reviewer, or integrator could reasonably read as available. Leaving it as it is leaves the node presenting a capability it does not have. + +## Decision drivers + +- **Truthfulness of the advertised surface.** A mechanism that is present but inert must not be represented as available. `AGENTS.md`'s hard invariant "Isolation claims are earned" states the principle for isolation; the same principle applies to authorization. +- **The boundary that is documented.** `plans/security/threat-model.md` is a standing document that states what the node enforces and what it does not. It currently names an open boundary. Leaving that boundary open while a mechanism for closing it sits inert in the tree is the situation this ADR exists to end. +- **Cost proportionality.** The mechanism is already built and publicly exported. Removing it is cheap; implementing it is not. +- **Compatibility.** `ResourceId`, `OperationRequest`, and the `Authorizer` trait are `pub` in `eggwork-server`, a published workspace crate. Removal is a breaking API change. +- **No new authority.** Eggwork must not become a policy engine, a role system, or a multi-tenant IAM product. The decision must stay inside "per-principal grants, optionally narrowed to named resources". +- **Blobs are special.** Content-addressed shared storage has no owner to fence against, so any resource-scoped boundary for blobs must be an explicit identifier list, not an ownership comparison. The decision must be explicit about this rather than discovering it during implementation. +- **Existing deployments must keep working.** A principal with no resource scopes must keep receiving exactly the operation-level decision it receives today. + +## Alternatives + +### A. Implement resource-scoped grants + +`GrantAuthorizer` implements `authorize_request` against a grant configuration that names resources, and the typed `ResourceId` decides. + +- The grant configuration gains an optional, additive resource-scope list naming the operation, the resource kind, and the resource identifier. A grant without scopes keeps today's operation-level meaning. +- For `Execution`, `Workspace`, and `Artifact`, the store's existing `principal_id` fence remains authoritative for ownership; the authorizer may narrow, never widen. +- For `Blob`, the scope is an explicit digest list, because there is no owner to compare against. +- The scope applies to the operations the existing call sites already name — `BlobRead`, `BlobWrite`, `WorkspaceCreate`, `Execute` — and the ADR must also settle whether it applies to the operations `resource_for_path` already resolves for `dispatch`: `Observe`, `Cancel`, `Renew`, `Events`, `ArtifactRead`. + +**Consequences.** The node gains a real per-resource boundary and the threat model's open boundary can be closed with evidence rather than with a caveat. The cost is a new configuration surface, new validation, new tests, and a per-request decision that consults a set. The blob boundary becomes real rather than notional. The `architecture/overview.md` divergences table gains a closed row. + +**Compatibility.** Additive to the configuration surface and to the public API. The one sharp edge is `#[serde(deny_unknown_fields)]` on `ClientGrant`: an older node reading a newer configuration containing a resource scope will refuse to start. That refusal is correct — a node must not silently ignore a scope it does not understand — and must be documented as such. + +### B. Remove the hook and the plumbing + +Delete the resource-scoped authorization surface so the mechanism stops looking available. + +- Delete `pub enum ResourceId` and the `resource` field of `pub struct OperationRequest`. +- Delete `fn resource_for_path` and `fn authorize_resource`. +- Remove the `authorize_request` method from the public `Authorizer` trait and its default implementation. +- Collapse the six resource-scoped handler call sites and the `dispatch`-level call to the operation-level authorizer, and remove the unit test that exercises `resource_for_path`. + +**Consequences.** The node stops advertising a boundary it does not enforce, and the divergence-table row can be closed honestly: the boundary that exists is the store's `principal_id` fence, and the blob boundary is exactly what the threat model says it is. The cost is that a per-resource boundary is not available until a future decision builds one, and that a future implementer starts from a smaller tree. The blob boundary remains open and must be stated plainly rather than implied closed. + +**Compatibility.** A breaking change to the public API of a published crate. Every in-tree consumer must be enumerated and migrated; the out-of-tree position must be stated honestly rather than assumed; the release version and notes must reflect the removal. + +### C. Defer, and mark the mechanism as unavailable + +Keep the hook in the tree but make its unavailability discoverable to a caller — for example, through an explicit protocol marker, a capability-advertisement string, or an operator-visible statement that resource-scoped authorization is not in force. + +**Consequences.** The smallest change, and it preserves the option to implement later without re-plumbing. But it leaves a public API that still *looks* like a resource-scoped hook, and the marker is only truthful if it is discoverable by the party who would otherwise rely on it. If the marker is a source comment or a documentation note, this alternative collapses into the status quo and does not satisfy the truthfulness driver. + +**Compatibility.** Additive. + +This alternative is viable **only** if the ADR states concretely how a caller learns that resource-scoped authorization is not in force, and only if the retained hook cannot be mistaken for a working one by a reader of the code. The ADR must record that requirement explicitly if this option is selected. + +## Consequences of the decision as a whole + +Whichever option is selected: + +1. The `architecture/overview.md` divergences table must be updated to the decided disposition. Divergence #4 is either closed with a statement of what now enforces the boundary, or rewritten to describe the mechanism actually in force. +2. `plans/security/threat-model.md`'s remaining-boundary column for the "Authenticated unauthorized principal" row must be updated to state the boundary as it is after the change. +3. `architecture/server-node.md` and `architecture/operations-cli.md` must describe the authorization decision path as it is. +4. Authorization must continue to precede resource resolution, and a denied caller must continue to be unable to distinguish an existing resource from an absent one. +5. The store's existing `principal_id` fences must not be weakened. +6. The configuration loader must continue to fail closed on a malformed or unknown field. + +Option A additionally narrows what a grant means; Option B additionally removes a public API; Option C additionally commits the project to making an unavailability discoverable. + +## Compatibility implications + +- **Option A** is additive at the wire and API level. A grant without scopes behaves identically to today. The `deny_unknown_fields` interaction with an older node reading a newer configuration is a deliberate refusal and must be documented. +- **Option B** is a breaking public-API removal in `eggwork-server`. The removal must be reflected in the release version and notes and must not be bundled silently into a release that claims to be a qualification-only candidate. +- **Option C** is additive, but it commits the project to an explicit unavailability marker, whose shape is part of the decision and must be specified here. +- No option may change the wire representation of a request or response type without a decision recorded in this ADR and coordination with the control-plane shared-protocol contract corrective, which owns `API_SCHEMA_VERSION`. + +## Verification expectations + +Common to all options: + +- the divergences-table row and the threat-model row match the code; +- the existing authorization test matrix — the operation-level grant matrix, the "request payload cannot supply authoritative principal" test, and the routing test — is green and unchanged; +- a denied caller still cannot distinguish an existing resource from an absent one, and the refusal still occurs at the same point in the dispatch path; +- the store's `principal_id` fences are unchanged and still refuse a foreign-owned resource; +- the configuration loader still refuses a malformed or unknown field, and the node still refuses to start; +- the full pre-submit gate is green on the reviewed head. + +Option A additionally: + +- a resource scope measurably narrows an operation grant — a test that fails if the scope is ignored, so that the hook cannot land inert a second time; +- the owner fence holds for `Execution`, `Workspace`, and `Artifact`, proven by a test that grants a scope and then attempts to reach a foreign-owned resource; +- a blob scope is an explicit digest list and does not permit a digest outside it; +- a principal with no scopes receives exactly the operation-level decision; +- every configuration error class — unknown operation, unknown resource kind, malformed identifier, a scope for an unheld operation, a duplicate scope, an over-cap count — refuses the configuration at load time. + +Option B additionally: + +- an assertion that `ResourceId`, `OperationRequest.resource`, `resource_for_path`, `authorize_resource`, the `authorize_request` trait method, and the unit test are gone, and a test that fails if any of them is reintroduced; +- an assertion that no handler-level call constructs a typed resource; +- the full behaviour of the authorization path is unchanged. + +Option C additionally: + +- a test proving that the unavailability marker is produced on the path where a caller would rely on resource scoping, and that it is discoverable without inspecting the node's source. + +## Architecture review + +**Yes — this decision class requires architecture review**, and this ADR is that review's vehicle. + +`plans/003-planning-process.md` §8 requires an ADR or a canonical amendment when implementation discovers that a durable invariant or ownership boundary must change. This decision changes a public API shape (Option B), adds a configuration and policy surface (Option A), or commits the project to a durable "not available" statement (Option C). Each of those constrains later implementation beyond this milestone and is therefore the kind of decision an ADR exists to record. + +The §8 examples of changes requiring architecture review include *"changing required isolation into silent best-effort"* — the same class of concern as this one. A required guarantee that is silently absent is the pattern both branches are designed to eliminate: Option A makes the guarantee real, Option B makes its absence explicit, and Option C makes its absence discoverable. All three are legitimate; the review's job is to pick one and write it down, not to leave three plausible. + +The review must also confirm that the chosen option does not move Eggwork toward owning policy, roles, or multi-tenant IAM, and that it does not weaken the store's ownership fences. + +## Decision + +**Not yet made.** This ADR is `proposed`. + +When the decision is made, this section is completed with the selected option, the decision date, and the constraints that apply to it, and the `Status:` line above is changed from `proposed` to `accepted`. Until then: + +- `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` remains `blocked`, with this ADR named as its concrete blocker; +- per `plans/003-planning-process.md` §4, that plan must not be handed off as ready merely because adjacent implementation exists; +- the implementation plan's Branch A (§5) and Branch B (§6) are written to be executable without re-deriving the design, so that whichever option is selected, the implementation is mechanical. + +## Supersession + +None. This ADR augments, and does not replace, ADR-0001 or ADR-0005. If a later decision changes the outcome, this ADR is superseded by a new ADR rather than rewritten. diff --git a/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md b/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md new file mode 100644 index 0000000..bd7eccf --- /dev/null +++ b/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md @@ -0,0 +1,339 @@ +# Control Plane M004 — Shared Protocol Contract Ownership + +Status: proposed + +Class: invariant + +Source roadmap: + +- `plans/subsystems/control-plane-protocol-roadmap.md` + +Corrective authority: + +- `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` + +Canonical/ADR references: + +- `plans/000-long-term-specification.md` +- `plans/001-terminology-and-domain-model.md` +- `plans/adrs/ADR-0001-fixed-target-scheduler-free-execution.md` +- `plans/adrs/ADR-0002-eggstack-transport-and-mtls.md` +- `plans/adrs/ADR-0003-execution-idempotency-leases-and-fencing.md` +- `plans/003-planning-process.md` + +Historical predecessor closures (immutable; this plan does not rewrite them): + +- `plans/closure/control-plane-protocol/001-status.md` +- `plans/closure/control-plane-protocol/002-status.md` +- `plans/closure/control-plane-protocol/002-lease-expiry-race-correction.md` +- `plans/closure/control-plane-protocol/003-status.md` + +Closure record: `plans/closure/control-plane-protocol/004-status.md` + +## 1. Objective + +Make the client, the server, and the runner agree on three protocol contract facts **by construction rather than by convention**, so that a future change to any of them is a compile-time or test-detectable event. + +The three facts: + +1. **CP-1** — the control-plane API schema version. +2. **CP-2** — the capability feature names and the sandbox profile name. +3. **CP-3** — the terminal/non-terminal classification of `ExecutionState`. + +For each, exactly one crate owns the fact; every producer and every consumer refers to it through that owner. + +This is a refactor of contract literals into owned constants. It changes no wire value, no wire field, no runtime behavior, and no authorization, lease, generation, fencing, or digest semantics. It removes no capability and adds none. + +## 2. Baseline and problem statement + +At the reviewed baseline: + +**CP-1.** `crates/eggwork-client/src/lib.rs` declares a private `const API_SCHEMA_VERSION: u16 = 1;`; `crates/eggwork-server/src/lib.rs` declares its own private `const API_SCHEMA_VERSION: u16 = 1;`. The client stamps its value into the execute, control, workspace-create, and workspace-derive request bodies. The server compares the received value against its own and rejects a mismatch with HTTP 426 `protocol_version` in the workspace-create, workspace-derive, execute, execute-spec, and cancel/renew paths. Nothing links the two declarations. `crates/eggwork-core/src/lib.rs` already declares `pub const NODE_TELEMETRY_SCHEMA_VERSION: u16 = 1;`, consumed by the client's telemetry reader, the server's telemetry projection, and core's own `NodeTelemetry::validate` — the precedent for the shape CP-1 needs. + +**CP-2.** `crates/eggwork-runner/src/lib.rs`, in `TrustedLandlockSetup::execution_capabilities`, pushes the literal `"isolation.landlock.workspace-rw.v1"` — the same file already declares `pub const LANDLOCK_WORKSPACE_RW_CAPABILITY` with that exact value and does not use it there — and carries `"resources.cgroups-v2.memory"`, `"resources.cgroups-v2.cpu"`, and `"resources.cgroups-v2.pids"` as literals in its probe table. `crates/eggwork-server/src/lib.rs`, in `check_resources_supported`, matches the three cgroup names as literals; its `check_isolation_supported` already imports `eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY`. The server produces `"exec.argv.v1"` in `static_capability_features`; `crates/eggwork-client/src/lib.rs` hardcodes `"exec.argv.v1"` in `NodeClient::ensure_protocol_compatible`. The `"workspace_rw"` profile name is a literal at three sites in the runner and one production site in `crates/eggwork-sandbox-helper/src/main.rs`. + +**CP-3.** `crates/eggwork-core/src/lib.rs` defines `ExecutionState` as a flat nine-variant enum and owns no terminal concept: no `is_terminal` helper, no terminal grouping, no terminal list. `architecture/core-domain.md` records this under **States**. The server enumerates the classification nine times: `fn state_name` and `fn is_terminal_name` in `crates/eggwork-server/src/store.rs`, an inline `matches!` in `ExecutionStore::reserve` that does not call the helper in its own file, `fn is_terminal` in `crates/eggwork-server/src/lib.rs`, an inline `Succeeded | Failed` artifact-capture subset, a wildcard-terminated terminal-to-metric-name match, a non-terminal `matches!` in `crates/eggwork-server/src/operations.rs`, the parallel SQL literal list in `fn count_active_executions`, and the second enum-to-string map `fn state_label`. + +**Why this is worth a milestone.** None of these is a live bug: both sides of every pair currently agree, by value. The defect is structural. A future rename or bump on the producing side desynchronizes the consuming side silently, and neither the compiler nor the test suite objects. The corrective converts three classes of silent-drift risk into compile-time or test-detectable events. + +**Two review-note corrections the implementer must know.** Two details in the interrogation notes that produced this plan did not survive re-reading against the code, and the plan follows the code: + +- The server's `check_isolation_supported` **already** imports `eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY`. The Landlock capability's consumer side is not duplicated; only the runner's own push site is. Do not "fix" a duplication that does not exist. +- The `"workspace_rw"` profile name appears **once** in the helper's production code (`crates/eggwork-sandbox-helper/src/main.rs`), not "several places". The runner has seven occurrences including doc comments; the helper's remaining six are in its integration test. + +## 3. Scope + +**In scope.** + +- CP-1: move the API schema version into `eggwork-core`; import it in the client and the server. +- CP-2: export the runner's capability feature names and sandbox profile name as public constants; use them at their producing sites; import them in the server; give `exec.argv.v1` a single owner reachable by both endpoints; pin the helper's `workspace_rw` literal with a test. +- CP-3: give the terminal/non-terminal classification one owner in `eggwork-core`; derive the server's existing helpers, its inline matches, its SQL literal list, and its metric mapping from it. + +**Explicitly out of scope.** + +- Changing any protocol wire field, field name, or value. +- Changing any capability feature-string **value** or any capability semantics. Those are frozen by `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md` §3 and are preserved byte-for-byte. Changing a feature value is a compatibility break requiring an ADR, not this plan. +- Changing authorization, authentication, lease, generation, fencing, digest, or idempotency behavior. +- Any change to the runner's or the server's runtime behavior beyond replacing a literal with the constant it already equals. +- Any new crate dependency edge. +- Adding, removing, or renaming a capability feature. +- Changing the artifact-capture eligibility rule (still exactly `Succeeded` and `Failed`). +- Changing the operator-facing state labels in `eggworkd status`. +- Changing the `state` column values or the SQL that reads them, beyond deriving the literal list from the shared spelling. +- The architecture-record drift noted in §2 (divergence #20's stale text) — recorded, not owned here. + +## 4. Invariants and non-goals + +**Invariants this plan must preserve.** + +1. One request targets one explicitly selected node. No node selection, queue, priority, fairness, DAG, or semantic retry is introduced. +2. Unauthenticated or unauthorized requests cause zero execution side effect. +3. Transport identity stays authoritative; a payload can never supply a principal. +4. Same accepted execution identity and digest cannot spawn twice; stale generations cannot control newer work. +5. Connection loss stays distinct from lease expiry. +6. Event history stays bounded; sequence gaps stay explicit. +7. Restart never blindly repeats uncertain work. +8. `eggwork-core` keeps no internal dependencies; `eggwork-sandbox-helper` keeps no workspace-crate dependency. +9. No authentication, lease, generation, fencing, or digest bound is weakened. +10. No wire representation changes — `ExecutionState` keeps its derived `Serialize`/`Deserialize` with no rename attribute, so it stays externally tagged PascalCase. + +**Non-goals.** This plan is not a place to "while we are here" refactor, to rename anything for style, to consolidate the server's two enum-to-string maps into one, or to change a function's signature for tidiness. Every edit must be traceable to CP-1, CP-2, or CP-3. + +## 5. Required production changes + +### 5.1 CP-1 — one API schema version, owned by `eggwork-core` + +1. In `crates/eggwork-core/src/lib.rs`, add `pub const API_SCHEMA_VERSION: u16 = 1;` next to `NODE_TELEMETRY_SCHEMA_VERSION`, with a doc comment stating that it is the control-plane request/response schema version, that every versioned body producer and consumer refers to this constant, and that the value is frozen for schema version 1. +2. In `crates/eggwork-client/src/lib.rs`, delete the private `const API_SCHEMA_VERSION: u16 = 1;` and import `eggwork_core::API_SCHEMA_VERSION`. Every existing use site keeps its behavior. +3. In `crates/eggwork-server/src/lib.rs`, delete the private `const API_SCHEMA_VERSION: u16 = 1;` and import `eggwork_core::API_SCHEMA_VERSION`. Every existing use site keeps its behavior, including the 426 `protocol_version` rejections and the values stamped into responses and into `ExecutionSnapshot.schema_version`. +4. Replace any remaining literal schema-version `1` used to stand for this fact — including the `schema_version: 1` in the `ExecutionSnapshot` fixture in `crates/eggwork-server/src/operations.rs`'s tests — with the shared constant. +5. Do not add a `validate()` to any request type and do not change when the server checks the version. The check sites stay exactly where they are. + +### 5.2 CP-2 — capability feature names and the sandbox profile name + +**Runner-produced names (owner: `eggwork-runner`).** + +6. In `crates/eggwork-runner/src/lib.rs`, export `pub` constants for the three cgroup-v2 resource feature names — for example `CGROUPS_V2_MEMORY_CAPABILITY`, `CGROUPS_V2_CPU_CAPABILITY`, `CGROUPS_V2_PIDS_CAPABILITY` — with doc comments stating that each is the frozen public feature name for that dimension and that the value must not change without an ADR. The exact names are the implementer's choice; the requirement is that they are `pub`, that they are in the runner, and that they are used. +7. In `TrustedLandlockSetup::execution_capabilities`, replace the pushed literal `"isolation.landlock.workspace-rw.v1"` with `LANDLOCK_WORKSPACE_RW_CAPABILITY`, and replace the three literals in the probe table with the new constants. +8. In `crates/eggwork-server/src/lib.rs`, in `check_resources_supported`, replace the three literals with imports of the runner's constants. `check_isolation_supported` needs no change — it already imports `eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY`. + +**The `exec.argv.v1` name (owner: `eggwork-core`).** + +9. In `crates/eggwork-core/src/lib.rs`, add `pub const EXEC_ARGV_CAPABILITY: &str = "exec.argv.v1";` with a doc comment stating that it is the feature name for argv-based execution, that the node advertises it in `NodeCapabilities.features`, and that a client requires it before submitting an execution. +10. In `crates/eggwork-server/src/lib.rs`, `static_capability_features` uses `eggwork_core::EXEC_ARGV_CAPABILITY` in place of the `"exec.argv.v1"` literal. +11. In `crates/eggwork-client/src/lib.rs`, `NodeClient::ensure_protocol_compatible` compares against `eggwork_core::EXEC_ARGV_CAPABILITY` in place of the literal. + +**Why `eggwork-core` and not the server.** The server produces the name and the client consumes it, and the client cannot depend on the server. `eggwork-core` is the crate both already depend on, and it already owns the `NodeCapabilities` type whose `features` field carries the name. The owner is the lowest crate every participant depends on. + +**The `workspace_rw` profile name (owner: `eggwork-runner`; helper pinned by test).** + +12. In `crates/eggwork-runner/src/lib.rs`, export a `pub` constant for the sandbox profile name — for example `WORKSPACE_RW_PROFILE: &str = "workspace_rw"` — with a doc comment stating that it is the only supported `SandboxRequest` profile and that the value must not change without an ADR. +13. Use it at all three runner sites: the profile comparison in `TrustedLandlockSetup::prepare`, the profile construction in `RunnerRequest::from_spec`, and the profile comparison in `SandboxChannel::new`. +14. `crates/eggwork-sandbox-helper/src/main.rs` is **not modified**. The helper's `LaunchSpec` validation keeps its `"workspace_rw"` literal, because the helper has no workspace-crate dependency and adding one would break the standalone-binary rule. +15. The helper's literal is pinned by a test instead: `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` already dev-depends on `eggwork-runner`, so it asserts that the profile the runner produces is accepted by the helper, and that a profile which differs is refused before the target spawns. See §6.4. + +**What must not change.** + +16. Every capability feature-name value stays byte-for-byte identical. `network.unrestricted.v1`, `events.live.v1`, `auth.mtls.v1`, `blob.sha256.v1`, `blob.stream.v1`, `workspace.manifest.v1`, `workspace.materialize.v1`, `workspace.derive.v1`, `artifact.declared.v1`, `artifact.stream.v1`, and `artifact.retention.v1` are not in scope; they are not duplicated across crates today and must not be moved merely for symmetry. + +### 5.3 CP-3 — one terminal-state classification, owned by `eggwork-core` + +17. In `crates/eggwork-core/src/lib.rs`, add to `ExecutionState`: + - a terminal predicate (`is_terminal`) and its complement (`is_non_terminal`); + - the canonical wire spelling of a state (for example `wire_name`) — the PascalCase string the derived `Serialize` already produces; + - a way to enumerate every variant (for example a `pub const ALL_EXECUTION_STATES: [ExecutionState; N]` iterated by reference, or a `pub fn all()` accessor), so a property test can range over the whole enum instead of over another hand-written list. + +18. `is_terminal` **must** be written as a `match` over all nine variants with **no wildcard arm**, and `is_non_terminal` as its complement. The same exhaustiveness rule applies to the wire-spelling function. This is what makes adding a tenth variant a compile error in core rather than a silent behavior change downstream. A `matches!` with a wildcard, or an `is_non_terminal` written as its own independent list, does not satisfy this requirement. + +19. In `crates/eggwork-server/src/store.rs`: + - remove `fn state_name`; use the core-owned wire spelling at its two call sites (the `state` column write in `ExecutionStore::reserve` and in `ExecutionStore::commit_event`); + - remove `fn is_terminal_name`; use the core-owned classification at its two call sites; + - replace the inline `matches!` over the five state-name literals in the generation-reservation path in `ExecutionStore::reserve` with the shared classification, so the path stops duplicating the set that `is_terminal_name` already expressed. + +20. In `crates/eggwork-server/src/lib.rs`: + - remove `fn is_terminal`; use the core-owned predicate at all its call sites; + - give the artifact-capture eligibility subset (`ExecutionState::Succeeded | ExecutionState::Failed`) a name, and keep it exactly that subset. It is **not** the terminal set and must not be folded into it, nor the terminal set folded into it; + - replace the wildcard-terminated terminal-to-metric-name match with a derivation from the shared terminal classification, so that a newly added terminal variant cannot silently lose its metric name. + +21. In `crates/eggwork-server/src/operations.rs`: + - replace the non-terminal `matches!` in the active-execution count with the shared classification; + - replace the hard-coded SQL literal list in `fn count_active_executions` with a list derived from the shared non-terminal spelling, keeping the same four state names and the same query semantics. If the derived list is assembled at runtime, the query must remain parameterized — no string-concatenated SQL; + - update the comment above `fn count_active_executions` that explains the PascalCase-versus-snake_case distinction, because after this change the two lists are derived from one spelling rather than kept in sync by hand; + - `fn state_label` stays a display projection. It may remain server-local or move to core, but the decision must be recorded in the closure record, and it must be total over the enum with no wildcard arm, and it must keep its current snake_case output exactly. + +22. Do not change the `state` column's stored values, the column's schema, or the JSON stored in the `executions` table. Do not change the store's SQL schema, the journal's event retention, or the recovery classification. + +23. Do not add a terminal-state concept to the client as a private copy. The client does not classify states today; if it ever needs to, it must ask `eggwork-core`. + +## 6. Required tests + +Tests are required. "It compiles" is not acceptance (§8). + +### 6.1 CP-1 + +- **Shared-value pin.** A test in `crates/eggwork-core` asserts `API_SCHEMA_VERSION` equals the frozen value for schema version 1, so that a careless edit to the shared constant is a test failure rather than a silent protocol break. +- **Client-side wire pin.** A test asserts that the client's serialized request bodies carry `eggwork_core::API_SCHEMA_VERSION` in their `schema_version` field. The client currently has no `tests/` directory; either add `crates/eggwork-client/tests/` with a focused serialization test, or place the assertion in the existing client unit-test module. The implementer picks the location and records it. +- **Server-side rejection pin.** The server already has a test that builds an `ExecuteRequest` with `schema_version: API_SCHEMA_VERSION + 1` and asserts a 426 `protocol_version`. Keep it, and make sure it names the shared constant so that the rejection path is proven to use the core-owned value rather than a private copy. +- **Cross-crate agreement.** `crates/eggwork-server/Cargo.toml` already dev-depends on `eggwork-client` (with the `eggress-route` feature). Use that to write a test that observes the actual client-built request body's schema version and asserts it equals the value the server accepts — i.e. that a client request is not rejected as `protocol_version`. This is the test that would have caught CP-1. + +### 6.2 CP-2 + +- **Runner advertisement uses the constants.** A test in `crates/eggwork-runner` asserts `TrustedLandlockSetup::execution_capabilities` output is checked against the exported constants rather than against literals — for example, that when the helper is trusted and the kernel supports the ruleset, the advertised set contains `LANDLOCK_WORKSPACE_RW_CAPABILITY`; and that the probe-table feature names are exactly the exported constants. +- **Value freeze.** The existing `capability_feature_string_is_frozen_for_workspace_rw_profile` test stays and keeps asserting the literal value. Add equivalent freeze assertions for the three cgroup constants and for `EXEC_ARGV_CAPABILITY`, so a value change fails a test even if someone edits the constant and its consumer together. +- **Server consumer imports the producer.** A test in `crates/eggwork-server` asserts `check_resources_supported` recognizes exactly the runner's exported constants — in particular that a required memory/cpu/pids dimension is admitted when the node advertises the runner's constant, and refused with `capability_mismatch` when the advertised name differs by even one character. That refusal case is the CP-2 regression test: it fails if the server and runner drift apart. +- **Client consumer imports the owner.** A test asserts `NodeClient::ensure_protocol_compatible` accepts a node advertising `eggwork_core::EXEC_ARGV_CAPABILITY` and returns the typed unsupported-capability error for a node whose feature list differs. +- **Helper profile pin.** In `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`: the runner-produced profile is accepted by the helper, and a profile that differs is refused before the target spawns. This is the test that pins the helper's unavoidable literal to the runner's constant. + +### 6.3 CP-3 + +- **Totality and disjointness property test.** A test ranges over every `ExecutionState` variant and asserts each one is classified into exactly one of the terminal and non-terminal sets — never both, never neither. It also asserts the terminal set has exactly five members and the non-terminal set exactly four, so a mis-edited classification (`Failed` flipped to non-terminal, say) fails even though the sets still partition. +- **Adding a variant breaks it.** The property test must be written so that adding a variant to `ExecutionState` breaks the build or the test. The primary mechanism is the exhaustive `match` with no wildcard (compile error in core). The test must not be satisfiable by a hand-written list of nine variants that a tenth variant simply joins unnoticed. +- **Wire spelling equals serde output.** A test asserts, for every variant, that the canonical wire spelling equals the enum's serde representation — for example that serializing the variant yields the same string. This is what keeps `state_name` and the `state` column honest against the derived `Serialize`. +- **Store column values unchanged.** A test asserts the `state` column still receives the same PascalCase strings it received before (for example that a `TimedOut` snapshot persists as `TimedOut`), so the storage format did not move. +- **SQL list still selects the non-terminal states.** A test asserts the derived literal list in `fn count_active_executions` selects exactly `Accepted`, `Preparing`, `Running`, and `Cancelling` — no more, no fewer — so the drain/quiescence count keeps its meaning. +- **Capture eligibility preserved.** A test asserts the artifact-capture eligibility predicate accepts exactly `Succeeded` and `Failed`, and rejects `Cancelled`, `TimedOut`, `Interrupted`, and the non-terminal states. It must also assert the subset is a strict subset of the terminal set, so nobody quietly widens it to all five. +- **Metric mapping total.** A test asserts every terminal state maps to a metric name, and that a non-terminal state maps to none. +- **Display labels unchanged.** A test asserts `fn state_label` produces exactly its current snake_case strings for all nine variants. + +### 6.4 Test placement constraints + +- The helper test in §6.2 lives in `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`, which already dev-depends on `eggwork-runner`. Do not add a workspace-crate dependency to the helper's `[dependencies]`. +- The cross-crate agreement test in §6.1 lives in the server crate, which already dev-depends on `eggwork-client`. Do not make `eggwork-client` a non-dev dependency of the server. +- No test may create a child process outside the repository's existing controlled-fixture patterns, and no test may use a live network. + +## 7. Failure, cancellation, restart, and contention semantics + +This plan changes no runtime behavior, so it introduces no new failure, cancellation, restart, or contention semantics. The implementing agent must confirm the following rather than assume it: + +- **Cancellation.** The cancel/renew path compares a received schema version against the shared constant. Its behavior on a mismatch — the 426 `protocol_version` rejection — is unchanged; only the constant's provenance changes. +- **Restart and recovery.** `ExecutionStore::recover` classifies uncertain work as `Interrupted` using the terminal classification. After this change it uses the shared classification. The recovery outcome for a given journal must be identical before and after. The existing recovery test in `crates/eggwork-server/src/store.rs` (`recovery_marks_uncertain_work_interrupted_and_never_replays_it`) must stay green and must still assert the same outcome. +- **Lease and generation fencing.** `ExecutionStore::reserve`'s generation-reservation path contains the inline `matches!` that this plan replaces. Its behavior must not change: a stale generation is still refused with the same result, and a generation may only advance from a terminal state. The existing reserve tests in `crates/eggwork-server/src/store.rs` must stay green unmodified. +- **Contention.** The `count_active_executions` query is on the drain/quiescence path and is polled on a timer. Changing it from a hard-coded literal list to a derived one must not change its result set, its query plan, or its behavior under concurrent execution. Because the query's `IN` list becomes runtime-assembled, it **must** stay parameterized — string-concatenated SQL is not acceptable and would introduce an injection-shaped defect into an operator path. +- **Failure.** A failure of the new shared-constant mechanism must not be silently tolerated. A compilation error is the intended outcome when the enum and the classification diverge; it is not a defect to work around. + +## 8. Compatibility and migration + +**Wire compatibility.** Unchanged. The schema version stays `1`. Every capability feature name keeps its exact bytes. `ExecutionState` keeps its derived `Serialize`/`Deserialize` with no rename attribute. The server's `state` column keeps the same PascalCase strings. `eggworkd status` keeps its current snake_case labels. + +**Behavioral compatibility.** Unchanged. Every literal this plan replaces is replaced by a constant whose value is identical to the literal it replaces. No execution, admission, authorization, lease, generation, event, artifact, or retention path changes behavior on any platform. + +**Rust API compatibility.** The plan adds `pub` constants and `pub` predicates. It removes no `pub` item: the two `API_SCHEMA_VERSION` constants it removes are crate-private. `eggwork-core` gains public items, which is additive. + +**Migration.** None. No stored-format migration, no rollout step, no coordination with deployed clients or nodes, because no observable value changes. + +**What this plan does not buy.** Sharing a constant prevents *creating* skew inside one build; it cannot remove skew between two already-deployed binaries. A future schema-version bump still needs its own compatibility story. Do not read this plan as pre-authorizing one. + +**Recorded, not owned.** `architecture/overview.md` divergence #20 states that the client's `decode_json` reads a response body with no size cap. At the reviewed baseline the client bounds accumulated bodies at the transport builder — `NodeClient::new` and `NodeClient::with_eggress` both set `max_decoded_body_size(MAX_BUFFERED_BODY_BYTES)` on the Eggfetch client builder — so that text no longer matches the code. This plan records the observation and leaves #20's disposition to the owner of the architecture record. + +## 9. Documentation updates + +Required in the same pass as the code change: + +1. **`architecture/core-domain.md`** — the **States** paragraph currently states that there is no `is_terminal()` helper and no terminal-state grouping in core. After M004 that is false. Rewrite it to describe the new ownership, and replace its line-number citations with symbol references. Do not touch its other findings. +2. **`architecture/overview.md`** — divergence #12 says the terminal/non-terminal sets "are spelled out in four places". Reconcile it with the implemented reality and its new count, and note that the classification is now owned by `eggwork-core`. Preserve the divergence's original substance; this is an update to a recorded observation, not a deletion. +3. **`architecture/client-transport.md`** — it documents that the client sends `schema_version: API_SCHEMA_VERSION` and that this matches the server's own constant. After M004 both refer to one core-owned constant; update that sentence and replace its line-number citation with a symbol reference. +4. **`architecture/server-node.md`** — it names `eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY` as the constant the isolation check requires. Verify the sentence still matches the code after M004 and update if the wording drifted; replace the surrounding line-number citations with symbol references. +5. **`architecture/storage-journal.md`** — it records that `ExecutionSnapshot.schema_version` is set to `API_SCHEMA_VERSION` at construction and that the `state` column's spellings have a hand-maintained relationship. Update to state that the value and the spelling are now core-owned and derived. +6. **`architecture/runner-execution.md`** — it describes the runner's capability advertisement and the `LANDLOCK_WORKSPACE_RW_CAPABILITY` constant. Update the description of where the feature names now come from, and replace the stale line-number citations with symbol references. +7. **No `docs/` change.** This corrective is invisible to an operator and to a user: no verb, flag, config field, endpoint, wire value, or observable behavior changes. Do not add an operator-facing note about it. + +## 10. Required verification commands + +The repository's pre-submit gate, exactly: + +```text +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +`--locked` is load-bearing on `clippy` and `test`: a version bump that skips `Cargo.lock` passes both and then fails every release build. + +Additional focused runs the implementer must perform and record, beyond the whole-workspace commands: + +```text +cargo test --locked -p eggwork-core --all-targets +cargo test --locked -p eggwork-client --all-targets +cargo test --locked -p eggwork-runner --all-targets +cargo test --locked -p eggwork-server --all-targets +cargo test --locked -p eggwork-sandbox-helper --all-targets +``` + +`cargo test --locked -p eggwork-client --features eggress-route --all-targets` is additionally required, because the server's dev-dependency on the client enables that feature and the cross-crate agreement test in §6.1 must compile and run under it. + +**Platform and feature matrix actually exercised must be recorded** — not claimed. State plainly which host the run happened on and which platform-specific paths were skipped. The runner's Linux-only Landlock and cgroup paths, the Windows Job Object path, and the macOS fail-closed path each have their own conditions; record which ones the local run actually covered and which it did not. Do not claim a platform is qualified because its code compiles. + +## 11. Acceptance criteria + +Each criterion is observable and checkable. + +1. `API_SCHEMA_VERSION` is declared exactly once in the workspace, publicly, in `crates/eggwork-core/src/lib.rs`; neither `crates/eggwork-client/src/lib.rs` nor `crates/eggwork-server/src/lib.rs` declares a local schema-version constant. +2. The client's request bodies and the server's acceptance and rejection paths both resolve to `eggwork_core::API_SCHEMA_VERSION`; verified by source inspection **and** by a test that would fail if a private copy were reintroduced. +3. A test exists that fails if the client-sent schema version and the server-accepted schema version can diverge, and it exercises the real client-built request body. +4. The runner exports `pub` constants for all three cgroup-v2 resource feature names, and `TrustedLandlockSetup::execution_capabilities` uses them; no capability feature literal remains at the runner's advertisement site. +5. The server's `check_resources_supported` imports the runner's constants; the cgroup feature names are not re-typed in the server. +6. `exec.argv.v1` is owned by `eggwork-core` and imported by both the server's `static_capability_features` and the client's `ensure_protocol_compatible`; the literal appears in neither endpoint crate's production code. +7. The `"workspace_rw"` profile name is a `pub` constant in `eggwork-runner`, used at all three runner sites; the helper's production code is unmodified and its literal is pinned by a test that proves a differing profile is refused before the target spawns. +8. Every capability feature-name value is byte-for-byte identical to its pre-M004 value, proven by freeze assertions. +9. `eggwork-core` owns the terminal/non-terminal classification; the classification is an exhaustive `match` over all nine variants with no wildcard arm, and the wire-spelling function is likewise exhaustive. +10. No terminal-state enumeration remains in `crates/eggwork-server/src/store.rs`, `crates/eggwork-server/src/lib.rs`, or `crates/eggwork-server/src/operations.rs` — including the inline `matches!` in the generation-reservation path, the inline capture-eligibility subset, the metric-name match's wildcard arm, and the SQL literal list. +11. A property test proves the classification is total and disjoint over every variant, and adding a variant to `ExecutionState` breaks the build or the test. +12. The `state` column stores the same values as before, and the SQL that counts active executions selects exactly `Accepted`, `Preparing`, `Running`, and `Cancelling`. +13. The artifact-capture eligibility predicate accepts exactly `Succeeded` and `Failed` and remains distinct from terminality. +14. The terminal-to-metric-name mapping is total over the terminal set, and the operator-facing state labels are byte-identical to their current output. +15. `crates/eggwork-core/src/lib.rs`'s `ExecutionState` wire representation is unchanged — still the derived `Serialize`/`Deserialize` with no rename attribute. +16. No new crate dependency edge exists; `eggwork-core` still has no internal dependency; `eggwork-sandbox-helper` still has no workspace-crate dependency. +17. The seven verification commands in §10 all pass, and the focused per-crate runs plus the `eggress-route` run are recorded. +18. The documentation updates in §9 are applied, and the touched documents cite by symbol name rather than by line number. +19. `plans/closure/control-plane-protocol/004-status.md` exists and satisfies §12. +20. No high or medium finding remains without an explicit owner. + +## 12. Stop conditions + +Stop, do not improvise, and escalate to the plan's owner if any of these occur. + +1. **A feature-string value would have to change.** If sharing a capability constant appears to require changing any feature name's bytes — including `exec.argv.v1`, the three `resources.cgroups-v2.*` names, `isolation.landlock.workspace-rw.v1`, or `network.unrestricted.v1` — stop. A value change is a compatibility break that needs an ADR, and `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md` §3 already froze these semantics. Preserve the values; change only the ownership. +2. **A dependency edge the crate rules forbid.** The rules are: `eggwork-core` and `eggwork-sandbox-helper` depend on nothing internal; `eggwork-client` depends on `eggwork-core`; `eggwork-server` depends on `eggwork-core` and `eggwork-runner`; `eggwork-client` is a dev-dependency of `eggwork-server` only. If a shared constant would require violating one of these — in particular, giving `eggwork-sandbox-helper` a workspace dependency, or giving `eggwork-client` a dependency on `eggwork-server` or `eggwork-runner` — stop and re-plan. The correct answer to a blocked owner is a different owner or a test-pinned literal, not a new edge. +3. **The core ownership change needs architecture review.** Giving `eggwork-core` a terminal-state classification and a schema-version constant is an intentional ownership change to a crate that currently owns neither. Per `plans/003-planning-process.md` §8, stop before implementing if that change has not been recorded as an ADR or canonical amendment, and report the blocker. +4. **The artifact-capture eligibility rule would have to widen.** If consolidating the enumerations appears to require capturing artifacts for `Cancelled`, `TimedOut`, or `Interrupted`, stop. That rule is a distinct policy subset and this plan must not touch it. +5. **The store's stored format would have to move.** If deriving the SQL literal list or the `state` spelling would change the stored bytes, the column schema, or the JSON in the `executions` table, stop and re-plan. This plan changes where the spelling comes from, not what it is. +6. **A test would become vacuous.** If any required test in §6 cannot be made non-vacuous — for example if the cross-crate agreement test cannot observe the client's real request body — stop and report. A test that passes for the wrong reason is worse than no test. +7. **A runtime behavior change is discovered to be required.** If any part of this plan appears to need a behavior change on the server or the runner beyond replacing a literal with the constant it already equals, stop. That means the plan's scope was wrong, not that the behavior should change. +8. **The `state_label` disposition cannot be decided.** If it is genuinely unclear whether the display map stays server-local or moves to core, either choice is acceptable — but the decision must be recorded in the closure record. Stop only if the ambiguity would change an operator-visible output. + +## 13. Closure evidence required + +Create `plans/closure/control-plane-protocol/004-status.md`. Per `plans/003-planning-process.md` §6, it MUST distinguish code inspection from executed evidence, and SHOULD include the following. + +**Required content.** + +1. **Reviewed baseline and implementation.** The reviewed head, the implementation commit(s), and the exact crates and symbols changed. Cite locations by file path and symbol name, not by line number. +2. **Requirement-to-evidence matrix.** One row per acceptance criterion in §11, each naming the specific implementation site and the specific test that proves it. A criterion with no named test is not closed. +3. **Tests and commands actually run.** The seven pre-submit commands from §10, with their actual outcomes, plus the focused per-crate runs and the `eggress-route` run. Record failures and retests honestly; a rerun is not a fix. +4. **Platform and feature matrix actually exercised.** The host actually used, and for each of the runner's platform paths (Linux Landlock/cgroup, Windows Job Object, macOS fail-closed) whether it was exercised, skipped, or not run. State plainly what was **not** exercised. Do not claim a platform or feature is qualified because its code compiles. +5. **Negative and adversarial evidence.** The cases that must fail: a schema-version mismatch still yields 426 `protocol_version`; a resource capability name differing by one character still yields `capability_mismatch` at admission; a sandbox profile differing from the runner's still fails before target spawn; the artifact-capture predicate still rejects `Cancelled`, `TimedOut`, and `Interrupted`; the SQL list still excludes terminal states. +6. **Compatibility review.** Evidence that no wire value, wire field, feature-string byte, stored format, or operator-visible output changed. If any changed, say so explicitly and treat it as a deviation. +7. **Security review.** Confirmation that authentication, authorization, lease, generation, fencing, and digest semantics are untouched, and that the ownership guard still passes — in particular that the shared constants introduce no new child-process creation path and no new dependency edge. +8. **Documentation status.** Which of the six documents in §9 were updated, and confirmation that the touched documents cite by symbol name. +9. **Unresolved findings by severity.** With an owner for each. A high or medium finding without an owner means the milestone is not closed. +10. **Decision record.** The two dispositions §2 left open and the plan required to be recorded: where `fn state_label` lives, and whether the artifact-capture eligibility predicate stayed server-local or moved to `eggwork-core`. +11. **Registry and roadmap disposition.** Note that `plans/registry.md` and `plans/subsystems/control-plane-protocol-roadmap.md` are owned by other writers and must be updated by them; do not edit them as part of this milestone. +12. **Deviations.** Anything that landed differently from this plan, with the reason. + +**Do not** rewrite the historical M001–M003 closure records. This corrective's record is additional. + +## 14. Handoff notes + +- **One agent, one bounded change.** This is a constant-and-derivation refactor across three crates. It is small per site and wide per crate; keep the edits mechanical and do not wander into the surrounding code. +- **Read the corrective addendum first.** `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` owns the findings and the ownership decisions. This plan owns the execution. Where they disagree, the addendum wins and the disagreement is a defect in this plan. +- **Start with CP-3's core change**, then CP-1, then CP-2. CP-3 is the one with the ownership question, so it is the one to get reviewed first; §5.3 item 17–18 is the part that needs the ADR named in §12 item 3. +- **The executor's crate dependency rules, verbatim:** `eggwork-core` → nothing; `eggwork-sandbox-helper` → nothing; `eggwork-client` → `eggwork-core`; `eggwork-server` → `eggwork-core` + `eggwork-runner`; `eggwork-client` is dev-only for the server. `eggwork-runner` → `eggwork-core`. No new edge may be introduced by this milestone. +- **The executor's scheduler-free constraint:** this milestone must not introduce node selection, a queue, priority, fairness, a DAG, cross-node placement, or semantic retry. One request targets one explicitly selected node. +- **Do not trust the interrogation notes over the code.** §2 records two places where the notes were wrong and the code was followed. Re-read every site before editing; the notes are a starting point, not an authority. +- **Cite by symbol, not by line.** This repository's architecture deep dives carry a stale-line-number defect at a large scale. New and edited planning documents must not add to it. If a line number is genuinely unavoidable, mark it as being at the reviewed baseline and re-verifiable before editing. +- **Do not claim anything was run.** The closure record is where runs are reported; a plan or an implementation note is not evidence. +- **Handoff is incomplete until the registry names this plan.** `plans/registry.md` is owned by another writer. Do not edit it; report that registration is required. diff --git a/plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md b/plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md new file mode 100644 index 0000000..2e49b05 --- /dev/null +++ b/plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md @@ -0,0 +1,212 @@ +# Foundation M005 — Runner request validation parity corrective + +Status: proposed + +Closure record: `plans/closure/foundation-execution-core/005-status.md` + +Class: invariant + +Source authority: + +- `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` +- `plans/subsystems/foundation-execution-core-roadmap.md` — durable invariants 4 and 5 +- `plans/closure/foundation-execution-core/002-status.md` — the canonical bounded local runner +- `plans/closure/foundation-execution-core/003-status.md` — runner API hardening +- `plans/003-planning-process.md#verification-philosophy` + +## 1. Objective + +Make the runner's request validation a projection of the `eggwork-core` domain contract instead of an independent restatement of it. + +Today the runner re-spells the core validation rules in a private helper. The two copies disagree: the runner is stricter than core on empty argv entries and materially weaker than core on environment-entry syntax and duplicate environment names. The runner's copy is the one that gates the actual `Command::env()` call on the run path, and the runner's public constructor and public environment setter reach that gate without passing through core validation at all. + +After M005, every request-construction rule has exactly one owner in `eggwork-core`; the runner consumes those rules rather than re-deriving them; and no public runner API can produce a request that violates the core contract. + +## 2. Baseline / problem statement + +At the reviewed baseline: + +- `crates/eggwork-runner/src/lib.rs` exposes `RunnerRequest::new(argv, root)` and `RunnerRequest::set_environment(Vec<(String, String)>)` as public API. Neither validates. +- `RunnerRequest::from_spec` calls `spec.validate()` before building the request, so the server's protocol path is safe. +- `RunnerRequest::validate` is a private method that re-implements the request rules. It is invoked at the top of the run path, immediately before the child process is constructed, and its result is what gates the environment handed to the child. +- `crates/eggwork-core/src/lib.rs` owns the real rules. `EnvironmentEntry::new` requires an environment name to be non-empty, within `MAX_ENV_NAME_BYTES`, composed only of ASCII alphanumerics and underscore, not to start with a digit, and to be free of NUL bytes. `CommandSpec::validate` additionally rejects duplicate environment names with a typed `ValidationError::InvalidSyntax`. +- The runner's copy checks only emptiness, length, NUL, and `=` in the name. It therefore accepts names containing `-` or `.`, accepts names beginning with a digit, and does not detect duplicate names at all. +- The runner also defines its own `StdinPolicy` enum, `Debug` implementation, and `validate` method, duplicating `eggwork_core::StdinPolicy`, which the crate already imports under the alias `CoreStdinPolicy` and converts to by hand. The runner's `OverflowPolicy` handling shows the intended pattern: the core type is imported and used directly. +- The runner's module documentation states: *"Request fields remain private so callers cannot bypass protocol bounds."* The fields are private, but the public constructor and public environment setter are the bypass that sentence claims cannot exist. + +The practical effect is narrow but real: an embedder using the public runner API can submit environment entries that the core domain contract rejects, and will not be told. + +## 3. Scope + +In scope: + +- the request-validation rules enforced by `crates/eggwork-runner/src/lib.rs`; +- the public construction surface of `RunnerRequest`; +- the runner's local `StdinPolicy` duplicate and its conversion from the core type; +- the runner's re-statement of the core output-policy bounds; +- the corresponding documentation in `architecture/runner-execution.md`. + +Out of scope: + +- any change to the wire representation of `ExecutionSpec`, `CommandSpec`, or any other core type; +- any widening or narrowing of a numeric bound — the core bounds remain the bounds; +- the `eggwork-sandbox-helper` crate, which has no workspace-crate dependencies and does not construct runner requests; +- the `eggwork-client` crate; +- the server's request handling, which already uses the validated path; +- the control-plane shared-contract corrective, the security isolation-truthfulness corrective, and the operations operator-truthfulness corrective — this milestone is independent of all three and may run in parallel with them; +- Operations M007 (Windows service host), which is a separate ready handoff. + +## 4. Invariants and non-goals + +Invariants that must hold after M005: + +1. A request-validation rule has exactly one owner in `eggwork-core`. +2. The runner is never weaker than its owner on any shared rule. +3. A rule the runner adds on top of core is explicit, documented in the code, and covered by a test. +4. No public runner API can produce a request that violates the core contract. +5. The runner accepts argv and never an implicitly interpreted shell string. +6. The runner's bounds are the core bounds. +7. The core crate keeps no internal dependencies and no scheduler or placement semantics. +8. The runner remains the single owner of production finite noninteractive process creation. + +Non-goals: + +- redesigning the core domain contract — core's rules are correct as they stand and are the authority here; +- introducing a validation framework, a builder crate, or a new error hierarchy; +- changing runner execution, timeout, cancellation, output-capture, or process-tree behaviour; +- making the runner aware of transport, authentication, or scheduling concerns. + +## 5. Required production changes + +1. **Move the environment-entry rules behind the core owner.** Ensure `eggwork-core` exposes the environment-name syntax and duplicate-name rules in a form the runner can consume, rather than the runner re-deriving them. If core already exposes enough, the change is to consume it; if not, the change is to widen an existing core helper's visibility rather than to add a second one. +2. **Consume, do not restate.** Replace the runner's environment checks in `RunnerRequest::validate` with calls into the core rules. The runner may retain an explicit check for an empty argv entry, because that rule protects the runner's child-process construction and is stricter than core; it must be documented as a runner-level rule in a comment that says why, and it must be tested. +3. **Remove the local `StdinPolicy`.** Delete the runner's duplicate enum, its `Debug` implementation, and its `validate` method; import `eggwork_core::StdinPolicy` directly, as the runner already does for `OverflowPolicy`. Remove the hand-written conversion. +4. **Consume the core output-policy bounds.** Replace the runner's re-stated capture-limit and event-chunk checks with the core `OutputPolicy` validation. +5. **Guard the public construction path.** Decide, and record the decision in the closure record, between: + - (a) removing `RunnerRequest::new` and `RunnerRequest::set_environment` from the public API so that `from_spec` is the only construction path; or + - (b) keeping them and making them validate, returning a typed error. + Option (a) is preferred if the repository has no in-tree caller, because it makes the bypass structurally impossible rather than merely checked. Verify the in-tree caller set before choosing. +6. **Preserve error fidelity.** A validation failure raised by the runner must remain attributable to the rule that produced it. Do not collapse distinct rules into a single undifferentiated message if the core types already distinguish them. +7. **Keep the runner's own contract rules intact.** The root-directory and working-directory resolution in `RunnerRequest::validate` — canonicalisation, the "root is a directory" check, and the "cwd escapes root" check — are runner-level rules that core does not own. They must survive M005 unchanged. + +## 6. Failure, cancellation, restart, and contention semantics + +M005 changes no runtime semantics. + +- Validation still occurs before any child process exists, on the same path, at the same point in the run sequence. +- A request that fails validation must still produce the same `RunnerError` family, and must still fail before spawn. +- Timeout, explicit cancellation, nonzero exit, output-limit termination, and cleanup failure must remain distinguishable, exactly as they are today. +- The `CancelledBeforeSpawn` check must continue to take precedence over validation, so a cancelled run does not report a validation error. +- Process-tree cleanup must complete before the execution owner releases its lifetime permit. + +The only behavioural difference M005 may introduce is that a request which previously passed the runner's weaker rules and was rejected by core, or vice versa, may now be rejected at a different point. That is the intended correction, and the closure record must name the specific rule dispositions that changed. + +## 7. Compatibility and migration + +No wire protocol change. No stored-format change. No change to any core type's serde representation. No change to the `ExecutionSpec` or `CommandSpec` wire shape. + +The compatibility surface is the runner's **public Rust API**. The runner crate is part of the published release artifact set, so any removal of a public item is release-visible and must be handled as a version-visible change, not a silent one. + +The plan must, before changing the API: + +1. enumerate every in-tree caller of `RunnerRequest::new` and `RunnerRequest::set_environment`; +2. state whether any out-of-tree embedder is known to exist, and if the answer is unknown, say so explicitly rather than assuming the API is free to change; +3. decide the disposition — removal, or validation with a typed error — and record which; +4. if removal is chosen, note that it is a breaking change to a published crate and that the release notes and the version must reflect it. + +The removal of the runner's local `StdinPolicy` is also public-API-visible, and must be included in the same compatibility statement. + +## 8. Required tests + +Required, and each must be non-vacuous: + +1. **Construction-path parity.** A test proving that a request built through every public construction path satisfies the same rules as a request built through `from_spec`. If the public constructor is removed, the test asserts that no other public construction path exists — that is, a test that fails if a new public constructor is added. +2. **Environment-name syntax.** Tests proving that the runner rejects every name form core rejects: a name containing a character outside ASCII alphanumerics and underscore, a name beginning with a digit, a name exceeding the core bound, and an empty name. These must fail through the runner's public API, not only through core's own tests. +3. **Duplicate environment names.** A test proving that a request carrying two entries with the same name is rejected, and that the rejection is attributable to the duplicate-name rule. +4. **Total and disjoint rule coverage.** A test over the core environment-entry rules proving the accepted and rejected sets partition the input space, so that a future rule change cannot silently open a gap. +5. **Stricter runner-level rules.** A test proving the runner still rejects an empty argv entry, and a comment at that check stating that it is a runner-level rule stricter than core. +6. **Stdin policy.** Tests proving the runner forwards stdin bytes and enforces the core stdin bound, after the duplicate type is removed. +7. **Output bounds.** Tests proving the capture-limit and event-chunk bounds behave as before the corrective. +8. **No behavioural regression.** The existing runner suite — timeout, cancellation, output-limit, process-tree, and cleanup diagnostics — must remain green unchanged. + +The verification must prove the rules are enforced where the runner claims them to be, not merely that the core crate's own tests pass. + +## 9. Required verification + +At minimum: + +```text +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 scripts/check_execution_ownership.py +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +`--locked` is load-bearing on both `clippy` and `test`: a version bump that skips `Cargo.lock` passes both and then fails every release build. + +If the runner's public API changes, the change must also be exercised on the Windows and macOS targets the release matrix builds, because the runner has platform-specific spawn paths and the request-validation change sits in front of all of them. Record the platform matrix actually exercised. + +## 10. Documentation updates + +- `architecture/runner-execution.md` — update the description of the runner's request validation so it matches the code, and in the same pass replace this deep dive's stale line-number citations with symbol references. This deep dive's citations are among the most drifted in the repository: the cited positions of `verify_trusted_helper`, `LANDLOCK_WORKSPACE_RW_CAPABILITY`, and `probe_landlock_ruleset` no longer point at those symbols. +- `architecture/overview.md` — record the new invariant in the divergences table only if a residual divergence remains after M005; if none remains, do not add a row. +- `architecture/core-domain.md` — note that core now owns the environment-entry rules the runner consumes, if the current text still describes them as unimplemented or ambiguous. +- `AGENTS.md` — update the "Construct validated state behind private fields (`RunnerRequest::from_spec`)" line if the construction path changes. +- `plans/subsystems/foundation-execution-core-roadmap.md` — add the M005 milestone entry and set the roadmap's status line to reflect it. +- `plans/registry.md` — updated by the registry owner when the milestone is registered; this plan does not edit it. + +## 11. Acceptance criteria + +1. Every environment-entry rule enforced by the runner is owned by `eggwork-core` and consumed by the runner. +2. The runner rejects every environment-name form core rejects, through the runner's public API. +3. Duplicate environment names are rejected by the runner. +4. The runner's local `StdinPolicy` duplicate, its `Debug` implementation, and its hand-written conversion are gone. +5. The runner's re-stated output-policy bounds are gone. +6. No public runner API can produce a request that violates the core contract, and a test proves it. +7. The runner remains at least as strict as core on every shared rule, and every intentional runner-level addition is documented in the code and covered by a test. +8. No numeric bound changed. +9. No wire representation changed; no core type's serde behaviour changed. +10. The existing runner suite is green, including the timeout, cancellation, output-limit, and process-tree tests. +11. `architecture/runner-execution.md` matches the code and no longer carries stale line-number citations. +12. The full pre-submit gate is green on the reviewed head. + +## 12. Stop conditions + +Stop and re-plan, recording the blocker, if any of the following occurs: + +- Consuming the core rules would require the `eggwork-core` crate to acquire a dependency, or would create a dependency edge the workspace's one-way rule forbids (core and the sandbox helper depend on nothing; client depends on core; server depends on core and runner; `eggwork-client` is dev-only for the server). +- Removing the public constructor or setter would break a known in-tree caller that cannot be migrated within this milestone, and the closure record cannot state the public-API compatibility position honestly. +- The core rules are found to be *weaker* than the runner's copy on some rule, which would mean the authority itself is wrong and the decision of which copy is correct must be escalated rather than assumed. +- Correcting the validation changes the observable behaviour of the server's execute path in a way that is not a pure rejection tightening — for example if a currently accepted request becomes rejected for a reason other than a validation rule. +- The milestone cannot be completed without weakening an authentication, lease, generation, fencing, or digest bound. + +## 13. Closure evidence required + +Create: + +- `plans/closure/foundation-execution-core/005-status.md` + +Per `plans/003-planning-process.md` §6, the record must distinguish code inspection from executed evidence and must include: + +- the reviewed repository head and the implementation commits; +- an executive finding; +- a requirement-to-evidence matrix mapping each acceptance criterion above to the specific command output or test that satisfies it; +- the exact focused and broader verification actually run, including the full pre-submit gate output; +- the platform matrix actually exercised, stated honestly — do not claim a platform was qualified merely because it compiles; +- negative and adversarial evidence: the environment-name and duplicate-name rejection tests, run and shown to fail the *pre-corrective* behaviour and pass the post-corrective behaviour; +- compatibility review: the public-API disposition, the in-tree caller enumeration, and the release-visibility consequence; +- documentation status, including the `architecture/runner-execution.md` update; +- unresolved findings ranked by severity; +- the registry and roadmap disposition. + +Do not claim tests were run when they were only inspected. Do not claim a platform or feature is qualified merely because its code compiles. + +## 14. Handoff notes + +- This milestone is independent and may be executed in parallel with the control-plane shared-contract corrective, the workspace data-plane correctives, the security isolation-truthfulness correctives, and the operations operator-truthfulness correctives. It may also be executed in parallel with Operations M007, which does not touch the runner's request API. +- The work is small and mechanical in the main, but the public-API decision in §5.5 is the part that needs a human's judgement. Resolve that decision first; the rest follows from it. +- The repository's own experience is that a rule written in one module and re-implemented in another has drifted before, and that the drift was found by inspection rather than by a failing test. Prefer the test that fails when a rule is weakened, over a comment that describes the rule. +- The runner crate is published. If the public API changes, the change must be reflected in the release version and notes, and must not be bundled silently into a release that claims to be a qualification-only candidate. diff --git a/plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md b/plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md new file mode 100644 index 0000000..ecbc3f1 --- /dev/null +++ b/plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md @@ -0,0 +1,267 @@ +# Operations M008a — Operator surface truthfulness corrective + +Status: proposed + +Closure record: `plans/closure/operations-distribution/008a-status.md` + +Class: capability + +Source authority: + +- `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` — findings OP-1, OP-2, OP-3 +- `plans/subsystems/operations-distribution-roadmap.md` — the operations surface milestones and their durable invariants +- `plans/closure/operations-distribution/001-status.md` — the node operations surface +- `architecture/operations-cli.md` — the operator command surface, its output discipline, and its redaction property +- `architecture/server-node.md` — admission, leases, and lifecycle +- `architecture/core-domain.md` — the wire types the client deserializes +- `plans/003-planning-process.md` — status vocabulary, milestone sizing, dependency discipline, required plan sections, closure evidence, corrective work, architecture changes + +## 1. Objective + +Make the node's operator surface report what the node actually knows, name each fact exactly once, and say what is wrong when the configuration is wrong. + +Three concrete defects are in scope: + +1. five metrics the server increments are never reported by `eggworkd metrics` / `eggworkd status`, because the operator surface keeps a hand-maintained name list instead of reading the producers; +2. two different facts are both called `active_executions` — permits held, and non-terminal execution rows — in the API status response and in the operator's own listing; +3. every configuration fault collapses into `configuration is invalid or unreadable`, so an operator with one wrong file mode is told nothing about which rule failed. + +After M008a, every metric the server can increment is visible to the operator; the two `active_executions` facts have distinct names and documented meanings; and a configuration failure names the rule it violated and the role of the offending item, without disclosing a private-key path or a certificate fingerprint. + +## 2. Baseline / problem statement + +At the reviewed baseline (`81f34e0`): + +**OP-1 — the metric vocabulary has no owner that is the producer.** + +- `crates/eggwork-server/src/operations.rs` declares `const METRIC_NAMES: &[&str]`, a hand-maintained list of metric names. +- `crates/eggwork-server/src/operations.rs` → `fn metrics_snapshot` seeds its counter map from `METRIC_NAMES`, then reads rows from the node metrics table and copies a value **only if the name is already in the map**. A metric absent from the list is silently discarded. +- `crates/eggwork-server/src/lib.rs` increments five metrics that are not in that list: `workspace_manifest_registrations`, `workspace_derived_requests`, `workspace_derived_hits`, `workspace_patch_entries`, `workspace_base_missing`. The workspace-derivation path increments three of them in one call. +- There is no test comparing `METRIC_NAMES` against the names the server can increment, and no test asserting that a freshly incremented metric appears in a snapshot. + +**OP-2 — one name, two facts.** + +- `crates/eggwork-server/src/lib.rs` → `fn node_status` computes `active_executions` as `max_active` minus available permits — *permits currently held*. The field is `eggwork_core::NodeStatus::active_executions`, a serialized wire type read by `eggwork-client` → `NodeClient::status`. +- `crates/eggwork-server/src/operations.rs` computes `active_executions` for the operator's execution listing as *the number of database rows in a non-terminal state*. +- `crates/eggwork-server/src/bin/eggworkd.rs` writes the key `active_executions` into the operator's status payload. +- The two facts legitimately differ: an execution that has crashed but has not been recovered still has a non-terminal row while its permit has been released. There is no field name that lets an operator tell which number is which. + +**OP-3 — the configuration fault kind is discarded.** + +- `crates/eggwork-server/src/operations.rs` returns `OperationsError::Config` at 25 sites covering every distinct configuration fault: unreadable file, wrong permissions, wrong owner, a sandbox helper outside a world-writable ancestor, a malformed field, an unparsable bind address, a failed serialization of the redacted config, and more. +- `crates/eggwork-server/src/bin/eggworkd.rs` maps the load failure to the single string `configuration is invalid or unreadable`. +- `AGENTS.md` records this as a known operator-visible pain point: the config loader's strictness "is undocumented anywhere else and produces a single unhelpful `configuration is invalid or unreadable`". +- `architecture/operations-cli.md` records the countervailing property that must survive: the binary "never interpolates an error's source text for library errors, no filesystem path, key detail, or child-process output can reach stderr through that path". The fix must add actionable detail without becoming a leak. + +## 3. Scope + +In scope: + +- the metric vocabulary and the report path in `crates/eggwork-server/src/operations.rs`; +- the metric increment sites in `crates/eggwork-server/src/lib.rs`; +- the operator-visible name and documentation of the two `active_executions` facts, in `crates/eggwork-server/src/operations.rs` and `crates/eggwork-server/src/bin/eggworkd.rs`; +- the configuration error taxonomy in `crates/eggwork-server/src/operations.rs` and its rendering in `crates/eggwork-server/src/bin/eggworkd.rs`; +- the `config print` and `config validate` verbs' reporting of configuration faults; +- the corresponding operator documentation in `docs/operations.md` and `docs/quickstart.md`, and the design record in `architecture/operations-cli.md`; +- tests for each of the above. + +Out of scope: + +- `crates/eggwork-core/src/lib.rs` → `NodeStatus` field names and the wire shape of the status response. This plan does **not** rename a wire field (see §9). +- The `doctor` check list and its ordering, except where a configuration fault is reported through it. +- The blob-inspection verb's re-derivation of the blob store's shard path layout. That is a further instance of the same defect class, observed during the interrogation pass, and it is **not** in this milestone; it is recorded here so it is not lost, and it is a candidate for a later corrective. +- The service-host lifecycle, the shutdown-and-wait convergence contract, and the Windows service path. Those belong to M007. +- The release harness, the design record's citation hygiene, and the CI feature-gate gap. Those belong to M008b. +- Any change to admission, authorization, lease, generation, fencing, or digest behaviour. + +## 4. Invariants and non-goals + +Invariants this plan must not weaken: + +- The scheduler-free, fixed-target boundary. `eggworkd` remains a single-node operator surface; nothing in this plan introduces a queue, worker selection, priority, or DAG. +- Authentication and authorization. The operator verbs keep their existing access model; no fault message may disclose the contents of an authorization decision, a principal, or a trust store. +- Lease, generation, and fencing bounds. The permit accounting that `fn node_status` reports is the same accounting that gates admission; this plan changes the *name* of one reported fact, never the accounting. +- Digest bounds. No artifact, workspace, or blob digest semantics change. +- The redaction property in `architecture/operations-cli.md`: `config print` redacts private-key paths and certificate fingerprints, and a configuration *failure* message must not disclose them either. +- `unsafe_code = "deny"` and the workspace clippy policy; no new dependency may be introduced into `eggwork-server` for this work. + +Non-goals: + +- Making the metrics subsystem support arbitrary user-defined metric names. The vocabulary is closed and node-internal. +- Changing the metric *storage* format. The node metrics table's shape is not in scope; only the report path is. +- Turning `eggworkd` into a monitoring product with per-metric thresholds, alerts, or history. +- Rewriting the config loader's rules. The rules are correct and strict; the defect is that the fault kind is discarded on the way to the operator. +- Any user-facing or wire-visible capability beyond the three named defects. + +## 5. Required production changes + +### 5.1 OP-1 — one owner for the metric vocabulary + +The producer must own the vocabulary. Two acceptable shapes, in order of preference: + +- **Preferred (derived):** the set of metric names the server can increment is derived from the producers rather than restated. This requires the increment sites to be the single registration point — for example a typed `Metric` enum or a `const`-declared set of names that `increment_metric`/`increment_metrics` accept, so that incrementing an unregistered name is a compile error rather than a runtime drop. If the names are strings in the database layer, the Rust-side vocabulary must still be the only list, and the report path must read *that* list rather than a second one. +- **Acceptable minimum (checked):** `METRIC_NAMES` remains hand-maintained, but a test derives the set of names the server can increment and fails when the two sets differ. + +In either shape: + +- `fn metrics_snapshot` must report every metric present in the node metrics table, and must not silently discard a row whose name is not in the vocabulary. A row whose name is unknown to the vocabulary must be either reported under its own name or reported as an explicit `unknown` bucket — never dropped without trace. +- The five currently invisible metrics — `workspace_manifest_registrations`, `workspace_derived_requests`, `workspace_derived_hits`, `workspace_patch_entries`, `workspace_base_missing` — must appear in `eggworkd metrics` and in the status payload. +- The workspace-derivation path's three-at-once increment must be covered by a test that asserts all three counters move. + +### 5.2 OP-2 — two facts, two names, one wire field + +The two facts must be separately named and separately documented. + +**Decision: rename the operator-side field; leave the wire field alone.** + +Rationale, stated explicitly because this is a protocol-visible choice: + +- `eggwork_core::NodeStatus::active_executions` is a serialized wire type that deployed `eggwork-client` builds already deserialize. Renaming it removes a field those clients require, and a missing field is a deserialization error, not a defaulted value — so renaming it breaks every deployed client that reads node status. +- Adding a new field to `NodeStatus` is also a wire change (clients that use `deny_unknown_fields` would reject it; the current type does not, but that is not a guarantee the client may rely on across versions), so no new wire field is introduced either. +- The operator-side field is *not* a published protocol. `eggworkd`'s JSON output is operator-facing and versioned with the binary, not with a wire contract. + +Therefore: + +- The wire field `NodeStatus::active_executions` keeps its name and keeps its meaning (permits held). Its meaning must be stated in `architecture/core-domain.md` and in the `NodeStatus` doc comment, because the name alone does not distinguish it from the operator fact. +- The operator-side field must take a distinct name that says what it is. The plan requires the implementer to choose names that are self-describing and stable — for example one that says *permits held* and one that says *non-terminal executions* — and to record the chosen names in the closure record. The plan does not fix the literal strings, because the string is not the substance; the substance is that the two are distinguishable without reading prose. +- The operator surface must be able to show **both** facts. The API's permit count and the store's non-terminal count are different measurements, and an operator investigating a stuck execution needs both. The operator status output must carry both under their distinct names. +- The `eggworkd executions list` output must use the same distinct name for the non-terminal fact as the status output, so the two surfaces agree with each other. + +### 5.3 OP-3 — actionable configuration failures + +`OperationsError::Config` must be replaced by a typed taxonomy, or complemented by one, that preserves the fault kind and the rule. + +Required shape of the operator-facing message: + +- **which rule** was violated, stated as a stable, greppable rule identifier or a stable human phrase — for example a wrong file mode, a group- or world-writable path, a wrong owner, a path outside the installation root, a helper outside a world-writable ancestor, a malformed field, an unparsable bind address; +- **which file or path failed** — for every item whose path is not itself secret, the message names it: the config file, the state directory, the blob root, the workspace root, the sandbox helper path, the bind address. For a **secret-bearing** item — the private key, and any certificate-bearing item — the message names the *role* only ("the private key"), never the path, because naming that path is exactly the leak the redaction rule exists to prevent; +- **what the operator should do** — the corrective action in one sentence. + +Requirements: + +- The message must not contain a private-key path, a certificate fingerprint, a certificate subject, or any arbitrary underlying error text. Underlying `std::io::Error` / `serde_json` text is not interpolated; only the classified rule, the offending file or path, and the role of a secret-bearing item are. +- `config print` and `config validate` must surface the same detail for the same fault. `config print`'s existing redaction of private-key paths and certificate fingerprints is preserved unchanged — the redaction applies to the *values it prints*, and the new detail applies to *faults it reports*. +- `doctor`'s configuration check must report the same rule when it reports a configuration fault. +- The daemon's startup path must report the same detail; a node that refuses to start because of one wrong file mode must say so. +- The taxonomy must not become a channel for disclosing configuration *contents*. Reporting "the private key file must be mode 0600" is required; reporting the path to that file, its fingerprint, or its subject is not. + +## 6. Failure, cancellation, restart, and contention semantics + +- The operator surface is a read path. This plan adds no new failure mode to the execute path and changes no cancellation or restart behaviour. +- The metric report path must tolerate a metrics table containing a name the vocabulary does not know: it must report or explicitly bucket it, not error and not drop it. A node whose metrics table has been written by an older or newer binary must still serve `eggworkd metrics`. +- Reading the configuration must remain side-effect free. The new fault classification must not change which faults are fatal or which are warnings. +- A configuration fault is reported once, at the layer that detects it. The `eggworkd` CLI must not re-detect a fault in order to describe it; it must render the kind the loader produced. +- The permit count reported by `node_status` is sampled at response time and may differ from a concurrently-taken permit. This is existing behaviour and stays. The two facts in §5.2 are inherently independent samples; the plan must not add a lock that makes them artificially consistent, and the documentation must not claim they are equal. + +## 7. Compatibility and migration + +- **Wire protocol: unchanged.** `eggwork_core::NodeStatus` keeps its fields, including `active_executions`, with its existing meaning (permits held). No field is added, renamed, or removed. `eggwork-client` requires no change. +- **Operator output: changed.** The operator-side `active_executions` key is replaced by two distinctly named keys. This is a change to `eggworkd`'s JSON output, which is operator-facing and not a published protocol. + - The plan requires the implementer to decide whether the old key is retained as a deprecated alias for one release, and to state that decision in the closure record. The default expectation is: retain the old key for one release, emitting it with the *store's* non-terminal meaning (the meaning the operator surface gave it before), and emit the new, unambiguous names alongside. If the implementer chooses not to offer an alias, the closure record must state why the operator-output break is acceptable and must not describe it as protocol-neutral. + - The documentation in `docs/operations.md` must show the new names from the first release that carries them. +- **Metric output: additive.** Five metrics become visible. No existing metric changes meaning, disappears, or changes value. Any operator script that asserted "the workspace counters are zero" will now see non-zero values; that is the point of the fix, and the release notes must say so. +- **Configuration error text: changed.** Scripts that matched the literal string `configuration is invalid or unreadable` will no longer match. The closure record must list this and the release notes must carry it. +- **No released artifact format changes.** The `eggworkd` binary changes; the release's asset names, install identities, and target set do not. +- **Migration for operators:** the new configuration message is actionable as-is; no operator action is required beyond fixing what it names. The renamed operator field is documented in `docs/operations.md` and in the release notes for the first release that carries it. + +## 8. Required tests + +- **Metric coverage (fails when a producer increments an unreported metric).** A test that derives the set of metric names the server can increment and asserts it equals the set the operator surface reports. The test must be written so that it *fails* when a new increment site adds a name the surface does not report — this is the test the repository currently lacks, and it is the test that makes the drift detectable next time. A test that only asserts the current five are present is insufficient; it must be a set-equality or coverage check over the producers. +- **Metric visibility.** A test that increments each of the five currently invisible metrics through the real increment path and asserts each appears in the resulting `metrics_snapshot`. +- **Multi-name increment.** A test that exercises the workspace-derivation path's three-at-once increment and asserts all three counters move. +- **Unknown metric name.** A test that inserts a metrics row with a name outside the vocabulary and asserts the report path reports or explicitly buckets it rather than dropping it. +- **Distinct names.** A test asserting the operator status payload contains both facts under their distinct names, and that no key carries the name `active_executions` for the non-terminal fact. +- **Naming collision guard.** A test over the operator output schema asserting that no two keys in the same object carry the same name with different meanings — a small structural check that generalises the specific defect. +- **Wire field stability.** A test asserting `eggwork_core::NodeStatus` still deserializes a status response that carries only the existing fields, and that `active_executions` still means permits held. If the wire type is changed in any way, this test must fail. +- **Configuration fault taxonomy.** One test per rule, asserting the reported rule identifier and the operator-facing message. +- **Redaction under failure.** A test that constructs configurations with a private key path and a certificate fingerprint, forces a configuration fault, and asserts the resulting message contains neither the private-key path nor the fingerprint, nor any certificate subject. This test is the proof that the added detail did not become a leak, and it is required, not optional. +- **Consistency across surfaces.** A test asserting that `config print`, `config validate`, `doctor`'s configuration check, and the daemon's startup failure report the same rule identifier for the same fault. +- **Success is unaffected.** A test asserting that a valid configuration still loads and still prints with the existing redactions intact. + +## 9. Required verification + +The repository's pre-submit gate, run in full: + +``` +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +Plus the focused evidence: + +- the metric-coverage test, run against the pre-change code, to show it **fails** before the fix and passes after; +- the naming-collision and distinct-name tests, run against the pre-change code, to show they fail before the fix; +- the redaction-under-failure test, run against the pre-change code and against any intermediate implementation, to show it never regresses. + +The ownership guard is load-bearing here: `crates/eggwork-server/src/**` is scanned by `scripts/check_execution_ownership.py`, and this plan must not introduce a process-spawning dependency into the server crate to implement anything in §5. + +`git diff --check` is part of the gate because this plan's own subject — citing code by symbol rather than by line — is a whitespace-and-formatting-adjacent discipline, and because the pre-submit list in `CONTRIBUTING.md` includes it. + +## 10. Documentation updates + +- `architecture/operations-cli.md` — update the inspection and reporting section to state that every incrementable metric is reported and that the vocabulary is owned by the producers; update the `doctor` description to reflect the current check list; update the output-discipline section to describe the configuration fault taxonomy and to state that a fault message names the rule and the item's role and discloses no path, fingerprint, or underlying error text. +- `architecture/core-domain.md` — state the meaning of `NodeStatus::active_executions` (permits held) and note that it is distinct from the operator-side non-terminal execution count. +- `architecture/server-node.md` — state that the permit count and the non-terminal row count are independent measurements that may legitimately disagree, and why. +- `docs/operations.md` — the operator-facing status and execution-listing output must document both distinctly named facts and say which is which; the `config print` / `config validate` section must show a failure message and explain the redaction rule. +- `docs/quickstart.md` — if any command in it can produce a configuration fault whose new text is shown, update the shown text. +- `architecture/overview.md` — the divergences table gains entries for the two findings that were recorded nowhere else (the metric vocabulary and the `active_executions` name collision) as *resolved by M008a*, or is corrected if it already carries them. This plan does not modify `architecture/overview.md`; the entry is recorded by the implementing agent under the roadmap's authority, or by the owner of that document. +- No document in this repository gains a line-number citation as a result of this plan. Citations added by this plan name the symbol and the file. + +## 11. Acceptance criteria + +1. `eggworkd metrics` and `eggworkd status` report `workspace_manifest_registrations`, `workspace_derived_requests`, `workspace_derived_hits`, `workspace_patch_entries`, and `workspace_base_missing`. +2. A test fails if any metric the server can increment is not reported by the operator surface. The test is demonstrated failing against the pre-change code. +3. The operator status output carries the permit count and the non-terminal execution count under two distinct names; neither uses `active_executions` for the non-terminal fact. +4. `eggwork_core::NodeStatus` is unchanged: same fields, same names, same meaning; `active_executions` remains permits held; a deployed client deserializing a status response is unaffected. +5. The operator output's disposition of the old `active_executions` key is decided, implemented, and documented, with the release-visible consequence stated. +6. A configuration fault produces a message naming the rule, the offending file or path (the role of the item, where the path is secret-bearing), and the corrective action. +7. No configuration fault message contains a private-key path, a certificate fingerprint, or a certificate subject. Proven by test. +8. `config print`, `config validate`, `doctor`, and daemon startup report the same rule identifier for the same fault. +9. `config print`'s existing redaction behaviour is unchanged. +10. The full pre-submit gate passes, with the focused tests demonstrated failing before the fix. +11. `architecture/operations-cli.md`, `architecture/core-domain.md`, `architecture/server-node.md`, `docs/operations.md`, and (if affected) `docs/quickstart.md` are updated and cite symbols, not line numbers. +12. No authentication, lease, generation, fencing, or digest bound is weakened; no new dependency is added; the scheduler-free fixed-target boundary is unchanged. + +## 12. Stop conditions + +Stop and escalate rather than proceeding if: + +- the wire field `NodeStatus::active_executions` cannot be preserved without a wire-visible change that breaks deployed clients — in that case the implementer must not rename it unilaterally; escalate the compatibility question; +- the metric vocabulary cannot be given a single owner without a change to the node metrics table's on-disk format — that is a storage change and belongs to the storage journal's authority, not to this plan; +- making a configuration fault actionable would require disclosing a private-key path, a fingerprint, a subject, or arbitrary underlying error text — the redaction property wins; the operator-facing detail must be re-derived from the classified rule instead; +- a configuration failure would have to name a secret-bearing *value* to be actionable — out of scope; report the rule and the role only; +- the fix would change which configuration faults are fatal, or would change admission, authorization, lease, generation, or fencing behaviour; +- the work would require weakening the ownership guard, adding a process-spawning dependency to `eggwork-server`, or moving the fixed-target, scheduler-free boundary. + +## 13. Closure evidence required + +Create `plans/closure/operations-distribution/008a-status.md`. + +Per `plans/003-planning-process.md` §6, the record must distinguish code inspection from executed evidence and must include: + +- the reviewed repository head and the implementation commits; +- an executive finding; +- a requirement-to-evidence matrix mapping each acceptance criterion above to the specific command output or test that satisfies it; +- the exact focused and broader verification actually run, including the full pre-submit gate output; +- the platform matrix actually exercised, stated honestly — do not claim a platform was qualified merely because it compiles; +- negative and adversarial evidence: the metric-coverage test, the naming-collision test, and the redaction-under-failure test shown failing against the pre-corrective behaviour and passing against the post-corrective behaviour; +- the compatibility review: the disposition of the operator-side key rename, the confirmation that the wire type is byte-for-byte unchanged, the enumeration of in-tree consumers of `NodeStatus`, and the release-visibility consequence for operator scripts; +- the security review: confirmation that no configuration fault message disclosed a path, fingerprint, subject, or secret-bearing value; +- documentation status, listing each document updated; +- unresolved findings ranked by severity, including the blob-inspection shard-layout duplication recorded in §3; +- the registry and roadmap disposition. + +Do not claim tests were run when they were only inspected. Do not claim a platform or feature is qualified merely because its code compiles. + +## 14. Handoff notes + +- **M008a is `proposed`, not `ready`.** It has no unmet dependency, but it carries two decisions that need a human's judgement before implementation: the exact names for the two operator-side facts (§5.2) and the disposition of the old `active_executions` key (§7). Resolve those first; the rest follows mechanically. +- **M008a is independent of M007 and of M008b.** It may execute in parallel with M007, with M008b, and with the other corrective addenda in this planning batch. It does not touch the service-host lifecycle, the shutdown-and-wait convergence contract, or the Windows service path; the foreground-`run` shutdown asymmetry is owned by M007 and is deliberately not duplicated here. +- The metric work in §5.1 is the part with the highest ratio of value to effort and should be done first, because it is the only finding in this plan that is purely additive and carries no compatibility cost. +- The redaction tension in §5.3 is the part most likely to be got wrong. The property in `architecture/operations-cli.md` — that no filesystem path, key detail, or child-process output reaches stderr — is deliberate and must survive. A configuration failure message that names a rule is worth having; a configuration failure message that leaks a key path is a security regression. The required test in §8 is what keeps the two apart. +- The repository's own experience is that a rule written in one module and re-implemented in another has drifted before, and the drift was found by inspection rather than by a failing test. Prefer the test that fails when the rule is weakened over a comment that describes the rule — that is the whole shape of OP-1 and OP-2. diff --git a/plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md b/plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md new file mode 100644 index 0000000..624f5f8 --- /dev/null +++ b/plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md @@ -0,0 +1,315 @@ +# Operations M008b — Release harness and documentation single-sourcing corrective + +Status: proposed + +Closure record: `plans/closure/operations-distribution/008b-status.md` + +Class: infrastructure (release harness and CI) / polish (documentation drift and citation hygiene) + +Source authority: + +- `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` — findings OP-4, OP-5, OP-6 +- `plans/subsystems/operations-distribution-roadmap.md` — the release and qualification milestones and their durable invariants +- `plans/closure/operations-distribution/003-status.md` — Eggpack producer packaging integration +- `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md` — operational and release qualification +- `architecture/distribution.md` — the producer/consumer/release-channel authority split +- `architecture/release-qualification.md` — the qualification harness and its failure semantics +- `architecture/ci-guardrails.md` — the CI jobs, the ownership guard, and the `--locked` discipline +- `architecture/overview.md` — the component table and the divergences table +- `plans/003-planning-process.md` — status vocabulary, milestone sizing, dependency discipline, required plan sections, closure evidence, corrective work, architecture changes, external dependencies + +## 1. Objective + +Make the release harness, the CI configuration, and the design record each state a fact once, derive it from its owner, and say so where a reader would look. + +Three defects are in scope: + +1. the release harness re-derives — or simply remembers — facts that already have one owner: the workspace version (three readers), the expected version (two conflicting authorities), the asset inventory (a hardcoded count beside a derived set), the install identities (four declarations), and the release-target classification (an explicit list beside a suffix heuristic); +2. the design record's line-number citations have drifted from the tree, the component size table is wrong in every row, and one divergences entry describes an already-fixed defect as an open question — with nothing in CI that would notice; +3. CI type-checks code it never executes, and one test reports success while asserting nothing. + +After M008b, the harness holds no independently remembered constant for any fact it asserts; the design record cites symbols rather than line numbers and a mechanical check keeps it that way; the quickstart is machine-verified or its waiver is recorded where a reader would look; and every test that CI reports as green has asserted something. + +**Classification note.** The harness and CI portion is internal machinery required by the release capability and is classified **infrastructure**. The documentation-drift portion is genuinely **polish** — a stale size table and a stale `doctor` check count are documentation defects, not behavioural ones — and must not be represented as capability. The one part of OP-5 that is not polish is the *absence of a gate*: a document that asserts "executed and verified" while nothing verifies it is a truthfulness defect of the same family as OP-1 and OP-3, and it is included here. + +## 2. Baseline / problem statement + +At the reviewed baseline (`81f34e0`): + +**OP-4 — the release harness re-derives facts that already have one owner.** + +- *Workspace version, three readers.* `scripts/check_release_tag.py` → `fn workspace_version` uses a regular expression over the whole `Cargo.toml` and takes the **first** `version = ` line in the file, not the one under `[workspace.package]`; it works only by accident of the current manifest layout, in which `[workspace.package]` happens to precede every other `version = ` line. `scripts/release_candidate_probe.py` → `fn workspace_version` reads `workspace.package.version` with `tomllib`. `crates/eggwork-server/tests/release_contract.rs` → `fn the_release_version_is_one_coherent_workspace_identity` reads the same field with the `toml` crate. +- *The tag guard is never executed by an automated job.* `scripts/check_release_tag.py` is referenced by nothing in the repository except its own docstring. It is not invoked by `.github/workflows/ci.yml`, `.github/workflows/release.yml`, `.github/workflows/operational-qualification.yml`, or `.github/workflows/windows-reproducibility.yml`, and it has no test in `tests/release/`. **The script's own docstring explains why the tag-dependent half cannot live in CI** — "the tag-to-version link cannot live in CI: the generated release workflow is producer authority (the `release-drift` job rejects hand edits to it), and CI never knows the future tag. So the check lives here, run by whoever cuts the tag, before the tag exists" — and that reasoning is sound: CI cannot assert a tag it does not know. The defect is therefore narrower than "it is unwired", and it is three things: the script reads the manifest with a **different parser** from the shared reader; `fn lock_versions` parses `Cargo.lock` with regular expressions as well; and a guard whose correctness decides whether a release may be tagged is exercised by **no automated job at all**, not even against a fixture, so its correctness is an untested assumption. +- *Two version authorities.* A manifest-derived authority (`scripts/validate-daemon-version.py`, `scripts/validate-sandbox-helper.py`, `scripts/release_candidate_probe.py` — all derive the expected version from the workspace manifest) and a tag-derived authority (`scripts/qualify_release.py` → `fn stage_install` derives `expected_version` from `args.release_tag` and asserts the installed daemon and helper report it). Nothing states which is the release gate and which is the build assertion. +- *Asset inventory, twice in one function.* `scripts/qualify_release.py` → `fn stage_inventory` derives the expected asset set dynamically from the release manifest and, in the same function, asserts the asset count against the hardcoded `QUALIFIED_ASSET_COUNT`. +- *Install identities, four times.* `crates/eggwork-server/src/deployment.rs` declares them as constants (`SERVICE_ID`, `MEMBER_DAEMON`, `MEMBER_HELPER`); `release/eggpack/distribution.toml` declares the same install identities in its `install` fields and describes itself as "the sole checked-in authority for the published target set, release asset names, install identities, and checksum sidecar names"; `scripts/qualify_release.py` declares `SERVICE_ID` and `HELPER_INSTALL_ID` as its own constants; `crates/eggwork-server/tests/release_contract.rs` pins the Rust side to string literals. The Rust side is cross-checked against the contract by the Rust contract test; the Python side is pinned by nothing. +- *Target classification, twice.* `crates/eggwork-server/tests/release_contract.rs` holds explicit lists of target triples; `scripts/qualify_release.py` → `fn target_daemon_install` and `fn target_ships_helper` classify a target by testing whether the string ends with `-pc-windows-msvc` or `-unknown-linux-gnu`. + +**OP-5 — the design record and the operator documentation have drifted, and there is no gate.** + +- *Line-number citations are stale.* `architecture/*.md` carries 718 line-number citations of the form `file.rs:NNN`. Re-measuring against the tree with the nearest backticked identifier as the anchor, 85% of the resolvable citations no longer resolve at the exact cited line, 83% are stale within a ±3-line tolerance, and 72% remain stale even allowing ±20 lines of drift. (The interrogation pass reported roughly 92%; the exact figure depends on the tolerance chosen and the conclusion does not depend on it.) The per-file distribution is concentrated: `data-plane.md` 206, `server-node.md` 198, `core-domain.md` 111, `storage-journal.md` 100, `sandbox-helper.md` 43, `client-transport.md` 39, `deployment-lifecycle.md` 18, `runner-execution.md` 3. Spot-verified examples: `architecture/deployment-lifecycle.md` cites `verify_trusted_helper` as living in `crates/eggwork-server/src/lib.rs`, while the function is defined in `crates/eggwork-runner/src/lib.rs` — the wrong file entirely; `architecture/runner-execution.md` cites `LANDLOCK_WORKSPACE_RW_CAPABILITY` and `probe_landlock_ruleset` at line numbers that sit roughly 140 lines away from the definitions they name in `crates/eggwork-runner/src/lib.rs`. The citation *form* is the defect: a line number is a property of the text, not of the symbol, and it is invalidated by every unrelated edit above it. Citations frequently use a bare basename (`lib.rs`, `artifact.rs`), which is additionally ambiguous across the five crates. +- *The component size table is wrong in every row.* Counting non-test Rust sources at the reviewed baseline: core 2,294 lines against a stated 1,671; runner 2,900 against 2,336; client 1,158 against 880; server 16,980 against 14,104; sandbox-helper 446 against 401. +- *Divergence #20 is stale in the dangerous direction.* The `architecture/overview.md` divergences table states that the client's `decode_json` calls `response.bytes()` with "no size cap", leaving the JSON paths open to memory exhaustion from a hostile node. That is no longer true: `crates/eggwork-client/src/lib.rs` applies `max_decoded_body_size(MAX_BUFFERED_BODY_BYTES)` at the transport layer and a stricter `MAX_TELEMETRY_BODY_BYTES` cap on the telemetry route, and the client's own module comment records the change. The table is read as the list of *open* questions, so a reader would go chasing an issue that is already fixed. This is the most dangerous form of documentation drift. +- *A second drift of the same kind exists between the design record, the operator documentation, and the code.* `architecture/operations-cli.md` describes `doctor` as "Seven checks, in order" and omits `host-telemetry`; `crates/eggwork-server/src/operations.rs` → `fn doctor` emits eight checks including `host-telemetry`; `docs/operations.md` documents eight. `docs/quickstart.md` shows a `doctor` output block with seven checks — so the quickstart's claim that "the output shown is real" is already false for that block. +- *The quickstart is not machine-verified.* No CI job, test, or script executes or even references `docs/quickstart.md`; the only mention outside `docs/` is a source comment. `AGENTS.md`'s assertion that quickstart commands "are executed and verified, not illustrative" is true of their authors' intent and unbacked by any gate. +- *The mechanism.* The repository's prose volume is roughly 85% of its code volume (`architecture/` about 8,500 lines against `crates/` about 28,400; `plans/` about 15,300; `docs/` about 870; `scripts/` about 2,550), and documentation files are touched about 2.7 times as often as Rust files in recent history. Prose moves faster than code and nothing reconciles the two. + +**OP-6 — CI does not execute the code it type-checks.** + +- *The feature-gated qualification test never runs in CI.* `.github/workflows/ci.yml` runs `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` with `--all-features`, but runs `cargo test --locked --workspace --all-targets` **without** it. `crates/eggwork-server/tests/installed_qualification.rs` is gated by `#![cfg(feature = "qualification")]`, so clippy type-checks it and the CI test step never executes it. It is additionally marked `#[ignore]` on its two tests, and it runs in `.github/workflows/operational-qualification.yml` — which is `workflow_dispatch` only, so on an ordinary push or pull request the suite never executes anywhere. +- *Adding `--all-features` to the test step would not close the gap.* The two `#[ignore]` attributes keep the tests from running regardless of which features are enabled. The gap is closed by **executing** the ignored tests in a job that has the environment they need, not by enabling a feature flag. +- *One test is green while proving nothing.* `crates/eggwork-runner/tests/capability_probe.rs` → `fn built_helper` locates the sandbox helper binary through the runtime environment variables `CARGO_TARGET_DIR` and `OUT_DIR`; when it cannot, the test returns early and **passes with zero assertions**. The file's own comment claims "CI builds it before running this suite, so this skip is a local-only convenience", but `CARGO_TARGET_DIR` is not set by the repository's `.cargo/config.toml` and is not exported to integration test binaries, and `OUT_DIR` is a compile-time variable for build scripts, not a runtime environment variable. The skip is therefore the *normal* path in CI as well as locally. The repository already contains the two deterministic patterns this test should use: `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` → `fn built_helper` resolves the helper through the compile-time `CARGO_BIN_EXE_` variable, and `crates/eggwork-server/src/lib.rs` → `fn locate_helper_binary` walks the current executable's sibling and grandparent before consulting `CARGO_TARGET_DIR`. + +## 3. Scope + +In scope: + +- the version readers in `scripts/check_release_tag.py`, `scripts/release_candidate_probe.py`, `scripts/validate-daemon-version.py`, and `scripts/validate-sandbox-helper.py`, and the version reader in `crates/eggwork-server/tests/release_contract.rs`; +- the expected-version assertion in `scripts/qualify_release.py` → `fn stage_install`; +- the asset inventory and its count in `scripts/qualify_release.py` → `fn stage_inventory`; +- the install-identity and service-identity constants in `scripts/qualify_release.py`, and the target-classification helpers `fn target_daemon_install` and `fn target_ships_helper`; +- the wiring of `scripts/check_release_tag.py` into CI, and the recording of the release-path wiring requirement that cannot be met in this repository alone; +- every line-number citation in `architecture/*.md`, and the design record's component size table and divergences table; +- `docs/quickstart.md`, its machine-verification, and the drift between it and the code; +- the CI test step's feature coverage and the qualification suite's execution; +- `crates/eggwork-runner/tests/capability_probe.rs` → `fn built_helper` and the vacuous skip it enables; +- `architecture/ci-guardrails.md`, `architecture/release-qualification.md`, `architecture/distribution.md`, `architecture/overview.md`, `docs/operations.md`, `docs/quickstart.md`, and `docs/releases.md` as they are affected. + +Out of scope: + +- `.github/workflows/release.yml`. It is **generated** by `eggpack ci generate` from `release/eggpack/`, and `AGENTS.md` invariant 7 says it must never be hand-edited; `eggpack ci check` fails on drift. Any change to the release workflow's steps must go through the producer configuration, and the plan treats that as an upstream dependency, not as an in-repo edit. +- `release/eggpack/` itself, which Eggpack owns. This plan *reads* the producer configuration; it does not change it. If the only route to a required fact runs through an Eggpack change, that is an upstream prerequisite and must be recorded as such. +- The operator-surface findings OP-1, OP-2, OP-3, which belong to M008a. The one coupling is that the quickstart's troubleshooting table quotes the configuration error text, which M008a changes; the two plans must not both edit that text. +- The service-host lifecycle and the shutdown-and-wait convergence contract, which belong to M007. +- The blob-inspection verb's re-derivation of the blob store's shard path layout, which M008a records as a further instance of the same defect class. +- Any change to a released artifact's bytes, name, target set, install identity, or version. This plan changes *how the harness knows* those facts, never the facts themselves. +- Any change to the wire protocol. + +## 4. Invariants and non-goals + +Invariants this plan must not weaken: + +- The scheduler-free, fixed-target boundary. The release channel ships a node; it does not schedule. +- The release-identity invariant: no release identity in `release/eggpack/` — no tag, source SHA, artifact digest, or size. Deriving facts *from* the producer configuration must not push identity into it. +- `.github/workflows/release.yml` is generated and is never hand-edited; `eggpack ci check` must still pass. +- `--locked` remains load-bearing on `clippy` and `test` in CI. Any CI change this plan makes must keep `--locked` on both. +- The ownership guard's scope and the `--prove-negative-exit` self-test are unchanged. +- No authentication, lease, generation, fencing, or digest bound is weakened. No released artifact format changes and no wire protocol changes. +- The isolation claims remain earned: nothing in the harness may assert a platform or capability that was not probed. + +Non-goals: + +- Making the harness a general-purpose release tool. It qualifies *this* product against *this* producer contract. +- Rewriting the release qualification workflow's structure or its receipt format. +- Translating the whole design record into a different documentation system. The correction is: cite symbols, and check the citations. +- Editing the divergences table's *substance* beyond re-verifying it. If re-verification reveals a genuine open divergence that is not recorded, that is a finding for the owner of `architecture/overview.md`; this plan records it and does not silently rewrite it. +- Making prose generation automatic. The correction is a *check*, not an author. + +## 5. Required production changes + +### 5.1 OP-4 — one owner per fact, and the harness's copies removed + +The rule this plan establishes: **multiple readers of one owner are fine; multiple owners are not.** A second implementation that *reads* the same owner and is itself checked against it is a useful cross-language check. A second implementation that *remembers* the fact is a defect. + +- **Workspace version.** One Python reader, used by every script. The repository already has the shape of the right answer: `scripts/release_candidate_probe.py` → `fn workspace_version` reads `workspace.package.version` with `tomllib`, and `scripts/validate-daemon-version.py` and `scripts/validate-sandbox-helper.py` already import `fn expected_version_line` from it rather than keeping their own copies. What is missing is that `scripts/check_release_tag.py` and `scripts/qualify_release.py` are not on that reader. `scripts/check_release_tag.py` → `fn workspace_version` must stop using a regular expression and must read `workspace.package.version` with a real TOML parser; the reader must be shared, not duplicated, and the plan requires that every release script obtains the version through it. The reader must fail closed on a malformed manifest or a missing `[workspace.package].version`, and must not fall back to a regex. + - The Rust reader in `crates/eggwork-server/tests/release_contract.rs` stays: it is an independent cross-language check of the *same owner*, not a second owner. The Rust test and the Python reader must both be checked against the manifest. +- **The two version authorities, reconciled explicitly.** + - **Owner of the version the binaries report:** `Cargo.toml` `[workspace.package].version`, inherited by every crate through `version.workspace = true` and surfaced by the daemon as `env!("CARGO_PKG_VERSION")` in `eggworkd version`. This is the *build assertion*: the binary must report the manifest version, always. + - **Release gate:** the release tag must equal `v` + the manifest version. That is `scripts/check_release_tag.py`'s job, and it is the only place a tag and a version are compared. + - **Why they are permitted to differ:** they are permitted to differ in exactly one respect — the tag may carry a `v` prefix and the manifest version may not. Beyond that prefix, the two must be equal, and the gate is what proves it. A binary built from a working tree reports the manifest version but is not a release candidate; a release candidate is a binary built from a tag that the gate has accepted. The qualification harness's job is therefore to assert the *binary* against the *manifest-derived* version, and to record the tag it was qualified under — not to re-derive the expected version from the tag. `scripts/qualify_release.py` → `fn stage_install` must stop deriving `expected_version` from `args.release_tag` and must instead use the shared manifest-derived version, while still asserting that the tag it was invoked with matches that version (or delegating that assertion to `check_release_tag.py`, which the release job must then run). + - The plan requires this reconciliation to be written down in `architecture/release-qualification.md`, in a form that a reader of the harness can consult to learn which number to trust. +- **Asset inventory.** `QUALIFIED_ASSET_COUNT` is **deleted**, not re-synced. `scripts/qualify_release.py` → `fn stage_inventory` already derives the expected asset set dynamically from the release manifest; the assertion must compare the staged set against the derived set. If a count is wanted for the receipt, it is computed from the derived list, never remembered. +- **Install identities and the service identity.** The harness must contain **no literal** install or service identity. + - Install identities (`eggworkd`, `eggwork-sandbox-helper`) are read from `release/eggpack/distribution.toml`'s `install` fields. `scripts/qualify_release.py`'s `SERVICE_ID` and `HELPER_INSTALL_ID` constants are deleted and their uses derive from the contract. The executable-name suffix convention (`.exe` on Windows) is applied in exactly one place and is not an identity. + - The service identity (`eggwork-node` — the systemd unit name and the launchd label) is owned by `crates/eggwork-server/src/deployment.rs` → `SERVICE_ID`, and the harness must obtain it from the daemon rather than remember it: `eggworkd service spec` already reports `service_id` (it requires `--executable` and `--service-config`, both of which the harness has when it stages an installation), and `eggworkd deployment status` reports it too. The harness reads it from the candidate daemon. + - The Rust contract test keeps pinning the Rust constants to the contract's values — that is the check that keeps the two languages honest — and the Python harness must have an equivalent check against the same owner. +- **Target classification.** `fn target_daemon_install` and `fn target_ships_helper` must stop classifying by string suffix and derive from the contract's `[[targets]]` entries: which assets a target ships, and therefore whether it ships the helper, is stated by the contract's asset kind and entries. The Rust test's explicit triple lists stay as the independent check against the same owner. + +### 5.2 OP-4 — the tag guard uses the shared reader and is exercised + +- **The reader.** `scripts/check_release_tag.py` → `fn workspace_version` must stop using a regular expression and must obtain the version through the shared reader (§5.1). `fn lock_versions` must likewise stop parsing `Cargo.lock` with regular expressions and must use a real TOML reader for the lock file. A guard that decides whether a release may be tagged must not depend on the layout of the files it reads. +- **The tests.** `scripts/check_release_tag.py` must gain tests in `tests/release/`, which it does not currently have: the tag↔version rule, the `v`-prefix case, the lock-version rule, the malformed-manifest case, the missing-`[workspace.package].version` case, and a manifest whose `[workspace.package]` section is not first. +- **The CI wiring — what CI *can* assert.** The tag-dependent half of the guard cannot run in CI, and the plan does not pretend otherwise: CI does not know the future tag, and the script's own docstring says so. What CI must do is: + - **exercise the guard's logic** against fixtures, so that the code path that decides whether a release may be tagged is executed by an automated job rather than trusted; + - **assert the version-coherence half on every push and pull request** — that the workspace manifest's version and the lock's pinned versions agree with each other, which needs no tag and is the condition that most often breaks (a version bump without a lock regeneration is exactly what failed the `v0.1.3` release attempt); and + - **state in the workflow itself** that the tag-dependent assertion lives in `scripts/check_release_tag.py` and is run by whoever cuts the tag, so a reader of `.github/workflows/ci.yml` can see where the gate is. +- **The wiring belongs in `.github/workflows/ci.yml`**, which is hand-maintained and is **not** checked by `eggpack ci check` (that check covers `.github/workflows/release.yml` only). +- **The release-path wiring cannot be done in this repository alone.** `.github/workflows/release.yml` is generated by `eggpack ci generate` from `release/eggpack/`, and hand-editing it is forbidden; `eggpack ci check` fails on drift. The plan therefore requires: + - the upstream prerequisite to be recorded explicitly, naming what Eggpack must support (a repository-local preflight step that runs the tag guard against the tag being released, or an equivalent hook) and where it would be configured; + - the in-repo CI wiring to land now, so the guard's logic is exercised even before the upstream hook exists; + - the *process* requirement to be documented — the script's own docstring already states that whoever cuts the tag runs it before the tag exists, and `docs/releases.md` or `architecture/release-qualification.md` must say so plainly rather than leaving it in a script docstring; and + - a statement, in `architecture/release-qualification.md` and in the closure record, of exactly where the gate runs today and where it does not, so that nobody reads "the tag guard is in the repository" as "the tag guard ran". + +### 5.3 OP-5 — citations become symbols, and a check keeps them that way + +- **Canonical citation form.** Every code reference in `architecture/*.md` and `docs/*.md` names a **repository-relative path** and a **symbol**, never a line number and never a bare basename. A path is required because `lib.rs` alone is ambiguous across five crates. +- **Conversion.** All 718 line-number citations in `architecture/*.md` are converted, in this order (largest first): `data-plane.md`, `server-node.md`, `core-domain.md`, `storage-journal.md`, `sandbox-helper.md`, `client-transport.md`, `deployment-lifecycle.md`, `runner-execution.md`. `docs/*.md` currently carries no line-number citations; the conversion must leave it that way. +- **The durable guard.** A script — the plan names `scripts/check_doc_citations.py` — verifies every code citation in `architecture/*.md` and `docs/*.md`: + - a citation in the legacy `file.rs:NNN` form is a failure, not a warning; + - a citation whose named path does not exist is a failure; + - a citation whose named symbol does not exist in the named file is a failure. The check must recognise Rust items (`fn`, `pub fn`, `const`, `static`, `struct`, `enum`, `trait`, `impl`, `mod`, `type`, `macro_rules!`) and Python items (`def`, `class`, and module-level assignments), and must resolve a bare basename only when it is unique in the tree — otherwise the citation must be rejected; + - the script must be wired into CI and must fail the build, not warn. +- **Why a symbol check and not a line check.** A line-number check is *strictly weaker* than it looks: it verifies that a line exists, not that it says what the citation claims, and it breaks on every unrelated edit above the target. A symbol check verifies that the named thing is still there and still named that, which is the property a reader actually relies on. It is not complete — a symbol can exist in the file without being the one the sentence means — so the plan requires that where a symbol name is ambiguous within its file, the citation names the qualified path (for example the module path as well as the item name). +- **The script must be proven to fail.** The plan requires a self-test of the checker — a fixture containing a deliberately wrong citation that the checker must reject — analogous to the ownership guard's `--prove-negative-exit`. A checker that has never been shown to fail is not a gate. +- **The component size table.** The plan requires the size column of the `architecture/overview.md` component table to be **removed and replaced by something that cannot silently go stale**: a checked-in script that prints the current per-crate figures on demand, with the table pointing at that script instead of carrying numbers. Rationale: the figures were never load-bearing — they are an at-a-glance claim about the shape of the tree — and they were wrong in every row, which is worse than absent. The alternative (regenerating the numbers into the table) is rejected because it would put a generated table inside a hand-written document and re-create the same drift loop with a new trigger. +- **The divergences table.** Every entry is re-verified against the tree, entry by entry, and each entry is either corrected, closed, or confirmed. Specifically: + - **Divergence #20 must be corrected or closed.** It states that the client's `decode_json` reads the body with no size cap; the client now applies a transport-level maximum decoded body size and a stricter telemetry cap. The entry must be rewritten to describe the cap that exists and to state the residual question precisely, or closed with the reason it no longer applies. + - The entry that describes the `doctor` check count must be reconciled with the code (`fn doctor` emits eight checks including `host-telemetry`), and the affected documents — `architecture/operations-cli.md` and the `doctor` block in `docs/quickstart.md` — must agree with it. + - The entry about `--windows-start-type` being passed by `scripts/qualify_release.py` to a code path that parses nothing is directly relevant to this plan's harness work and must be re-verified rather than assumed still true. + - Entries that remain open must stay open, with the open question stated. + +### 5.4 OP-5 — the quickstart becomes machine-verified + +The options considered: + +- **(a) A CI job that executes the quickstart against a locally built node with generated TLS material.** Real cost: the quickstart needs `openssl`, a built daemon and helper, the helper installed at a *trusted* path (outside any world-writable ancestor), a config with correct `0700`/`0600` modes, a running node that must be stopped before the fixture step (the fixture takes an exclusive lock on the state directory), and the `qualification`-feature tests, which are `#[ignore]`d and need their environment variables set. The job also has to keep the document honest about its *shown output*, not only its commands. +- **(b) A test that extracts and runs the quickstart's commands.** Rejected: it parses arbitrary shell out of Markdown, which is brittle (the quickstart uses process substitution and a `pkill`), it inherits the prose's ordering as an implicit dependency, and a failure in such a test is hard to read. It also cannot check the *shown output*, which is where the quickstart's existing falsehood is. +- **(c) A documented waiver.** Rejected: it leaves `AGENTS.md`'s claim that the quickstart's commands "are executed and verified, not illustrative" unbacked — which is the defect this plan exists to remove. A waiver is acceptable only as an interim state with an expiry and a named owner, and it must live where a reader of `AGENTS.md` would look. + +**Decision: (a), implemented through a checked-in script that the document embeds.** + +- The quickstart's executable steps live in a checked-in script (the plan names `scripts/quickstart.sh`, or an equivalent under `scripts/`), which the CI job runs end to end on Linux: build the daemon and the helper, generate the TLS material with `openssl`, install the helper under a trusted path, write the config, apply the documented modes, run `doctor`, start the node, run `status`, `executions list` and `storage summary`, stop the node, and then run the two `installed_qualification` tests with the `qualification` feature and the documented environment variables. +- `docs/quickstart.md` embeds the script's steps, and a check compares the document's command blocks with the script, so the document cannot drift from what CI runs. The document stays prose-first for a human reader; the script is the machine-checked form. +- The job must also check the document's *shown output*: at minimum, the set of `doctor` check names shown in the quickstart must equal the set the node actually reports. That check alone would have caught the present seven-versus-eight mismatch. +- The job's failure output must name the failing step, so a failing quickstart is diagnosable from CI alone. + +### 5.5 OP-6 — CI executes what it type-checks + +- **The qualification suite.** The `qualification`-feature tests must **execute** in CI. Adding `--all-features` to the CI test step is explicitly *not* the fix: the two `#[ignore]` attributes keep the tests from running regardless of the feature set, so a feature flag alone leaves the gap open. The plan requires one of: + - the quickstart CI job (§5.4) runs the two ignored qualification tests with `--ignored` and the documented environment — which it does by construction, since the quickstart's step 7 is exactly those tests; and + - the CI configuration states, in the workflow itself and in `architecture/ci-guardrails.md`, why the default `cargo test` step does not enable `qualification` and where the suite is executed instead. A reader of the workflow must not have to infer it. +- **The vacuous capability probe.** `crates/eggwork-runner/tests/capability_probe.rs` → `fn built_helper` must stop silently passing when it cannot find the helper. The plan requires the deterministic location the repository already uses elsewhere: `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` → `fn built_helper` resolves the helper through the compile-time `CARGO_BIN_EXE_` variable, and `crates/eggwork-server/src/lib.rs` → `fn locate_helper_binary` walks the current executable's sibling and grandparent. The runner crate cannot use `CARGO_BIN_EXE_eggwork-sandbox-helper` directly, because that variable is only provided to the package that owns the binary; the runner's test must therefore locate the helper deterministically relative to its own test executable, which lives under the target directory's `deps` directory. + - When the helper cannot be found, the test must **fail loudly** with a message naming the expected path and what to build — not return early and pass. Alternatively the test may be marked `#[ignore]` with a stated reason; the plan prefers the loud failure, because an `#[ignore]`d test is a hole rather than a check. + - The CI job that runs the runner's test targets must build the helper first (`cargo build --locked -p eggwork-sandbox-helper`), so the precondition holds. The `windows-runner` job currently runs `cargo test --locked -p eggwork-runner --all-targets` alone, which does not build the helper — so the plan requires that job to build it, or that the test's loud failure be explicitly expected there with the reason recorded. + - The test must be shown to be non-vacuous: the plan requires evidence that it fails when the helper is absent and passes when it is present. + +## 6. Failure, cancellation, restart, and contention semantics + +- **The harness must fail closed.** Every derivation in §5.1 is a check, not a hint: a manifest that cannot be parsed, a contract that cannot be read, an identity that cannot be resolved, a tag that does not match the manifest — each must stop the qualification, not produce a report that quietly omits the fact. The harness's existing failure semantics (a `QualificationFailure` with a fixed reason, no child-process output interpolated) are preserved. +- **The citation checker must fail closed.** An unreadable document, an unparsable citation, or a citation it cannot resolve must be a failure. It must never treat "cannot check" as "checked". +- **The CI jobs must fail loudly.** The quickstart job's failure must name the failing step; the runner capability probe must fail when its precondition is absent; the qualification suite must not be reported as green when it did not run. +- **Contention.** The qualification fixture takes an exclusive lock on the state directory, and the quickstart itself warns that a running node holds it. The quickstart CI job must use a state root that no other job or workflow uses, and must stop the node before running the fixture. Two CI jobs sharing a state root is a contention failure that must be designed out, not retried. +- **Restart.** The harness has no restart semantics of its own; it qualifies an installed tree and exits. The quickstart job's node start/stop must be bounded and must not leave a process behind, or the job's own step ordering fails on the lock. +- **No change** to the release workflow's own failure semantics, to the qualification receipt format, or to the operational-qualification workflow's structure. + +## 7. Compatibility and migration + +- **No released artifact format changes.** Asset names, install identities, target set, checksum sidecar names, and the binary version are unchanged. This plan changes only the harness's route to those facts. +- **No wire protocol changes.** Nothing in `eggwork-core`, `eggwork-client`, or the server's HTTP surface changes. +- **The release workflow file is unchanged.** `.github/workflows/release.yml` is generated by `eggpack ci generate`; it is never hand-edited, and `eggpack ci check` must continue to pass. The plan's CI changes are in `.github/workflows/ci.yml`, which is hand-maintained. +- **The producer configuration is unchanged.** `release/eggpack/` is Eggpack's; this plan reads it. +- **The harness's behaviour changes in one observable way:** if a fact in the tree and the harness's remembered copy of it disagree, the harness now follows the tree and the qualification stops with a specific failure, where before it might have passed. This is the intended behaviour change and it is why the harness's remembered copies must be removed rather than reconciled. +- **Operator-facing:** the quickstart's troubleshooting table and its `doctor` output block are corrected to match the node's actual behaviour. The quickstart's error-message quotes must not be edited by both this plan and M008a; the coupling is recorded in both plans and resolved by whichever lands second. +- **Migration:** none for operators. The release process gains a guard that was previously absent. + +## 8. Required tests + +- **Version reader.** A test in `tests/release/` proving the shared Python reader returns `[workspace.package].version` from a manifest whose `[workspace.package]` section is *not* first, and fails closed on a malformed manifest and on a manifest with no `[workspace.package].version`. This is the test that distinguishes a real TOML reader from the regex the current `check_release_tag.py` uses, and it must be shown to fail against the pre-change reader. +- **Tag guard.** Tests for `scripts/check_release_tag.py`: the tag matches the manifest version with and without the `v` prefix; a mismatched tag fails; the lock's pinned workspace versions are checked against the same value; a malformed manifest fails closed; a manifest with no `[workspace.package].version` fails closed; and a manifest whose `[workspace.package]` section is not first still yields the right version — the case the regex reader gets wrong. +- **CI exercise of the guard.** Evidence that an automated job executes the tag guard's logic against fixtures, and that the version-coherence half — the manifest against the lock — is asserted on every push and pull request. The point of the finding was that the guard was executed by no job at all, so "the script exists" is not evidence. +- **Version authority reconciliation.** A test proving the qualification harness's expected version equals the manifest version, and that a tag which disagrees with the manifest is refused by the gate rather than being used to derive the expected version. +- **Asset inventory.** A test proving the harness's expected asset set equals the set derived from the contract, and that no hardcoded count remains in the harness. The test should assert that the harness module contains no literal asset count — the kind of check that fails when someone re-adds one. +- **Install and service identities.** A test proving the harness resolves the install identities from the contract and the service identity from the daemon, and that the harness source contains no literal install or service identity string. +- **Target classification.** A test proving the classification of each target in the contract matches the contract's own asset entries, including the Linux targets that ship the helper and the macOS and Windows targets that do not. +- **Citation checker.** Tests for `scripts/check_doc_citations.py`: a correct citation passes; a citation naming a non-existent symbol fails; a citation naming a non-existent file fails; a legacy line-number citation fails; an ambiguous bare basename fails; a citation into a Python file resolves Python symbols. Plus the self-test fixture proving the checker rejects a deliberately wrong citation — the negative-exit proof. +- **Documentation gate.** A test or CI assertion that the citation checker runs over every document in `architecture/` and `docs/`, and that the design record contains no line-number citation at all. +- **Quickstart.** The CI job that executes the quickstart script is the test. Additionally, a check that the `doctor` check names shown in `docs/quickstart.md` match the node's reported check names, and that the quickstart's command blocks match the checked-in script. +- **Qualification execution.** Evidence that the `qualification`-feature tests execute in CI, and that the CI configuration records where they run and why the default test step does not run them. +- **Capability probe non-vacuity.** Evidence that `crates/eggwork-runner/tests/capability_probe.rs` fails when the helper binary is absent and passes when it is present, with the helper present in the CI job that runs it. + +## 9. Required verification + +The repository's pre-submit gate, run in full: + +``` +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +Plus the focused evidence: + +- `python3 scripts/check_doc_citations.py` over `architecture/` and `docs/`, run against the pre-change tree to show it fails, and after the conversion to show it passes; +- `python3 scripts/check_release_tag.py v0.1.5` (or the repository's current tag), which passes on the pre-change tree and must still pass after the reader changes — proving the new reader yields the same value the old one did by accident — together with the tag-guard tests, run against the pre-change script to show the regex reader's failure mode; +- `eggpack ci check --workflow-shape release/eggpack/workflow-shape.json --contract release/eggpack/distribution.toml --github-policy release/eggpack/github-policy.json --workflow .github/workflows/release.yml`, proving the generated workflow has not drifted; +- the release-harness tests in `tests/release/`, run before and after; +- the capability probe, run with the helper absent and with the helper present; +- the quickstart CI job, run end to end. + +`--locked` remains load-bearing on the clippy and test steps, and `git diff --check` remains part of the gate because the plan's own subject is citation hygiene and because `CONTRIBUTING.md`'s pre-submit list includes it. + +## 10. Documentation updates + +- `architecture/overview.md` — the component table's size column is removed and replaced by a pointer to the script that prints the current figures; the divergences table is re-verified entry by entry, with divergence #20 corrected or closed and the `doctor`-check-count entry reconciled; every line-number citation in the file is converted. +- `architecture/ci-guardrails.md` — the new CI job is documented: what it runs, what it proves, what it does not prove, and why the default test step does not enable `qualification`. The citation checker is documented alongside the ownership guard, with its scope and its limits stated honestly. +- `architecture/release-qualification.md` — the version-authority reconciliation is written down: which is the gate, which is the build assertion, and why they are permitted to differ. It must also state **where the tag-dependent gate runs today** — `scripts/check_release_tag.py`, run by whoever cuts the tag, before the tag exists — so that no reader mistakes "the guard is in the repository" for "the guard ran". The harness's derivation of the asset inventory, the install identities, and the target classification is documented as derivations from their owners, not as lists. +- `architecture/distribution.md` — updated only where it describes how the harness learns the release facts, so that it agrees with the code. +- `architecture/operations-cli.md`, `architecture/core-domain.md`, `architecture/server-node.md`, `architecture/runner-execution.md`, `architecture/data-plane.md`, `architecture/storage-journal.md`, `architecture/sandbox-helper.md`, `architecture/client-transport.md`, `architecture/deployment-lifecycle.md` — line-number citations converted to symbol citations; no other content changes except where a citation's surrounding sentence was itself wrong (the `doctor` check count in `operations-cli.md`). +- `docs/quickstart.md` — the executed steps are aligned with the checked-in script; the `doctor` output block is corrected to the eight checks the node actually reports; the document states how it is machine-verified and where. +- `docs/operations.md` — updated only if the quickstart or the harness changes anything it documents. +- `docs/releases.md` — updated only if the release-consumption story changes; this plan is expected not to change it. +- `AGENTS.md` — the claim that the quickstart's commands "are executed and verified" must be either made true by §5.4 or qualified. Leaving an unqualified claim that is still unbacked is not an acceptable outcome of this plan. +- No document in this repository gains a line-number citation as a result of this plan. This is the plan's own subject, and it must model the fix. + +## 11. Acceptance criteria + +1. The workspace version is read by exactly one Python implementation, using a real TOML parser scoped to `[workspace.package].version`, and every release script obtains it through that implementation. +2. `scripts/check_release_tag.py` reads the manifest and the lock through real TOML readers, has tests in `tests/release/`, and its logic is exercised by an automated CI job; the tag-dependent half is documented as running by whoever cuts the tag, since CI does not know the future tag. +3. The version authorities are reconciled in writing and in code: the manifest owns the version the binaries report; the tag↔version comparison is the release gate; the qualification harness no longer derives its expected version from the tag. +4. `QUALIFIED_ASSET_COUNT` and the harness's install- and service-identity constants are deleted, not re-synced. The harness contains no literal for any fact it asserts. +5. The harness's target classification is derived from `release/eggpack/distribution.toml`, not from string suffixes. +6. Every line-number citation in `architecture/*.md` is converted to a symbol citation; `docs/*.md` carries none. +7. A citation checker runs in CI, fails on a legacy line-number citation, fails on a missing symbol or a missing file, and is proven to fail on a deliberately wrong citation. +8. The `architecture/overview.md` component table carries no hand-written size figures; the current figures are obtainable from a checked-in script. +9. Every entry of the divergences table is re-verified; divergence #20 is corrected or closed; the `doctor`-check-count entry and the affected documents agree with the code. +10. The quickstart is executed by CI against a locally built node with generated TLS material, and the document's shown output is checked against the node's actual output — or, if the quickstart CI job cannot be landed, a waiver with an expiry and a named owner is recorded where a reader of `AGENTS.md` would look. +11. The `qualification`-feature tests execute in CI, and the CI configuration and `architecture/ci-guardrails.md` record where they run and why the default test step does not run them. +12. `crates/eggwork-runner/tests/capability_probe.rs` fails loudly when the helper is absent, passes when it is present, and is proven non-vacuous. +13. The full pre-submit gate passes; `eggpack ci check` passes against the unchanged generated workflow; the focused tests are demonstrated failing before the fix. +14. No released artifact format changes, no wire protocol changes, and no authentication, lease, generation, fencing, or digest bound is weakened. + +## 12. Stop conditions + +Stop and escalate rather than proceeding if: + +- wiring the tag guard into the *release* workflow would require hand-editing `.github/workflows/release.yml` — the file is generated and `eggpack ci check` must keep passing; the change goes through the producer configuration or it does not happen, and the upstream prerequisite is recorded instead; +- the producer configuration `release/eggpack/` would have to change to carry a fact this plan needs — that is Eggpack's file; record the prerequisite and escalate rather than editing it; +- the citation checker's rule set would have to be weakened (for example by allowing a bare basename, or by exempting a file) to make the conversion pass — a check with an exemption is a check that will be bypassed; resolve the ambiguity in the citations instead; +- the quickstart CI job cannot be made deterministic in the CI environment (for example because the helper's trusted-path requirement or the fixture's state-directory lock cannot be satisfied) — then the waiver route applies, and it must be recorded with an expiry and a named owner, not silently; +- executing the qualification suite in CI would require weakening an isolation, trust, or resource-enforcement bound, or would require a platform claim that was not probed; +- the harness's derivations would change any released fact — asset name, install identity, target set, or version. If a derivation disagrees with the tree, the *tree* is the owner and the disagreement is a finding to investigate, not a constant to update; +- the work would weaken the ownership guard, the `--locked` discipline, or the `--prove-negative-exit` self-test. + +## 13. Closure evidence required + +Create `plans/closure/operations-distribution/008b-status.md`. + +Per `plans/003-planning-process.md` §6, the record must distinguish code inspection from executed evidence and must include: + +- the reviewed repository head and the implementation commits; +- an executive finding; +- a requirement-to-evidence matrix mapping each acceptance criterion above to the specific command output or test that satisfies it; +- the exact focused and broader verification actually run, including the full pre-submit gate output and the `eggpack ci check` output; +- the platform matrix actually exercised, stated honestly — do not claim a platform was qualified merely because it compiles, and do not claim the qualification suite ran on a platform where it did not; +- negative and adversarial evidence: the citation checker shown failing on the pre-change tree and on a deliberately wrong fixture; the version reader shown failing on a manifest whose `[workspace.package]` is not first; the capability probe shown failing with the helper absent; the quickstart job shown failing when a step is broken; +- the release-visibility consequence: confirmation that no asset name, install identity, target set, or binary version changed, and that the generated workflow did not drift; +- documentation status, listing each document changed and each citation converted, with the before-and-after counts; +- the upstream prerequisite status for the release-path tag gate; +- unresolved findings ranked by severity; +- the registry and roadmap disposition. + +Do not claim tests were run when they were only inspected. Do not claim a platform or feature is qualified merely because its code compiles. + +## 14. Handoff notes + +- **M008b is `proposed`, not `ready`.** It has no unmet in-repo dependency, but it carries two decisions that need a human's judgement before implementation: the canonical citation form and the checker's rule set (§5.3), and the reconciliation of the two version authorities (§5.1), which is an ownership-boundary statement and therefore an architecture review item under `plans/003-planning-process.md` §8. Resolve those first. +- **M008b is independent of M007 and of M008a.** It may execute in parallel with M007, with M008a, and with the other corrective addenda in this planning batch. It does not touch the service-host lifecycle or the shutdown-and-wait convergence contract. +- **One coupling with M008a:** the quickstart's troubleshooting table quotes the configuration error text, and M008a changes that text. Whichever plan lands second must reconcile it; neither may edit it blind. This is recorded in both plans. +- The citation conversion is the bulk of the effort and the least interesting part. Land the checker *with* the conversion, not after it: a checker that is added before the citations are converted will fail the build, and that is the correct outcome — a gate that only turns on when the tree is already clean protects nothing. +- The release-harness work is the part with the highest blast radius, because it decides what a release is allowed to contain. The discipline that matters is that the harness's remembered copies are **deleted** rather than reconciled: a constant that is updated when it disagrees is still a second owner, and it will drift again. +- The repository's own experience is that a rule written in one module and re-implemented in another has drifted before, and the drift was found by inspection rather than by a failing test. Prefer the test that fails when the rule is weakened, over a comment that describes the rule — that is the whole shape of OP-4 and OP-6. +- The quickstart job is the most expensive item here and the one that most directly discharges an unbacked claim in `AGENTS.md`. If it turns out to be too expensive to land as part of this milestone, take the waiver route and record it honestly rather than letting the claim stand unbacked. diff --git a/plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md b/plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md new file mode 100644 index 0000000..4111593 --- /dev/null +++ b/plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md @@ -0,0 +1,266 @@ +# Security M005a — Degraded isolation observability corrective + +Status: proposed + +Closure record: `plans/closure/security-isolation-resource/005a-status.md` + +Class: invariant + +Source authority: + +- `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` — finding SI-1 +- `plans/subsystems/security-isolation-resource-roadmap.md` — the subsystem's durable invariants, including "Isolation claims are earned" +- `plans/closure/security-isolation-resource/004-status.md` — security closure +- `plans/closure/security-isolation-resource-remote-admission-corrective/001-status.md` — the remote-admission and capability-truthfulness corrective (C001) +- `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` — decision 10: "Sandbox helper and resource-controller helper boundaries remain beneath the runner and must fail closed when required" +- `plans/security/threat-model.md` — the standing threat model +- `plans/003-planning-process.md#verification-philosophy` + +## 1. Objective + +Make a degraded isolation or resource enforcement observable **in the event stream**, not only in the terminal snapshot, and make the terminal state non-misleading for a caller that never polls a snapshot. + +Concretely: when a best-effort isolation or resource request could not be enforced, the execution's event stream must carry a diagnostic event that states the class of degradation and a bounded reason. That diagnostic must reach the caller **before the target produces any output** and **before the terminal event**. A `Required` request that cannot be satisfied must continue to fail closed before the target process starts, exactly as it does today. + +## 2. Baseline / problem statement + +At the reviewed baseline: + +- `crates/eggwork-core/src/lib.rs` defines `ExecutionEventKind::Diagnostic(String)` — the only event kind that is neither a state transition nor target output. It is the carrier this milestone uses. Its wire shape does not change. +- `ExecutionEvent::validate` in the same file bounds a diagnostic payload by `MAX_EVENT_CHUNK_BYTES` (64 KiB). `EventMetadata::validate` bounds a metadata field count by `MAX_METADATA_COUNT` (64) and each value by `MAX_METADATA_VALUE_BYTES` (2048). +- `ExecutionEventKind::Diagnostic` is constructed in exactly three places in the workspace, all of them test code: twice inside the `#[cfg(test)] mod tests` block of `crates/eggwork-server/src/lib.rs`, and once inside the `#[cfg(test)] mod tests` block of `crates/eggwork-server/src/store.rs` (a payload-length probe). **There is no production diagnostic event in the repository.** +- The degradation itself *is* recorded. `crates/eggwork-runner/src/lib.rs` produces `SandboxOutcome::NotApplied { reason }` from `TrustedLandlockSetup::prepare` for an unsupported sandbox profile and for an untrusted helper, `ResourceSetupOutcome::NotApplied { reason }` when the cgroup backend probe fails or when the helper cannot be trusted for the resource path, and `RunnerResult::execution_result` maps both onto `eggwork_core::SandboxResult::NotApplied` and `eggwork_core::ResourceDimensionResult::NotApplied`. The server carries them into `ExecutionResult`. +- The runner's degradation paths are, in `LocalProcessRunner::run` in `crates/eggwork-runner/src/lib.rs`: + - an unsupported sandbox profile — decided in `ExecutionSetup::prepare`, before any process exists; + - an untrusted helper — decided in `ExecutionSetup::prepare`, before any process exists; + - no backend configured (`NoExecutionSetup`) — decided in `ExecutionSetup::prepare`, before any process exists; + - a resource-backend probe failure — decided in `ExecutionSetup::prepare`, before any process exists; + - a helper handshake failure — decided **after** the helper process was spawned as the tree leader. `SandboxChannel::wait` returning `Ok(None)`, or `Err(SandboxWaitError::BeforeTarget(..))`, causes the runner to kill the helper tree, rewrite `setup.sandbox` and `setup.resources` to `NotApplied`, and **re-spawn the target directly through `direct_command`, bypassing the helper entirely**. The target then runs with no Landlock ruleset and no cgroup verification. + - a helper-reported unobservable counter (`STATUS_UNOBSERVED` in the helper) — the runner turns this into `NotApplied` for the affected resource dimension. +- The server publishes events in `run_execution` in `crates/eggwork-server/src/lib.rs`: a `State(Running)` event, then one event per output chunk forwarded from the runner's output channel, then the terminal event through `publish_terminal`. +- `publish` in the same file returns early when the recorded base state is already terminal, and `store::ExecutionStore::commit_event` refuses to append to a terminal execution. **A diagnostic published after the terminal event is silently dropped.** The ordering requirement is therefore a correctness requirement, not a style preference. +- The `Required` path is already truthful in the stream and must not change. When a required setup cannot be satisfied, the runner returns an error before the target starts; the server's `failed_result` synthesizes `SandboxResult::Failed { reason: "required sandbox setup failed" }` and a `Failed` terminal event. The gap this milestone closes is the *successful* execution whose isolation was degraded, where the terminal event says only "succeeded". +- `crates/eggwork-client/src/lib.rs`'s `ExecutionStream::into_events` already yields any `ExecutionEvent`, including a diagnostic, so a client can receive the new event without a transport change. + +## 3. Scope + +In scope: + +- the production emission of `ExecutionEventKind::Diagnostic` from the execution path in `crates/eggwork-server/src/lib.rs`; +- the runner-side surfacing of a degradation so that the ordering guarantee can be met — specifically `crates/eggwork-runner/src/lib.rs`'s `LocalProcessRunner::run`, its `ExecutionSetup::prepare` implementations (`TrustedLandlockSetup`, `NoExecutionSetup`), and the helper-handshake recovery path; +- the runner's public `OutputChunk` type, if the ordering guarantee requires it (see §5); +- the payload grammar and bounds for the diagnostic; +- the server's event-publication ordering relative to the terminal event; +- the corresponding documentation in `architecture/runner-execution.md`, `architecture/server-node.md`, and `architecture/sandbox-helper.md`. + +Out of scope: + +- any change to the wire representation of `ExecutionEventKind`, `ExecutionResult`, `SandboxResult`, or `ResourceResult`. The wire contract belongs to the control-plane shared-contract corrective, and M005a must not collide with it; +- any change to the `Required` path's semantics — a required request still fails closed before the target process starts, and this milestone may not soften that; +- the environment deny-list and the `PATH` rule, which belong to M005b; +- resource-scoped authorization, which belongs to M005c and is blocked on an ADR; +- the `eggwork-client` crate's transport, retries, or egress routing. A client-side convenience accessor is permitted but not required; +- the server's own diagnostics (configuration faults, admission refusals) — this milestone is scoped to the *execution* event stream; +- any change to the isolation, resource, admission, or lease semantics themselves. + +## 4. Invariants and non-goals + +Invariants that must hold after M005a: + +1. A best-effort isolation or resource request that could not be enforced produces a diagnostic event in the execution's event stream. +2. The diagnostic event precedes the terminal event, and precedes any stdout or stderr event of the target. +3. The diagnostic payload is bounded, machine-readable, and carries the degradation class and a bounded reason. +4. A `Required` isolation or resource request that cannot be satisfied still fails closed **before the target process starts**, and its terminal state is unchanged. +5. A `Required` failure is never reported as a degradation. A diagnostic is not a substitute for a refusal. +6. An execution whose isolation and resources were fully applied emits no diagnostic event. +7. The diagnostic is durable: it is committed to the execution journal and is visible to a client that connects after the execution finished and replays the event page. +8. `ExecutionEventKind`'s wire representation is unchanged. +9. The runner remains the single owner of production finite noninteractive process creation. +10. The server does not create a child process on any path added by this milestone. + +Non-goals: + +- redesigning the event protocol, the event metadata shape, or the client API; +- adding new isolation or resource enforcement mechanisms; +- making the node *fail* on a best-effort degradation — best-effort degradation must remain permitted, and must merely become visible; +- reporting anything about the target's own behaviour, exit status, or output beyond the degradation itself; +- exposing the reason strings verbatim without bounds — they are operator-facing text and must be truncated to a documented limit. + +## 5. Required production changes + +1. **Define the diagnostic payload grammar.** The diagnostic is carried by the existing `ExecutionEventKind::Diagnostic(String)` variant. Its payload MUST be a single string with a documented, stable grammar of the form: + + ```text + eggwork.diagnostic..v1 key=value key=value … + ``` + + `` is drawn from a closed set owned by this milestone: + + | Class | Meaning | + |---|---| + | `isolation.degraded` | a requested best-effort filesystem isolation was not applied | + | `resources.degraded` | a requested best-effort resource enforcement was not applied | + + The minimum key set is `class`, `requirement` (always `best_effort` for a degradation), and `reason`. `isolation.degraded` additionally carries `profile` (the requested profile) when one was requested. `resources.degraded` carries `dimension` (the affected `ResourceDimension`) when a single dimension is affected, and one event per affected dimension when more than one is. + + The payload MUST be at most `MAX_METADATA_VALUE_BYTES` (2048) bytes so it stays inside the same bound as any event-metadata value, and therefore trivially inside `MAX_EVENT_CHUNK_BYTES`. The reason text MUST be truncated to fit that bound, and the truncation MUST be observable in the payload rather than silent. + +2. **Decide where the diagnostic is produced and state it in the closure record.** The expected mechanism is that the runner surfaces the degradation through its output channel, before it spawns the target, and the server's forwarding loop in `run_execution` maps that chunk to `ExecutionEventKind::Diagnostic`. This is the only mechanism that can satisfy invariant 2 in full, because the server's `run_execution` learns the outcome from the runner's `RunnerResult` only **after** the execution has already finished — a server-side diagnostic derived from `RunnerResult` would necessarily arrive after all target output. A server-side mechanism that publishes the diagnostic from `RunnerResult` immediately before `publish_terminal` is permitted only as a fallback, and the closure record MUST state which mechanism was chosen and why. + + If the runner-side mechanism is chosen, `crates/eggwork-runner/src/lib.rs`'s public `OutputChunk` type gains a diagnostic variant. That is a public-API change to a published crate; see §7. + +3. **Emit the diagnostic exactly once per degradation.** A single degraded dimension produces exactly one diagnostic event. A degraded isolation and a degraded resource enforcement produce two events, each naming its own class. The diagnostic MUST NOT be duplicated by both the runner and the server. + +4. **Emit the diagnostic before the target starts, in every degradation path.** For the degradations decided in `ExecutionSetup::prepare` — unsupported profile, untrusted helper, no backend, resource probe failure — the diagnostic is emitted before the target process exists. For the helper-handshake recovery path, the helper process was already spawned as the tree leader, but the helper refused to start the target; the runner MUST emit the diagnostic after the handshake failure is classified and **before** it re-spawns the target directly. The target therefore never starts without the caller having already been told. + +5. **Publish the diagnostic before the terminal event.** The publication point in `run_execution` MUST be before `publish_terminal`, because `publish` returns early on a terminal base state and the event would be silently dropped. The implementer MUST verify this by asserting on event sequence numbers, not by inspection. + +6. **Leave the `Required` path's behaviour unchanged.** The runner's `Required` branches — the `Err(RunnerError::Setup(..))` returns in `TrustedLandlockSetup::prepare`, the `RunnerError::RequiredSetupUnavailable` returns in `LocalProcessRunner::run`, and the `Ok(None)` arm that kills the helper tree — MUST keep their current semantics and their current terminal classification. No diagnostic may be used to convert a required refusal into a degraded execution. A diagnostic MAY additionally be emitted on the `Required` path to explain the refusal, provided it does not change the terminal state and provided the closure record states that the path was otherwise untouched; this milestone does not require it. + +7. **Keep the terminal snapshot's evidence.** `ExecutionResult.sandbox` and `ExecutionResult.resources` continue to carry `NotApplied { reason }` exactly as they do today. The diagnostic is additive; the snapshot is not replaced by it. + +8. **Keep the journal complete.** The diagnostic is committed through the existing `commit_event` path so it is durable and replayable, and it must carry a sequence number consistent with the rest of the execution's event sequence. + +9. **Keep the client able to receive it.** Confirm that `ExecutionStream::into_events` in `crates/eggwork-client/src/lib.rs` surfaces the diagnostic unchanged. If a typed convenience accessor is added, it must not change the transport. + +10. **Document the grammar.** The closed class set, the key set, the bound, and the truncation rule must be written down where an operator or a client author will find them — `architecture/protocol.md` for the grammar, `docs/` only if an operator-facing behaviour changes (it does not: the operator surface is unchanged). + +## 6. Failure, cancellation, restart, and contention semantics + +- **Cancellation before spawn.** `RunnerError::CancelledBeforeSpawn` must not be reported as a degradation. A cancelled execution must not emit an `isolation.degraded` or `resources.degraded` diagnostic. +- **Cancellation after spawn.** A degraded execution that is then cancelled still emits its diagnostic — the degradation happened and is still true. The diagnostic precedes the terminal `Cancelled`/`Interrupted` event. +- **Lease expiry.** The server rewrites a successful runner result in place to `Interrupted`/`LeaseExpired`. A diagnostic emitted before that rewrite stays in the stream; it is not retracted, because the degradation really occurred. +- **Timeout and output-limit termination.** The diagnostic is emitted at setup time and is unaffected by a later timeout or output-limit termination. +- **Runner error.** When the runner returns an error, there is no `RunnerResult` and therefore no degradation to report from the result. If the degradation was already observed at setup time and the diagnostic was emitted, it stands. The server's `failed_result` path is unchanged. +- **Event-publication failure.** If `commit_event` fails, the existing behaviour applies — the server marks the execution draining and cancels. The diagnostic must not change that. +- **Restart and recovery.** The diagnostic is part of the durable journal, so a client that reconnects after a node restart sees it in the replayed event page. +- **Contention.** The diagnostic occupies one event sequence number and one journal row. It must not change the ordering guarantees of the state machine or the existing per-execution event trimming. +- **Ordering under the `biased` select.** `run_execution`'s output-forwarding loop is `biased` and drains the runner's output channel before observing the runner task's completion. A diagnostic delivered through that channel is therefore forwarded before the terminal publication, deterministically. + +## 7. Compatibility and migration + +**Wire protocol.** No change. `ExecutionEventKind::Diagnostic(String)` already exists in the wire contract and is already decodable by `eggwork-client`. This milestone makes a previously-unused variant appear in production traffic. + +**Client behaviour.** A client that today assumes the event stream contains only `State`, `Stdout`, and `Stderr` kinds must be updated to tolerate `Diagnostic`. That is the intended correction and is a client-side behaviour change. The change is additive at the transport level: an older client decoding the stream still receives a well-formed event, but a client that treats an unknown kind as fatal would break. The implementer MUST state, in the closure record, whether the repository's own client tolerates it (it does — `into_events` yields every kind) and MUST flag the external-client consequence explicitly. + +**Public Rust API.** If the runner-side mechanism is chosen, `crates/eggwork-runner/src/lib.rs`'s public `OutputChunk` struct gains a variant. `OutputChunk` currently has exactly two construction sites in the workspace — the runner's own producer and one server test helper — so the in-tree blast radius is small, but the type is public in a published crate and the change is release-visible. It MUST be handled as a version-visible change and MUST NOT be bundled silently into a release that claims to be a qualification-only candidate. + +**Operator surface.** Unchanged. `eggworkd` verbs, the node's capability advertisement, and the deployment trust checks are not touched. The capability advertisement already reflects the *node's* ability to enforce isolation (`verify_trusted_helper` and `probe_landlock_ruleset`), not any individual execution's degradation, and must not be changed to carry per-execution state. + +## 8. Required tests + +Required, and each must be non-vacuous — a test that would still pass if the feature were removed is not acceptable. + +1. **A degraded best-effort execution emits the diagnostic.** A server-level integration test that submits an execution with a best-effort sandbox request against a node whose runner is constructed with an explicit, deterministic setup that cannot enforce isolation — `LocalProcessRunner::new(NoExecutionSetup)` in `crates/eggwork-runner/src/lib.rs`, whose `ExecutionSetup::prepare` returns `SandboxOutcome::NotApplied { reason: "no sandbox backend is configured" }` for a best-effort request — and then asserts that the execution's events contain an `ExecutionEventKind::Diagnostic` whose payload carries the `isolation.degraded` class. + + The test MUST use an explicitly constructed setup, not `LocalProcessRunner::default()`: on Linux the default discovers a sibling helper next to the test binary and on other platforms it uses `NoExecutionSetup`, so the default's behaviour is environment-dependent and the test would not be deterministic. + +2. **The diagnostic precedes the terminal event.** The same test MUST assert on sequence numbers: the diagnostic's sequence number is strictly less than the terminal event's sequence number. + +3. **The diagnostic precedes any target output.** The same test MUST run a target that writes to stdout, and assert that the diagnostic's sequence number is strictly less than the first `Stdout` event's sequence number. This is the assertion that fails if the diagnostic is produced from the runner's `RunnerResult` instead of from the setup path, so it must be present and must not be weakened to "the diagnostic exists somewhere in the stream". + +4. **A `Required` execution never reaches the target.** A test that submits an execution with a required sandbox request against the same deterministic setup, and asserts that the target's observable side effect never happened — the child must not have created its marker file, and the terminal state must be a failure, not a success. The assertion must be on the side effect, not merely on the terminal state. + +5. **The `Required` path's terminal classification is unchanged.** A test asserting that a required setup failure still yields `ExecutionFailure`/`ExecutionState` exactly as it does at the reviewed baseline, so that no future change can quietly convert a required refusal into a best-effort degradation. + +6. **No diagnostic when nothing degraded.** A test proving that an execution with no isolation and no resource request, or with both fully applied, emits no diagnostic event. Without this test, a diagnostic emitted on every execution would pass tests 1–5. + +7. **Payload bounds and grammar.** A test proving that the diagnostic payload is at most `MAX_METADATA_VALUE_BYTES` bytes, that it begins with the documented `eggwork.diagnostic..v1` prefix, that `` is one of the closed set, and that an over-long reason is truncated in a documented way rather than silently. + +8. **The diagnostic is durable and replayable.** A test that reads the execution's event page after the execution has finished and finds the diagnostic, proving it was committed to the journal and not merely broadcast to a live subscriber. + +9. **Resource degradation.** A test that induces a best-effort resource degradation — the cgroup backend probe failing, or the helper reporting an unobservable counter — and asserts a `resources.degraded` diagnostic naming the affected dimension. + +10. **Cancellation does not produce a false degradation.** A test proving that an execution cancelled before spawn emits no diagnostic. + +11. **No behavioural regression.** The existing server and runner suites remain green and unchanged, including the runner's timeout, cancellation, output-limit, and process-tree tests, and the server's existing event-ordering tests. + +## 9. Required verification + +At minimum: + +```text +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +`--locked` is load-bearing on both `clippy` and `test`: a version bump that skips `Cargo.lock` passes both and then fails every release build. + +The verification must prove the *ordering* property, not merely the presence of a diagnostic. A test that asserts "the stream contains a diagnostic" without asserting sequence numbers does not satisfy this milestone. + +If the runner's public `OutputChunk` type changes, the change must also be exercised on the Windows and macOS targets the release matrix builds, because the runner has platform-specific spawn paths and the diagnostic sits in front of all of them. Record the platform matrix actually exercised, honestly: do not claim a platform was qualified merely because it compiles. + +## 10. Documentation updates + +- `architecture/protocol.md` — document the diagnostic payload grammar, the closed class set, the key set, the bound, and the truncation rule. +- `architecture/runner-execution.md` — describe where the runner emits a degradation and when, replacing the current prose that implies the degradation is only visible in the terminal result. +- `architecture/server-node.md` — describe the publication point and the ordering guarantee relative to the terminal event, and the fact that a post-terminal publication would be dropped. +- `architecture/sandbox-helper.md` — note the helper-handshake recovery path's degradation and where it is now reported. +- `architecture/overview.md` — add a divergence row only if a residual divergence remains after M005a; if the truthfulness gap is closed, do not add a row. Divergence #5 (the weaker deployment-path helper-trust check) is a separate, still-open item and must not be closed by this milestone. +- `AGENTS.md` — the hard-invariant list does not need a new entry; if the "Isolation claims are earned" line is extended, extend it in the same wording style and keep it true. +- `plans/subsystems/security-isolation-resource-roadmap.md` — add the M005a milestone entry and set the roadmap's status line to reflect it. +- `plans/registry.md` — updated by the registry owner when the milestone is registered; this plan does not edit it. + +## 11. Acceptance criteria + +1. A best-effort isolation or resource request that could not be enforced produces a diagnostic event in the execution's event stream. +2. The diagnostic's sequence number is strictly less than the terminal event's sequence number. +3. The diagnostic's sequence number is strictly less than the first stdout/stderr event's sequence number. +4. The diagnostic payload matches the documented grammar, names the degradation class, and is at most `MAX_METADATA_VALUE_BYTES` bytes. +5. A `Required` request still fails closed before the target process starts, proven by an assertion on the target's side effect. +6. A `Required` request's terminal classification is unchanged from the reviewed baseline. +7. An execution with nothing degraded emits no diagnostic. +8. The diagnostic is durable and appears in a replayed event page. +9. No wire representation changed; `ExecutionEventKind` keeps its current shape. +10. The server creates no child process on any path added by this milestone. +11. The runner's public API change, if any, is enumerated and reflected in the release version and notes. +12. `architecture/protocol.md`, `architecture/runner-execution.md`, `architecture/server-node.md`, and `architecture/sandbox-helper.md` match the code. +13. The full pre-submit gate is green on the reviewed head. + +## 12. Stop conditions + +Stop and re-plan, recording the blocker, if any of the following occurs: + +- meeting the ordering requirement would require changing the wire representation of `ExecutionEventKind`, which belongs to the control-plane shared-contract corrective; +- meeting the ordering requirement would require the server to spawn or inspect a child process, which would break the process-ownership invariant; +- the diagnostic would have to carry data that is not already available at the point of emission — in particular, the diagnostic must not be reconstructed from the terminal snapshot after the fact, because that reintroduces the gap; +- the runner-side mechanism would require the sandbox helper to gain a workspace-crate dependency, which M005b owns and the helper's standalone-binary rule forbids; +- the implementation would change the `Required` path's behaviour in any way, including only its diagnostic; +- a degraded execution would begin emitting a diagnostic that could be mistaken for a terminal failure by an existing client, and the distinction cannot be made unambiguous in the payload; +- the milestone cannot be completed without weakening an authentication, lease, generation, fencing, or digest bound; +- the capability advertisement would have to change to carry per-execution degradation state, which would make a node-level advertisement depend on an execution's outcome. + +## 13. Closure evidence required + +Create: + +- `plans/closure/security-isolation-resource/005a-status.md` + +Per `plans/003-planning-process.md` §6, the record must distinguish code inspection from executed evidence and must include: + +- the reviewed repository head and the implementation commits; +- an executive finding; +- a requirement-to-evidence matrix mapping each acceptance criterion above to the specific command output or test that satisfies it; +- the exact focused and broader verification actually run, including the full pre-submit gate output; +- the platform matrix actually exercised, stated honestly — do not claim a platform was qualified merely because its code compiles; +- negative and adversarial evidence: the ordering assertions shown to fail against the pre-corrective behaviour (or against a deliberately reordered implementation) and pass after it, and the `Required` side-effect assertion shown to pass; +- the chosen emission mechanism and the reason for choosing it, including the compatibility consequence of any public runner API change; +- the diagnostic payload grammar as implemented, with the bound and the truncation rule; +- documentation status, including the four deep dives; +- unresolved findings ranked by severity; +- the registry and roadmap disposition. + +Do not claim tests were run when they were only inspected. Do not claim a platform or feature is qualified merely because its code compiles. + +## 14. Handoff notes + +- This milestone is independent of M005b and M005c and may be executed in parallel with them, with the foundation runner-request-validation corrective, with the control-plane shared-contract corrective, and with Operations M007. +- The hard part is not emitting an event; it is emitting it **in the right order**. Read §5.4 and §5.5 before choosing a mechanism, because the obvious implementation — deriving the diagnostic from the runner's result inside the server — satisfies "the stream contains a diagnostic" and still fails the milestone. +- The repository's own experience is that a claim written in one module and re-implemented in another drifts, and that the drift was found by inspection rather than by a failing test. The ordering assertions in §8 are the part that must not be skipped. +- The `Required` path is the safety property this milestone must not damage. If a change to it ever looks necessary, that is a stop condition, not a task. +- The wire contract is not this milestone's to change. If a structured diagnostic payload appears to need a new event variant, stop and hand the question to the control-plane shared-contract corrective rather than widening the protocol here. diff --git a/plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md b/plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md new file mode 100644 index 0000000..216a487 --- /dev/null +++ b/plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md @@ -0,0 +1,306 @@ +# Security M005b — Sandbox-helper environment parity corrective + +Status: proposed + +Closure record: `plans/closure/security-isolation-resource/005b-status.md` + +Class: invariant + +Source authority: + +- `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` — finding SI-2 +- `plans/subsystems/security-isolation-resource-roadmap.md` — the subsystem's durable invariants, including "Isolation claims are earned" +- `plans/closure/security-isolation-resource/002-status.md` — Landlock runtime and `/dev/null` handling +- `plans/closure/security-isolation-resource/003-status.md` — enforced resource controls +- `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` — decision 10: "Sandbox helper and resource-controller helper boundaries remain beneath the runner and must fail closed when required" +- `architecture/sandbox-helper.md` — the standalone-binary rule and the helper's dependency surface +- `AGENTS.md` — hard invariant 3 (crate dependencies stay one-way: core/helper → nothing) +- `plans/003-planning-process.md#verification-philosophy` + +## 1. Objective + +Give the sandbox environment policy — the denied-key list, the matching rule, the node-owned baseline keys, and the `PATH` value contract — **one owner**, consumed by both the runner and the standalone sandbox helper, without giving the helper a workspace-crate dependency, and make a one-sided edit fail the build instead of silently changing what is enforced. + +The milestone also closes the live hole that the duplication makes reachable: at the reviewed baseline, a caller-supplied environment key that collides with the node's own baseline produces a launch specification the helper refuses, which a best-effort execution silently answers by running the target **unconfined**. + +## 2. Baseline / problem statement + +At the reviewed baseline: + +- `crates/eggwork-runner/src/lib.rs` defines `fn denied_environment_key(key: &str) -> bool`. `crates/eggwork-sandbox-helper/src/main.rs` defines its own `fn denied_environment_key(key: &str) -> bool` inside `mod linux`. The two lists are **element-for-element identical**: the same 21 entries in the same order — `LD_`, `DYLD_`, `PATH`, `IFS`, `SHELLOPTS`, `CDPATH`, `BASH_ENV`, `ENV`, `PYTHONPATH`, `PYTHONHOME`, `NODE_OPTIONS`, `RUBYOPT`, `PERL5OPT`, `GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_CONFIG`, `GIT_CONFIG_`, `AWS_`, `AZURE_`, `GOOGLE_`, `SSH_AUTH_SOCK` — matched by the same rule: uppercase the key with ASCII rules, then `upper == denied || upper.starts_with(denied)`. +- Two properties of the rule are worth recording, because a parity fix must preserve them: `GIT_CONFIG_` is redundant, because the `GIT_CONFIG` prefix already covers `GIT_CONFIG_GLOBAL` and its relatives; and because the match is prefix-based, `PATH` denies *any* key beginning with `PATH`, not only `PATH` itself. +- **The semantics differ, and they differ in the dangerous direction.** + - The runner **drops**. `direct_command` in `crates/eggwork-runner/src/lib.rs` calls `command.env_clear()`, installs `baseline_child_environment`, and then installs each caller-supplied entry for which `denied_environment_key` is false. `SandboxChannel::new` does the same for the helper's launch specification. + - The helper **refuses the whole launch**. `read_spec` in `crates/eggwork-sandbox-helper/src/main.rs` rejects a specification whose environment contains a denied key (`denied_environment_key(key) && key != "PATH"`) or whose `PATH` is not exactly `/usr/bin:/bin` (`key == "PATH" && value != "/usr/bin:/bin"`), returning status code 12. `SandboxChannel::wait` in the runner reads a status byte of 4 or above as `RunnerError::Setup("sandbox helper rejected its launch specification (status {code})")`, delivered as `SandboxWaitError::BeforeTarget`. +- The helper's `PATH` rule has **no runner counterpart**. The runner satisfies it only incidentally, through the non-Windows branch of `baseline_child_environment`, which sets `PATH` to `/usr/bin:/bin`. The Windows branch sets `PATH` to `%SystemRoot%\System32;%SystemRoot%` and adds `SystemRoot` and `windir`. The helper is Linux-only (`#[cfg(target_os = "linux")] mod linux`), so the Windows shape never reaches it — but the rule is a property of the helper's environment contract and it is written in only one of the two places that own the environment. +- **The duplication is architecturally forced.** `crates/eggwork-sandbox-helper/Cargo.toml` declares no workspace-crate production dependency — only `serde`, `serde_json`, and the target-scoped `landlock` and `nix`. `architecture/sandbox-helper.md` states the rule and its reason: the helper is the trusted artifact that is staged, trust-verified, and run under its own rules, and its shipped dependency surface is deliberately kept to serde/serde_json plus one sandbox crate. `AGENTS.md`'s hard invariant 3 says the same thing in one line: "core/helper → nothing". The fix therefore cannot be "share a crate". +- **A live consequence follows from the duplication being invisible.** The runner's launch-specification builder starts from a fixed baseline — `PATH`, `LANG`, `LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER` — and then appends every caller-supplied entry that is not denied. None of `LANG`, `LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER` is on the deny-list, and `CommandSpec::validate` in `crates/eggwork-core/src/lib.rs` rejects only duplicates *within the caller's own* environment, not a collision with the node's baseline. A caller that sets `LANG` therefore produces a launch specification with two `LANG` entries. `read_spec` in the helper rejects a specification whose environment contains duplicate keys, returning status code 12. The runner reads that as a setup failure before the target, and — for a best-effort request only — kills the helper tree, rewrites `setup.sandbox` to `NotApplied`, and **re-spawns the target directly through `direct_command`, with no Landlock ruleset at all**. + The observable behaviour today is therefore: a caller that sets `LANG=en_US.UTF-8` gets a successful execution that was never confined, and the only record of the degradation is `ExecutionResult.sandbox`'s `NotApplied { reason }` in the terminal snapshot. M005a is the milestone that makes that degradation visible; M005b is the milestone that stops it happening for a key the caller was never going to be denied. +- **Two further duplications sit in the same code and are the same class of defect.** + - The node-owned baseline is written **twice inside the runner**: `baseline_child_environment` produces the direct child's environment, and `SandboxChannel::new` writes a second, separate literal list for the helper's launch specification. The two carry the same eight keys and the same values on Linux and nothing keeps them in step. `SandboxChannel::command` writes a third, shorter literal for the helper *process's own* environment. + - The protocol limit constants are duplicated from `eggwork-core` into the helper: `MAX_ARG_COUNT`, `MAX_ARG_BYTES`, `MAX_ENV_COUNT`, `MAX_ENV_NAME_BYTES`, and `MAX_ENV_VALUE_BYTES` are re-declared in `crates/eggwork-sandbox-helper/src/main.rs` with the same values that `crates/eggwork-core/src/lib.rs` exports and that `crates/eggwork-runner/src/lib.rs` imports. (`MAX_SPEC_BYTES` is helper-only and has no core counterpart.) +- **The repository already holds the pattern this milestone generalizes.** `crates/eggwork-runner/tests/windows_process_tree.rs` keeps a hand-maintained `BASELINE_KEYS` list beside the runner's own `baseline_child_environment`, with the comment: *"Kept in sync with `baseline_child_environment` in the crate; a mismatch is a contract change, not a test fix."* That is a comment, not a gate. M005b turns it into a gate. + +## 3. Scope + +In scope: + +- the denied-key list and its matching rule, in `crates/eggwork-runner/src/lib.rs` and `crates/eggwork-sandbox-helper/src/main.rs`; +- the `PATH` value rule, which currently exists only in the helper; +- the node-owned baseline environment, which is currently written three times in the runner and once implicitly in the helper; +- the rule that governs a caller-supplied key that collides with a node-owned baseline key — the cause of the live unconfined-execution hole described in §2; +- the helper's exit status for an environment-policy refusal, which is currently indistinguishable from several other specification-validation failures; +- the duplicated protocol limit constants in the helper, insofar as the milestone's mechanism makes them cheap to pin; +- the corresponding documentation in `architecture/sandbox-helper.md`, `architecture/runner-execution.md`, and `architecture/data-plane.md` if the data-plane deep dive describes the environment. + +Out of scope: + +- any change to the **content** of the denied-key list. M005b is an ownership and enforcement milestone, not a policy-tightening milestone. Adding or removing an entry is a separate decision with its own security review; the closure record must state that the entry set was carried over unchanged, and must list the entries as they stand. +- any change to the `Required` path's semantics. A required request still fails closed before the target starts. +- any change to the wire representation of `ExecutionEventKind`, `ExecutionResult`, `SandboxResult`, or `ResourceResult`; +- the diagnostic event itself, which belongs to M005a; +- resource-scoped authorization, which belongs to M005c and is blocked on an ADR; +- the Landlock ruleset, the cgroup verification, and the helper's status protocol, except for the environment-policy exit status named above; +- any new dependency for the helper, including a dev-dependency on a workspace crate for production code; +- the foundation runner-request-validation corrective, which changes request *validation* and is independent of this milestone. + +## 4. Invariants and non-goals + +Invariants that must hold after M005b: + +1. The denied-key list and the matching rule have exactly one owner. +2. The sandbox helper has no workspace-crate production dependency, and none is introduced. +3. Neither the runner's nor the helper's build reads a file from outside its own crate directory. +4. The runner's and the helper's effective environment policies agree, element-wise and rule-wise, and a test proves it. +5. A one-sided edit to either copy fails the build. +6. The runner drops a denied key; the helper refuses a launch that contains one. That difference is a deliberate two-layer contract, documented on both sides. +7. The helper refuses a launch whose `PATH` is not exactly `/usr/bin:/bin`, and the runner guarantees that value on every path that reaches the helper. +8. A caller-supplied key that collides with a node-owned baseline key does not produce a launch specification with duplicate keys, and does not cause a best-effort execution to lose its confinement. +9. The node-owned baseline environment is written once, not three times. +10. The `Required` path still fails closed before the target process starts. +11. The helper's environment-policy refusal is distinguishable, by exit status, from the other specification-validation failures. +12. The duplicated protocol limit constants agree with their `eggwork-core` owners. + +Non-goals: + +- tightening the environment policy — M005b makes the existing policy single-sourced and enforced, not stricter; +- changing what the child process may do, beyond what the shared policy already specifies; +- redesigning the helper's launch protocol or its status bytes beyond the one named exit status; +- introducing a shared crate, a shared workspace library, or a code-generation framework; +- changing the node's capability advertisement. + +## 5. Required production changes + +### 5.1 Choose the mechanism, and justify it against the standalone-binary rule + +The plan MUST evaluate and settle a mechanism. Three candidates were considered at the reviewed baseline: + +| Candidate | How the helper consumes it | Verdict | +|---|---|---| +| **(A) Share a crate** — a new workspace crate owning the policy, depended on by both the runner and the helper | The helper gains a workspace-crate dependency | **Rejected.** It violates `AGENTS.md` hard invariant 3 and `architecture/sandbox-helper.md`'s stated rule that the helper ships with no production dependency on any workspace crate. The helper is the trusted artifact; its dependency surface is part of its trust story. | +| **(B) Build-time generation** — a `build.rs` in the helper reads the policy from elsewhere in the workspace and generates a Rust module into `OUT_DIR` | The helper's build reads a path outside its own package directory | **Rejected.** It makes the helper's build depend on the workspace layout rather than on its own crate, which is exactly the standalone property the helper has. It also adds a `build.rs`, and `build.rs` is outside the ownership guard's scan (`crates/*/src/**/*.rs`), so the guard would stop seeing part of the helper. | +| **(C) A single source-of-truth file, with generated copies checked into each crate** — the policy is authored once; a script regenerates both copies; both copies live inside their own crate's directory | The helper compiles its own in-crate copy; no cross-crate path, no `build.rs`, no new dependency | **Selected.** See below. | + +**Mechanism (C), in detail.** + +- The **source of truth** is a single checked-in file that states the policy: the denied-key entries, the matching rule, the node-owned baseline keys and values, and the `PATH` value contract. It is authored in one place and is not duplicated by hand. +- A **generator script** (new, under `scripts/`, alongside the other Python guardrails) reads the source of truth and writes a generated copy into each crate, inside that crate's own source directory: + - `crates/eggwork-runner/src/` — the runner's copy, which the runner compiles directly. + - `crates/eggwork-sandbox-helper/src/` — the helper's copy, which the helper compiles directly. +- Both crates compile only their **own** copy. No crate reads a file from another crate's directory, no `build.rs` is added, and no dependency edge is created. `scripts/check_execution_ownership.py`'s `check_dependencies` operates on Cargo dependency edges, so a generated file inside a crate creates no dependency edge and does not trip the guard. +- The generated copies are **checked in**. A build does not need the generator, so the release build does not depend on the script, and a reader of either crate sees the policy in that crate. +- The generated files carry a header saying they are generated, naming the source of truth and the generator, and saying that a hand edit is a contract change rather than a local fix. + +**Direction of ownership — the decision.** The **runner owns the policy**; the helper's copy is the generated conformance copy. The justification is the ownership hierarchy the repository already states: `AGENTS.md` makes `eggwork-runner` "the single owner of OS process lifecycle + isolation setup seam", and `architecture/sandbox-helper.md` places the helper *beneath* the runner. The environment policy is part of the isolation setup contract the runner owns; the helper is the enforcement implementation that must conform to it. The reverse direction — the helper owning the policy — was rejected because it would invert that hierarchy and would make the runner, the crate with the wider consumer set, depend on the helper's directory. + +**The generator's output must be deterministic and reviewable.** Re-running the generator over an unchanged source of truth must produce byte-identical output, and the generated file must be a plain, diff-friendly Rust module rather than a generated blob. The generator must not depend on network access and must fail loudly rather than emitting a partial file. + +**The generator is not the gate; the test is.** The generator exists to make the intended edit a one-step operation. The *enforcement* of parity is the test in §8, which is what makes a one-sided edit fail the build even when the generator is not run. + +### 5.2 Reconcile the drop-versus-reject difference explicitly + +The two behaviours are **not** a contradiction to be eliminated. The milestone's decision is that they are a deliberate two-layer contract, and the fix is to remove the duplicated *list*, not to unify the duplicated *behaviour*. + +- **The runner drops a denied key.** Rationale: the runner is the request-normalisation boundary. A caller may legitimately send `LD_PRELOAD` or `PATH`; the node's contract is that such a key never reaches the child. Dropping is silent, it is the current behaviour, and it is what makes a hardened environment a *property of the node* rather than a request the caller has to get right. Changing this to a refusal would turn currently-accepted requests into failures, which is a compatibility break with no security benefit. +- **The helper refuses a launch that contains a denied key.** Rationale: the helper is the enforcement point, and its job is to refuse a launch it cannot confine. If a denied key reaches the helper's launch specification, the runner's filtering did not happen — which is a defect in the node, not a caller error, and must surface as a failure rather than be silently tolerated. This is the repository's fail-closed rule applied to the enforcement point. +- The consequence of the two behaviours is that **the helper's refusal is unreachable while the lists agree**, and reachable the moment they do not. That is precisely the failure mode M005b exists to remove, and it is why the parity test in §8 is behavioural rather than structural. +- Both sides must carry a comment stating this contract in the same terms, and `architecture/sandbox-helper.md` must state it. + +### 5.3 Settle the `PATH` rule + +The `PATH == /usr/bin:/bin` rule exists only in the helper today. The milestone's decision is that it becomes an **enforced contract on both sides**, not a removed rule. + +- The rule is a confinement-relevant invariant: a `PATH` that points outside `/usr/bin:/bin` widens what a confined target can execute, and the helper's Landlock ruleset does not restrict `execve` by path. +- The helper keeps the check — it is the enforcement point — but the expected value comes from the shared policy rather than from a literal in `read_spec`. +- The runner guarantees the value: the value it puts in the child environment and the value it puts in the launch specification are the same, and both come from the shared policy. The runner does **not** merely satisfy the rule incidentally through the baseline; the shared policy states the value, and both sides reference it. +- The Windows shape is explicitly **outside** this contract. The helper is Linux-only; the runner's Windows baseline is a different, platform-shaped environment that the helper never sees. The shared policy must say so, so that a future reader does not "fix" the Windows `PATH` to `/usr/bin:/bin`. +- The `PATH` rule is a Linux/Unix contract. The non-Windows runner baseline is the one it constrains. + +### 5.4 Give the node-owned baseline one owner + +`baseline_child_environment`, the launch-specification baseline in `SandboxChannel::new`, and the helper-process environment in `SandboxChannel::command` are three separate literals. The milestone requires the node-owned baseline to be written once in the shared policy, with the platform-specific branch (Windows) kept runner-local and stated as such. + +The rule that the baseline is *node-owned* — a caller-supplied value for a baseline key does not replace it — is part of the shared policy and is what §5.5 depends on. + +### 5.5 Close the baseline-key collision hole + +This is the live defect the milestone must close, and it is the reason the milestone is not merely cosmetic. + +The shared policy must distinguish three classes of key: + +1. **Denied** — the caller may not set them. The runner drops them; the helper refuses a launch that contains them. +2. **Node-owned (reserved)** — the node sets them and the caller's value never reaches the child. `PATH`, `LANG`, `LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER` on the Unix baseline. A caller-supplied value for a reserved key is discarded in favour of the node's value, and the launch specification therefore never contains a duplicate key. +3. **Caller-controlled** — everything else. + +The rule must be applied in **both** places the runner builds an environment: `direct_command` and `SandboxChannel::new`. A caller-supplied `LANG` must therefore produce a launch specification with exactly one `LANG`, not two, and must not cause the helper to refuse the specification and the execution to lose its confinement. + +The milestone must state, and the closure record must record, the chosen behaviour for a caller-supplied reserved key: **discard the caller's value and use the node's** (the same shape as the denied-key drop), rather than refusing the request. Discarding is chosen because it is the current effective behaviour for the direct path — the direct child today receives the node's baseline `LANG` *and* the caller's `LANG`, with the caller's applied last, so the two paths currently disagree — and because refusing a request for `LANG` would be a surprising compatibility break for an ordinary key. The milestone must make the direct path and the helper path agree on this, and must say which way it resolved the disagreement. + +### 5.6 Give the environment-policy refusal a distinguishable exit status + +At the reviewed baseline, the helper's status 12 covers "the specification contains a denied key", "the `PATH` value is wrong", "the specification contains a duplicate key", "the argv is empty or oversized", "the environment exceeds its bounds", and "the schema version or profile is wrong". An operator reading "status 12" cannot tell which happened. + +The milestone must give the **environment-policy refusal** its own status byte, distinct from the general specification-validation status, and must document the status table in `architecture/sandbox-helper.md`. The runner's handling of the new status must remain the fail-closed behaviour it has today: a required request fails before the target; a best-effort request degrades to `NotApplied` — and, after M005a, emits a diagnostic. + +### 5.7 Pin the duplicated protocol limit constants + +`MAX_ARG_COUNT`, `MAX_ARG_BYTES`, `MAX_ENV_COUNT`, `MAX_ENV_NAME_BYTES`, and `MAX_ENV_VALUE_BYTES` are re-declared in the helper with the same values that `eggwork-core` exports. The milestone's mechanism makes it cheap to generate the helper's copy from the core constants, and the closure record must state whether that was done. If it was not done, the parity test must still cover these five constants, and the closure record must state that they are duplicated rather than generated. + +`MAX_SPEC_BYTES` is helper-only and has no core counterpart; it stays where it is. + +## 6. Failure, cancellation, restart, and contention semantics + +- **The `Required` path is unchanged.** A required isolation request that cannot be satisfied still fails closed before the target process starts. M005b must not convert a helper's environment-policy refusal into a degraded execution for a required request. +- **A best-effort request that the helper refuses** still degrades to `NotApplied` and, after M005a, still emits a diagnostic. M005b's effect is that this path becomes unreachable for a caller-supplied key that the policy reserves, because the specification the runner builds no longer contains the collision. +- **Cancellation** is unaffected. A cancelled run must not be reported as an environment-policy refusal, and the `CancelledBeforeSpawn` check must keep its precedence over the setup path. +- **Helper exit statuses.** Introducing a new status byte changes the runner's interpretation of the helper's status. The runner's status interpretation is a small match on the byte read from the status channel in `SandboxChannel::wait`; the new byte must be classified as a setup failure before the target, exactly like the status it replaces, and must not be mistaken for a success or a post-target status. +- **Restart and recovery.** The policy is compile-time. Nothing about restart behaviour changes. +- **Contention.** None. The policy is a static list; the only runtime effect is a lookup per environment entry at spawn time, which is bounded by `MAX_ENV_COUNT`. + +## 7. Compatibility and migration + +**Wire protocol.** No change. + +**Public Rust API.** The parity test needs to observe the runner's policy from outside the runner crate, because the helper's crate cannot be a library dependency of anything (it is a binary-only crate) and the helper's own test suite already depends on the runner as a dev-dependency. The runner's environment policy must therefore be reachable from the runner's public API — a `pub` predicate and a `pub` list, or equivalent — or the parity check must be implemented by comparing the generated files as data rather than by calling into the runner. + +This is an **additive** public API change to a published crate, which is materially smaller than a removal, but it is still release-visible and must be handled as a version-visible change: the new public items need doc comments saying that they are the node's environment policy and that the sandbox helper's copy is generated from them, so that a consumer does not treat the runner's copy as the only one. + +**Behaviour change — this is the point of the milestone.** At the reviewed baseline, a caller that supplies `LANG` (or `LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER`) receives, on the helper path, an execution that was never confined; on the direct path, the child's `LANG` is the caller's value rather than the node's. After M005b, the node's baseline wins on both paths and the execution stays confined. The closure record MUST state this behaviour change explicitly, in the "before" and "after" form, and MUST list the affected keys. It is a security improvement, and it is still a behaviour change a caller can observe. + +**Behaviour change — the helper's exit status.** The new status byte changes what the runner reports for an environment-policy refusal, and therefore what appears in `ExecutionResult.sandbox`'s `NotApplied { reason }` and, after M005a, in the diagnostic payload. The reason text is operator-facing; the closure record must show the before and after text. + +**Operator surface.** `eggworkd` verbs and the node's capability advertisement are unchanged. + +## 8. Required tests + +Required, and each must be non-vacuous. + +1. **Element-wise parity between the runner's policy and the helper's policy.** A test that loads both lists and asserts they have the same length, the same entries in the same order, and the same matching rule. This is the test that makes a one-sided edit fail the build. It must fail with a message that names the first differing entry and states that a mismatch is a contract change rather than a test to be adjusted — the wording the repository already uses in `crates/eggwork-runner/tests/windows_process_tree.rs`. +2. **Behavioural parity against the real helper binary.** A test that drives the actual helper executable — the helper's own test suite already does this through `env!("CARGO_BIN_EXE_eggwork-sandbox-helper")` — with a launch specification for each probe key, and asserts that the helper's accept/refuse decision matches the runner's policy for every probe key. This is what proves the two *rules* agree, not merely that the two *lists* have the same text. The probe corpus must include, for each entry: the entry itself, a lowercase form, a prefixed form (for prefix entries), and a near-miss that must be allowed. +3. **The generated copies are up to date.** A test that re-runs the generator over the unchanged source of truth and asserts the output is byte-identical to the checked-in copies. This catches a hand edit of a generated file with a message that points at the generator. +4. **A one-sided edit fails the build — demonstrated, not asserted.** The closure record must show, as negative evidence, that editing only the runner's copy (or only the helper's copy) makes the parity test fail, and that the failure message is the intended one. This is the evidence that the gate works. +5. **The baseline-key collision hole is closed.** A test that submits a request carrying `LANG` (and each other reserved key) and proves that: + - the launch specification the runner builds contains exactly one entry for that key — proven either by observing the real helper's accept/refuse decision, or by asserting on the specification the runner writes; + - the helper accepts the specification; and + - the execution remains confined — that is, the helper path is taken and the target is not re-spawned directly. + This test must be shown to fail against the pre-corrective behaviour. +6. **The direct path and the helper path agree on a reserved key.** A test proving that the child's environment on the direct path and the environment in the launch specification carry the same value for each reserved key. +7. **The `PATH` contract holds on both sides.** A test proving that the runner's child environment and the runner's launch specification both carry `PATH` equal to the shared policy's value, and that the helper refuses a specification whose `PATH` differs from it. +8. **The denied-key drop is unchanged.** A test proving that a caller-supplied denied key still does not reach the child, on both the direct path and the helper path, and that the execution is not refused by the helper for it. +9. **The helper's environment-policy refusal is distinguishable.** A test proving that the new status byte is used for an environment-policy refusal and is distinct from the general specification-validation status, and that the runner classifies it as a setup failure before the target. +10. **The `Required` path is unchanged.** A test proving that a required request whose helper refuses the specification still fails before the target process starts. +11. **The protocol limit constants agree.** A test comparing the helper's five duplicated constants against the `eggwork-core` values, whether by generation or by an explicit comparison. +12. **The generator is deterministic.** A test running the generator twice and asserting identical output, and asserting that it fails loudly on a malformed source of truth. +13. **No behavioural regression.** The existing runner, helper, and server suites remain green — in particular the helper's `tests/landlock_runner.rs` suite, which drives the real binary through the real runner, and the runner's Windows process-tree suite, whose `BASELINE_KEYS` list must be reconciled with the new single owner rather than left as a third hand-maintained copy. + +## 9. Required verification + +At minimum: + +```text +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +`--locked` is load-bearing on both `clippy` and `test`: a version bump that skips `Cargo.lock` passes both and then fails every release build. + +The environment-policy and Landlock machinery is Linux-only. The helper's test suite is `#[cfg(target_os = "linux")]` and runs zero tests elsewhere. The closure record must state the platform matrix **actually exercised**, honestly, and must not claim the helper path was qualified on a platform where the suite did not run. The parity gate itself must run everywhere, because the *lists* are platform-independent; only the behavioural helper tests are Linux-gated. + +If the new generator script is added, it must also be covered by the release-harness test suite under `tests/release/`, following the convention the other `scripts/` guardrails follow. + +## 10. Documentation updates + +- `architecture/sandbox-helper.md` — state the single owner of the environment policy, the drop-versus-reject contract, the `PATH` contract and its Linux scope, the node-owned baseline, the status table including the new environment-policy status, and the generated-file convention. Replace any stale line-number citations with symbol references in the same pass. +- `architecture/runner-execution.md` — describe the runner's environment construction: the denied-key drop, the reserved-key rule, the baseline, and the launch-specification environment. +- `architecture/overview.md` — add a divergence row only if a residual divergence remains after M005b. If the duplication is closed, do not add a row. +- `AGENTS.md` — the hard-invariant list does not need a new entry. If the "Isolation claims are earned" line is extended to mention the environment policy's single owner, keep the wording in the same style and keep it true. +- `plans/subsystems/security-isolation-resource-roadmap.md` — add the M005b milestone entry and set the roadmap's status line to reflect it. +- `plans/registry.md` — updated by the registry owner when the milestone is registered; this plan does not edit it. + +## 11. Acceptance criteria + +1. The denied-key list and the matching rule have exactly one owner; the helper's copy is generated and checked in. +2. `crates/eggwork-sandbox-helper/Cargo.toml` still declares no workspace-crate production dependency, and neither crate's build reads a file from outside its own crate directory. +3. A test compares the runner's policy and the helper's policy element-wise and rule-wise, and fails on a one-sided edit. +4. The negative evidence shows a one-sided edit failing the build with the intended message. +5. The runner drops denied keys and the helper refuses a launch containing one; both behaviours are documented on both sides, and the difference is stated as deliberate. +6. The `PATH == /usr/bin:/bin` rule is an enforced contract on both sides, sourced from the shared policy, with the Windows shape explicitly out of scope. +7. The node-owned baseline is written once, and `crates/eggwork-runner/tests/windows_process_tree.rs`'s `BASELINE_KEYS` is reconciled with the new owner rather than left as a hand-maintained third copy. +8. A caller-supplied reserved key no longer produces a duplicate launch-specification key, and no longer causes a best-effort execution to lose its confinement. +9. The direct path and the helper path agree on every reserved key's value. +10. The helper's environment-policy refusal has a status byte distinct from the general specification-validation status, and the runner classifies it as a setup failure before the target. +11. A required request still fails closed before the target process starts. +12. The helper's five duplicated protocol limit constants agree with `eggwork-core`, whether by generation or by an explicit comparison test. +13. The denied-key entry set is unchanged from the reviewed baseline, and the closure record lists it. +14. No wire representation changed. +15. `architecture/sandbox-helper.md` and `architecture/runner-execution.md` match the code. +16. The full pre-submit gate is green on the reviewed head. + +## 12. Stop conditions + +Stop and re-plan, recording the blocker, if any of the following occurs: + +- the selected mechanism would require the helper to gain a workspace-crate dependency, or would require either crate's build to read a file outside its own directory; +- parity cannot be established without changing the *content* of the denied-key list — that is a policy decision, not an ownership decision, and it must be escalated separately; +- the resolution of the direct-path versus helper-path disagreement over a reserved key would require refusing a request that is accepted today, without an explicit decision to make that compatibility break; +- the helper's environment-policy refusal cannot be given a distinct status byte without breaking the runner's status interpretation in a way that would weaken a fail-closed path; +- the fix would change the `Required` path's behaviour in any way; +- the milestone cannot be completed without weakening an authentication, lease, generation, fencing, or digest bound; +- the parity test turns out to be impossible to express against the real helper binary — in that case, escalate rather than weakening the test to a structural comparison of text. + +## 13. Closure evidence required + +Create: + +- `plans/closure/security-isolation-resource/005b-status.md` + +Per `plans/003-planning-process.md` §6, the record must distinguish code inspection from executed evidence and must include: + +- the reviewed repository head and the implementation commits; +- an executive finding; +- a requirement-to-evidence matrix mapping each acceptance criterion above to the specific command output or test that satisfies it; +- the exact focused and broader verification actually run, including the full pre-submit gate output; +- the platform matrix actually exercised, stated honestly — the helper suite is Linux-gated and must not be claimed as run elsewhere; +- negative and adversarial evidence: the one-sided-edit demonstration, the baseline-key collision test shown to fail against the pre-corrective behaviour and pass after it, and the behavioural parity sweep over the probe corpus; +- the denied-key entry set as it stood before and after, with the explicit statement that it was carried over unchanged; +- the reserved-key disposition, including the direct-path versus helper-path disagreement and how it was resolved; +- the before-and-after reason text for the helper's environment-policy refusal; +- the public-API change and its release-visibility consequence; +- documentation status, including the two deep dives; +- unresolved findings ranked by severity; +- the registry and roadmap disposition. + +Do not claim tests were run when they were only inspected. Do not claim a platform or feature is qualified merely because its code compiles. + +## 14. Handoff notes + +- This milestone is independent of M005a and M005c and may be executed in parallel with them, with the foundation runner-request-validation corrective, with the control-plane shared-contract corrective, and with Operations M007. It does touch `crates/eggwork-runner/src/lib.rs` in the same file as the foundation corrective, but in a different region. +- The mechanism choice in §5.1 is the part that needs judgement; the rest follows from it. Read the three candidates and their verdicts before writing code. +- The live hole in §2 is the reason this milestone is not cosmetic. A caller who sets `LANG` today gets an execution that was never confined, and only the terminal snapshot says so. If the implementation lands the single-source-of-truth change without closing the baseline-key collision, the milestone will have produced a tidier tree and the same hole. +- The repository already holds the pattern this milestone generalizes: `crates/eggwork-runner/tests/windows_process_tree.rs` keeps a hand-maintained `BASELINE_KEYS` list with the comment that a mismatch is a contract change, not a test fix. That comment is right and it is not enough. Prefer the test that fails when the two sides drift. +- The helper is the trusted artifact. Every choice in this milestone should be defensible as "the helper still ships alone, with a dependency surface an operator can read". diff --git a/plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md b/plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md new file mode 100644 index 0000000..364e0d5 --- /dev/null +++ b/plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md @@ -0,0 +1,323 @@ +# Security M005c — Resource-scoped authorization disposition corrective + +Status: blocked + +Concrete blocker: `plans/adrs/ADR-0007-resource-scoped-authorization.md` — **proposed, not yet accepted**. The ADR must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. Per `plans/003-planning-process.md` §4, this plan MUST NOT be handed off as ready until that ADR is accepted, and it MUST NOT be handed off as ready merely because adjacent implementation exists. + +Closure record: `plans/closure/security-isolation-resource/005c-status.md` + +Class: invariant + +Source authority: + +- `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` — finding SI-3 +- `plans/adrs/ADR-0007-resource-scoped-authorization.md` — the decision this milestone is blocked on (**proposed**) +- `architecture/overview.md` — divergence #4, which already records this gap +- `plans/security/threat-model.md` — the "Authenticated unauthorized principal" row, which already states this boundary +- `plans/subsystems/security-isolation-resource-roadmap.md` — the subsystem's durable invariants +- `plans/adrs/README.md` — the ADR rules this milestone must obey +- `plans/003-planning-process.md#dependency-discipline` and `#architecture-changes` + +## 1. Objective + +Resolve the already-recorded divergence #4 to a **decided disposition**, so that the node stops presenting a mechanism as available when it is inert. + +This milestone is a decision about an existing gap, not a new defect report. The gap is recorded in `architecture/overview.md`'s divergences table and stated as an open boundary in `plans/security/threat-model.md`. The objective is to close it in one of the two coherent ways the ADR weighs, and to leave the code, the public API, the design record, and the threat model all saying the same thing. + +## 2. Baseline / problem statement + +At the reviewed baseline: + +- `crates/eggwork-server/src/lib.rs` defines `pub enum ResourceId { Execution(ExecutionId), Blob(BlobDigest), Workspace(WorkspaceId), Artifact(ArtifactId) }` — a typed resource identifier. +- The same file defines `pub struct OperationRequest { pub operation: Operation, pub resource: Option }`. +- The same file defines `fn resource_for_path(operation: Operation, path: &str) -> Option`, mapping a request path segment to a typed resource for `Observe`, `Cancel`, `Renew`, `Events`, `BlobRead`, `BlobWrite`, and `ArtifactRead`. `ArtifactRead` distinguishes the artifact route from the execution route by path shape. +- The same file defines the public trait `Authorizer`, whose `fn authorize_request(&self, principal: &NodePrincipal, request: &OperationRequest) -> bool` has a default implementation that delegates to `fn authorize(&self, principal: &NodePrincipal, operation: Operation) -> bool`. +- `crates/eggwork-server/src/operations.rs` defines `pub struct GrantAuthorizer(HashMap>)` and implements **only** `authorize`. The trait's default `authorize_request` therefore applies on the production path, and the typed `ResourceId` is **never consulted**. +- `fn authorize_resource(state, principal, operation, resource)` in `crates/eggwork-server/src/lib.rs` is the resource-scoped call helper. It is invoked at six handler sites: + 1. the blob-find-missing handler — `Operation::BlobRead`, `ResourceId::Blob(digest)`; + 2. the blob-prepare handler — `Operation::BlobWrite`, `ResourceId::Blob(digest)`; + 3. the workspace-create handler — `Operation::WorkspaceCreate`, `ResourceId::Workspace(workspace_id)`; + 4. the workspace-derive handler — `Operation::WorkspaceCreate`, `ResourceId::Workspace(workspace_id)`; + 5. the execute handler — `Operation::Execute`, `ResourceId::Execution(execution_id)`; + 6. the execute handler, conditionally on the request naming one — `Operation::Execute`, `ResourceId::Workspace(workspace_id)`. +- The `dispatch` function in the same file additionally calls `authorize_request` with a `resource_for_path`-derived resource for every routed request. +- Every one of those call sites resolves to the same operation-level decision. The typed resource is constructed, passed, and discarded. +- **The owner fence that does exist is a store fence, not an authorizer fence.** `ExecutionStore::load_snapshot_for_principal` in `crates/eggwork-server/src/store.rs` selects by `(execution_id, principal_id)`. The artifact store's `load` selects by `(artifact_id, principal_id)` and its list selects by `(execution_id, generation, principal_id)`. The workspace store's `lookup_manifest` selects by `(principal_id, manifest_digest)`, and `WorkspaceStore::materialize` rejects a conflicting materialization whose `principal_id` differs. **Blob storage has no owner fence at all** — it is content-addressed and shared, which is why the threat model's remaining-boundary column reads: *"Broad BlobRead capability permits any known digest unless resource-scoped policy is configured."* +- The only exerciser of the resource-scoped path is a unit test in `crates/eggwork-server/src/lib.rs`'s test module, which asserts that `resource_for_path` maps a path segment to a `ResourceId`. No production authorization decision depends on the answer. +- The configuration surface is `ClientGrant` in `crates/eggwork-server/src/operations.rs` — `{ principal_id, certificate_sha256, operations: Vec }`, with `#[serde(deny_unknown_fields)]`, held in `OperatorConfig`'s `clients` list and validated in `OperatorConfig::validate`, which rejects an unknown operation name, an empty operations list, a malformed principal id, and a duplicate certificate fingerprint. `GrantAuthorizer` is built from that configuration in `OperatorConfig::principals`, which returns the `FingerprintPrincipalResolver` and the `GrantAuthorizer` pair. + +## 3. Scope + +In scope: + +- the disposition of the `Authorizer::authorize_request` hook and its `ResourceId` plumbing; +- the grant configuration shape, if the ADR selects implementation; +- the authorizer's decision logic, if the ADR selects implementation; +- the six resource-scoped call sites and the `dispatch`-level `authorize_request` call, under whichever disposition is decided; +- `architecture/overview.md`'s divergence #4 row, which must end up reflecting the decided disposition; +- `plans/security/threat-model.md`'s remaining-boundary column for the "Authenticated unauthorized principal" row; +- the corresponding deep dives — `architecture/server-node.md` and `architecture/operations-cli.md`, both of which are cited by divergence #4. + +Out of scope: + +- any change to the wire representation of a request or response type, unless the decided disposition requires one and the ADR says so; +- any change to the store's ownership model, the artifact store's retention, the blob store's content-addressing, or the workspace store's derivation rules; +- the execution-ownership boundary, the mTLS identity model, and the lease and fencing rules; +- M005a (degraded-isolation observability) and M005b (sandbox-helper environment parity), which are independent and may run in parallel; +- the control-plane shared-contract corrective, except that this milestone must not change `API_SCHEMA_VERSION` on its own authority; +- any change to `eggwork-client`'s request shapes unless the decided disposition requires one. + +## 4. Invariants and non-goals + +Invariants that hold in **both** branches: + +1. **The node does not present a mechanism as available when it is inert.** If the hook is kept, it decides. If it is removed, the public API, the documentation, and the operator surface no longer imply that resource-scoped authorization exists. +2. **The `architecture/overview.md` divergences table is updated to the decided disposition.** Divergence #4 is either closed with a statement of what now enforces the boundary, or rewritten to describe the mechanism that is actually in force. It is not left describing an inert hook as an open gap once the gap has been decided. +3. **Authorization still strictly precedes resource resolution** in `dispatch`, and a denied caller still cannot distinguish an existing resource from an absent one. +4. **No new information is disclosed to an unauthorized caller.** A resource-scoped denial must be indistinguishable from an operation-level denial, and from a missing resource, in both status code and response body. +5. **The store's existing owner fences are not weakened.** The `principal_id` fences on executions, artifacts, and workspaces remain, and remain the backstop behind whatever the authorizer decides. +6. **The configuration loader still fails closed.** A malformed or unknown field in a grant remains a configuration error, and the node refuses to start. + +Non-goals: + +- inventing a general policy language, a rule engine, or a role system; +- adding a scheduler, a queue, or a placement concept; +- changing who may hold which *operation* — this milestone is about the resource scope within an operation, not about the operation grant itself; +- auditing the many other authorization boundaries the repository already records. + +## 5. Required production changes — Branch A: implement resource-scoped grants + +This branch is the work required **if** ADR-0007 selects implementation. It is written so that an agent can execute it without re-deriving the design. + +### 5.1 The grant configuration shape + +Extend `ClientGrant` in `crates/eggwork-server/src/operations.rs` with an optional resource-scoped grant list. The shape must: + +- be additive — a grant without a resource list keeps today's operation-level meaning; +- name the **operation** the scope applies to, so a scope cannot widen an operation the principal does not hold; +- name the **resource kind** and the **resource identifier** — the identifier being the string form of the corresponding `ResourceId` variant; +- be bounded — a per-grant cap and a per-node cap on the total number of resource-scoped grants, both validated in `OperatorConfig::validate`, alongside the existing caps; +- be validated — an unknown operation name, an unknown resource kind, a malformed identifier, a resource scope for an operation the grant does not hold, and a duplicate scope must each be a configuration error, not a silently ignored entry; +- remain `#[serde(deny_unknown_fields)]`, so a typo in a scope is a refusal rather than a silently absent scope. + +The identifier is the **string form** of the `ResourceId` variant, and the implementation must parse it back into the typed variant — `ExecutionId::new`, `BlobDigest::parse`, `WorkspaceId::new`, `ArtifactId::new` — so that the configuration and the wire path agree on what an identifier is. A scope that names an identifier the corresponding type rejects is a configuration error. + +### 5.2 The owner fence + +A resource-scoped grant must not be usable to reach a resource the principal does not own. Two different fences apply, and the implementation must distinguish them: + +- **Execution, Workspace, Artifact** — these have an owner. The store already compares `principal_id` for them: `ExecutionStore::load_snapshot_for_principal` selects by `(execution_id, principal_id)`; the artifact store's `load` selects by `(artifact_id, principal_id)`; the workspace store's `lookup_manifest` selects by `(principal_id, manifest_digest)`. The authorizer's resource-scoped decision must therefore be **consistent with** the store's ownership, and the milestone must decide which of the two is authoritative when they disagree. The recommended disposition is that the **store remains authoritative** for ownership — the authorizer may narrow, never widen — so that a resource-scoped grant cannot be used to reach a foreign resource even if the grant list is misconfigured. The milestone must prove that property with a test that grants a scope and then attempts to reach a resource owned by a different principal. +- **Blob** — there is no owner. Blob storage is content-addressed and shared; the same digest is the same bytes for every principal. A blob scope must therefore be an **explicit digest list**, never an owner comparison, and the implementation must say so in the code and the documentation. This is the case the threat model's remaining-boundary column names. + +### 5.3 The authorizer's decision + +`GrantAuthorizer` must implement `authorize_request` so that the typed `ResourceId` is consulted. The decision rule must be: + +- the operation grant must be present — a resource scope never *grants* an operation the principal does not hold; +- when a resource scope is configured for that operation and that resource kind, the resource must be within the granted set; +- when no resource scope is configured for that operation and that resource kind, the decision falls back to the operation-level grant, exactly as today — this preserves existing deployments' behaviour and is the compatibility contract; +- when the request carries no resource (`resource: None`), the decision falls back to the operation-level grant. + +The implementation must keep the **existing** rule from `architecture/overview.md`'s positive notes: "Authorization strictly precedes resource resolution in `dispatch`, and id parsing touches only the path, so a denied caller cannot distinguish an existing resource from an absent one." A resource-scoped denial must not introduce a distinguishable failure. + +### 5.4 The operations the resource scope applies to + +The scope applies to the operations whose resources the six call sites already name: + +| Operation | Resource kind | Call sites | +|---|---|---| +| `BlobRead` | `Blob` | the blob-find-missing handler | +| `BlobWrite` | `Blob` | the blob-prepare handler | +| `WorkspaceCreate` | `Workspace` | the workspace-create and workspace-derive handlers | +| `Execute` | `Execution` | the execute handler | +| `Execute` | `Workspace` | the execute handler, when the request names one | + +`resource_for_path` additionally produces a resource for `Observe`, `Cancel`, `Renew`, `Events`, and `ArtifactRead`, and the `dispatch`-level call passes it. The milestone must decide, explicitly, whether the scope applies to those operations too. The recommended disposition is that it **does**, because `dispatch` already constructs the resource for them and the six handler-level call sites are the ones that would need additional coverage — leaving `dispatch` unscoped while scoping the handlers would produce an inconsistent boundary. + +### 5.5 The configuration, operator, and documentation surface + +- The node configuration gains the new field; `examples/eggworkd.example.json` must show it. +- `config print` must redact it consistently with the existing redactions, and must not print a private key path or a certificate fingerprint. +- `architecture/server-node.md` and `architecture/operations-cli.md` must describe the new decision rule. +- `plans/security/threat-model.md`'s remaining-boundary column must be updated to state what is now enforced. + +## 6. Required production changes — Branch B: remove the hook and the plumbing + +This branch is the work required **if** ADR-0007 selects removal. It is written so that an agent can execute it without re-deriving the design. + +### 6.1 The removals + +In `crates/eggwork-server/src/lib.rs`: + +1. delete `pub enum ResourceId` and its four variants; +2. delete the `resource` field from `pub struct OperationRequest`, leaving `operation` as its only field; +3. delete `fn resource_for_path(operation, path) -> Option`; +4. delete `fn authorize_resource(state, principal, operation, resource) -> bool`; +5. remove the `resource` argument from every `authorize_resource` call and collapse the six handler-level call sites to the operation-level `state.authorizer.authorize(...)` form — the blob-find-missing handler, the blob-prepare handler, the workspace-create handler, the workspace-derive handler, and the two execute-handler call sites; +6. change the `dispatch` function to build an `OperationRequest` with no resource, or to call the operation-level authorizer directly; +7. remove the `authorize_request` method from the public `Authorizer` trait, and remove its default implementation. + +### 6.2 The test removal + +Remove the unit test in `crates/eggwork-server/src/lib.rs`'s test module that asserts `resource_for_path` maps a path segment to a `ResourceId`. If the `dispatch` path's routing test asserts on the resolved resource, that assertion must be removed with it, and the routing test must be rewritten to assert on the *operation* rather than on the resource. + +### 6.3 The compatibility note — this is a public API removal + +`ResourceId`, `OperationRequest`, and the `Authorizer` trait are `pub` in `eggwork-server`, which is a published workspace crate. Removing `ResourceId` and the `authorize_request` method is a **breaking change to that crate's public API**. The milestone must: + +- enumerate every in-tree consumer of the removed items and state that each was migrated; +- state whether any out-of-tree embedder is known to exist, and if the answer is unknown, say so explicitly rather than assuming the API is free to change; +- reflect the removal in the release version and notes, and not bundle it silently into a release that claims to be a qualification-only candidate; +- record in the closure record that the removal is the reason the divergence is closed: the mechanism no longer *looks* available. + +### 6.4 The boundary that remains after removal + +Removing the hook does **not** remove the boundary; it removes the pretence. The store's `principal_id` fences remain the enforcement for executions, artifacts, and workspaces. The blob boundary remains exactly what the threat model says it is: a principal holding `BlobRead` may read any known digest. The milestone must make sure the documentation says that plainly, and must not let the removal be described as if it closed the blob boundary. + +### 6.5 The documentation surface + +- `architecture/overview.md`'s divergence #4 is rewritten or closed: the row must no longer describe an inert hook as if it were a live mechanism. If the row is closed, it must say what now enforces the boundary and what residual boundary remains. +- `architecture/server-node.md` and `architecture/operations-cli.md` must stop describing a resource-aware hook. +- `plans/security/threat-model.md`'s remaining-boundary column must be updated to state the boundary as it is, without the "unless resource-scoped policy is configured" clause if no such policy can now be configured. + +## 7. Failure, cancellation, restart, and contention semantics + +- **Authorization precedes everything.** Both branches preserve the rule that authorization runs before resource resolution and before any store lookup that could disclose existence. A resource-scoped denial must be indistinguishable from an operation-level denial. +- **No state machine change.** Neither branch touches the execution state machine, leases, generations, or fencing. +- **No restart or recovery change.** Both branches are authorization-decision changes; neither alters what is persisted or how a node recovers. +- **Contention.** Neither branch adds a lock on the authorization path. The authorizer's decision must remain a bounded, in-memory decision over the configuration-derived grant tables. +- **Failure ordering.** A configuration error must be detected at load time, before the node accepts traffic, and must refuse the node — not degrade to a permissive decision. + +## 8. Compatibility and migration + +**Branch A.** Additive to the configuration surface; the default behaviour for a grant without a resource list is unchanged, so an existing deployment's behaviour is unchanged. The change to *decisions* applies only to principals that configure resource scopes. The public API changes are additive (`GrantAuthorizer` gains an implementation of an existing trait method; `ClientGrant` gains an optional field). `ClientGrant` is `pub` and serialized — adding an optional field is a compatible change, but `#[serde(deny_unknown_fields)]` means an **older** node reading a **newer** configuration with a resource scope will refuse to start. That refusal is correct and must be documented: a node must not silently ignore a scope it does not understand. + +**Branch B.** A breaking public-API removal, as described in §6.3. + +**Both branches.** No wire protocol change to request or response shapes is required by either branch as written. If the decided disposition requires one, the ADR must say so and the change must be coordinated with the control-plane shared-contract corrective, which owns `API_SCHEMA_VERSION`. + +## 9. Required tests + +Required, and each must be non-vacuous. + +### Common to both branches + +1. **The divergence table matches the code.** A test or review assertion that the disposition recorded in `architecture/overview.md` is the disposition the code implements. In Branch A, a test proving that `GrantAuthorizer::authorize_request` is reached and consults the resource — for instance, that two principals with the same operation grants but different resource scopes receive different answers for the same resource. In Branch B, an assertion that no `ResourceId` and no `authorize_request` remain, so the hook cannot be inert again. +2. **No regression in the existing boundary.** The existing server authorization tests — the operation-level grant matrix, the "request payload cannot supply authoritative principal" test, and the routing test — remain green and unchanged in their assertions. +3. **Authorization still precedes resource resolution.** A test proving that an unauthorized principal's request is refused at the same point and with the same response as at the reviewed baseline, and that the response does not disclose whether the named resource exists. + +### Branch A only + +4. **A resource scope actually narrows.** A test proving that a principal with the `BlobRead` operation grant and a scope naming one digest is refused a *different* digest, and permitted the named one. Without this test, Branch A could land as an inert hook again — which is the defect being corrected. +5. **The owner fence holds.** A test proving that a resource-scoped grant naming a resource owned by a different principal does not permit access to it, for each of `Execution`, `Workspace`, and `Artifact`. +6. **Blobs have no owner fence, and the scope says so.** A test proving that a blob scope is an explicit digest list and that a principal with a blob scope cannot read a digest outside it. +7. **Operation grants are never widened by a scope.** A test proving that a resource scope for an operation the principal does not hold grants nothing. +8. **No scope configured means today's behaviour.** A test proving that a principal with no resource scopes receives exactly the operation-level decision, so existing deployments are unaffected. +9. **Configuration failures are refused.** Tests proving that an unknown operation, an unknown resource kind, a malformed identifier, a scope for an unheld operation, a duplicate scope, and an over-cap grant count each cause the configuration to be rejected and the node to refuse to start. +10. **Redaction.** A test proving that `config print` does not print the resource scope identifiers in a way that leaks a private key path or a certificate fingerprint, consistent with the existing redactions. + +### Branch B only + +11. **The hook is gone.** An assertion that `ResourceId`, `OperationRequest.resource`, `resource_for_path`, `authorize_resource`, and the `authorize_request` trait method no longer exist — a test that fails if any of them is reintroduced. +12. **The six call sites are gone.** An assertion that no handler-level call constructs a typed resource, and that the six sites now authorize at the operation level. +13. **Behaviour is unchanged.** The existing authorization test matrix is green and unchanged, proving the removal did not change any decision. +14. **The residual boundary is stated, not hidden.** A documentation assertion — or an explicit closure-record statement — that the blob boundary remains exactly as the threat model describes it, and that the removal closed the *pretence*, not the boundary. + +## 10. Required verification + +At minimum: + +```text +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +`--locked` is load-bearing on both `clippy` and `test`: a version bump that skips `Cargo.lock` passes both and then fails every release build. + +The authorization path is exercised entirely on the host; no platform matrix is required for the decision logic itself. If either branch changes a request or response wire shape, the change must additionally be exercised across the release matrix, and the platform matrix actually exercised must be stated honestly. + +## 11. Documentation updates + +- `architecture/overview.md` — divergence #4 must end up reflecting the decided disposition. This is a required update in **both** branches, and it is the single most important documentation consequence of the milestone. +- `architecture/server-node.md` — the authorization decision path, whichever branch is decided. +- `architecture/operations-cli.md` — the grant configuration surface, in Branch A; the absence of a resource-scope surface, in Branch B. +- `architecture/protocol.md` — only if a wire shape changes. +- `plans/security/threat-model.md` — the "Authenticated unauthorized principal" row's remaining-boundary column. +- `examples/eggworkd.example.json` — Branch A only. +- `AGENTS.md` — the hard-invariant list does not need a new entry. If the "Node trust requires a verified mTLS client CA and explicit per-principal grants" line is extended, keep the wording in the same style and keep it true. +- `plans/subsystems/security-isolation-resource-roadmap.md` — add the M005c milestone entry and set the roadmap's status line to reflect it. +- `plans/registry.md` — updated by the registry owner when the milestone is registered; this plan does not edit it. + +## 12. Acceptance criteria + +Common to both branches: + +1. The decided branch is recorded in `plans/adrs/ADR-0007-resource-scoped-authorization.md` as **accepted**, with the status changed from `proposed`. +2. `architecture/overview.md`'s divergence #4 reflects the decided disposition. +3. `plans/security/threat-model.md` states the boundary as it is after the change. +4. The node does not present a mechanism as available when it is inert: in Branch A the hook decides and a test proves it; in Branch B the hook and its plumbing are gone and a test proves they stay gone. +5. Authorization still precedes resource resolution, and an unauthorized caller cannot distinguish an existing resource from an absent one. +6. The store's existing owner fences are not weakened, and the existing authorization test matrix is green and unchanged. +7. The configuration loader still fails closed on a malformed or unknown field. +8. No wire protocol change, unless the ADR decided one and the change is coordinated with the control-plane shared-contract corrective. +9. The full pre-submit gate is green on the reviewed head. + +Branch A additionally: + +10. A resource scope measurably narrows an operation grant, proven by a test that fails if the scope is ignored. +11. The owner fence holds for `Execution`, `Workspace`, and `Artifact`, and blobs are governed by an explicit digest list. +12. A principal with no resource scopes receives exactly the operation-level decision. +13. Every configuration error class is refused at load time. + +Branch B additionally: + +14. `ResourceId`, `OperationRequest.resource`, `resource_for_path`, `authorize_resource`, the `authorize_request` trait method, the six resource-scoped call sites, and the unit test are all removed, and a test proves they stay removed. +15. The removal is recorded as a breaking public-API change, with the in-tree consumer enumeration, the out-of-tree position stated honestly, and the release version and notes updated. + +## 13. Stop conditions + +Stop and re-plan, recording the blocker, if any of the following occurs: + +- the ADR is still `proposed` when implementation is proposed to begin — this is the milestone's own blocker, and per `plans/003-planning-process.md` §4 it must not be worked around; +- either branch would require weakening the store's `principal_id` fences, or would let a resource-scoped grant reach a resource owned by another principal; +- either branch would make a denied caller able to distinguish an existing resource from an absent one; +- either branch would require the authorizer to consult the store on the authorization path in a way that introduces a lock or an ordering dependency that authorization does not have today; +- either branch would change the wire protocol without a decision recorded in the ADR and coordinated with the control-plane shared-contract corrective; +- implementing Branch A would require a general policy language, a role system, or a rule engine — that is a different decision and must be escalated; +- the milestone cannot be completed without weakening an authentication, lease, generation, fencing, or digest bound. + +## 14. Closure evidence required + +Create: + +- `plans/closure/security-isolation-resource/005c-status.md` + +Per `plans/003-planning-process.md` §6, the record must distinguish code inspection from executed evidence and must include: + +- the reviewed repository head and the implementation commits; +- the **accepted** ADR's identity, its status, and the decision it records; +- an executive finding; +- a requirement-to-evidence matrix mapping each acceptance criterion above to the specific command output or test that satisfies it; +- the exact focused and broader verification actually run, including the full pre-submit gate output; +- negative and adversarial evidence: in Branch A, a resource scope shown to refuse a resource outside the scope and a foreign-owned resource shown to remain refused; in Branch B, an assertion that the removed items cannot be reintroduced silently; +- compatibility review: for Branch A, the configuration compatibility position including the `deny_unknown_fields` refusal by an older node; for Branch B, the public-API removal, the in-tree consumer enumeration, the out-of-tree position stated honestly, and the release-visibility consequence; +- documentation status, including the divergences-table row, the threat-model row, and the deep dives; +- the residual boundary that remains after the change, stated plainly — including, in Branch B, that the blob boundary remains exactly as the threat model describes it; +- unresolved findings ranked by severity; +- the registry and roadmap disposition. + +Do not claim tests were run when they were only inspected. Do not claim a platform or feature is qualified merely because its code compiles. + +## 15. Handoff notes + +- **This plan is blocked and must not be handed off as ready.** The blocker is concrete and named: `plans/adrs/ADR-0007-resource-scoped-authorization.md`, which is **proposed, not accepted**. It is written now, per `plans/003-planning-process.md` §4, to preserve the design intent so that the implementation is mechanical once the decision is made. +- The plan is written so that **either** ADR outcome is executable without re-deriving the design. §5 is Branch A's work; §6 is Branch B's work; §4, §7, §8, §9, §10, §11, §12, and §14 hold in both. +- The decision is durable and needs a human's judgement, not an implementer's. The two branches differ enormously in cost and in what they promise a caller: one adds a real per-resource boundary, the other removes a false promise. +- The defect is **already recorded**. This milestone must not be reported as a newly discovered defect, and the closure record must say that the gap was known and is now decided. +- If the ADR defers with a third option — keeping the mechanism present while advertising that it is unavailable — that option must still satisfy the invariant in §4.1, and the ADR must say concretely how a caller learns that resource-scoped authorization is not in force. A comment in the source is not that. +- This milestone is independent of M005a and M005b and may be executed in parallel with them, with the foundation runner-request-validation corrective, with the control-plane shared-contract corrective, and with Operations M007. diff --git a/plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md b/plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md new file mode 100644 index 0000000..79417f3 --- /dev/null +++ b/plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md @@ -0,0 +1,613 @@ +# Workspace and Artifact Transport M005a — Declared-artifact capture fails closed + +Status: proposed + +Class: invariant + +Closure record: `plans/closure/workspace-artifact-transport/005a-status.md` + +Source authority: + +- `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, finding 1.1 (WA-1); +- `plans/subsystems/workspace-artifact-transport-roadmap.md`, durable invariant 6 ("Declared outputs are the default artifact capture boundary"); +- `plans/adrs/ADR-0004-content-addressed-workspaces-and-artifacts.md`; +- `plans/003-planning-process.md#verification-philosophy` and `#corrective-work`. + +## 1. Objective + +Make the declared-artifact failure mode honest. + +An execution whose declared outputs could not be captured MUST NOT present as a successful +execution with missing declared artifacts. Today, on a platform where safe descriptor-relative +capture is unavailable, the caller receives a successful execution, zero artifacts, and a failure +marker buried inside the terminal snapshot. That is the highest-severity finding in the +workspace/artifact corrective, and this plan is the small, high-severity, always-correct part of +its fix. + +The decision this plan must force is stated in section 4. The acceptable resolutions, in order of +preference, are: + +(a) implement a safe open on the target platform so that capture actually works; or + +(b) if the platform genuinely cannot support descriptor-relative safe capture, the execution must +terminate in a state that truthfully reports the failure instead of `Succeeded` with a buried +`finalization_failure` marker. + +## 2. Baseline + +**What the code does.** `crates/eggwork-server/src/artifact.rs` has two variants of +`open_file_beneath`. The unix variant opens the root and each path component descriptor-relatively +with `O_NOFOLLOW` (`rustix::fs::{Mode, OFlags, open, openat}`). The `#[cfg(not(unix))]` variant +returns `io::ErrorKind::Unsupported` with the message *"safe artifact capture is unavailable on this +platform"*. + +`capture_blob` in the same module calls `open_file_beneath` and propagates the error with `?`. +`capture_declared` calls `capture_blob` inside its capture loop and propagates with `?`, so the +first failure aborts the entire capture: no artifact record is published and the returned count is +never produced. + +`crates/eggwork-server/src/lib.rs` (`run_execution`) performs the capture in the +execution-finalization path and matches on the result. `Ok(count)` sets +`execution_result.artifact_count`. `Err(_)` sets +`execution_result.finalization_failure = Some(ExecutionFinalizationFailure::ArtifactCapture)` and +changes nothing else: the terminal `ExecutionState` remains `Succeeded`, the `exit_code` remains +the target's, and `artifact_count` remains `0`. The terminal event published immediately afterwards +is `ExecutionEventKind::State(terminal)`; `eggwork-core`'s `ExecutionEventKind` has variants +`State`, `Stdout`, `Stderr`, and `Diagnostic`, and no artifact-specific variant, so the failure +never appears in the event stream. + +**The behaviour is asserted, not merely tolerated.** The integration test in +`crates/eggwork-server/src/lib.rs` (`blob_protocol_streams_verifies_deduplicates_and_enforces_quota`) +asserts the whole combination: `state == ExecutionState::Succeeded`, `exit_code == Some(0)`, +`artifact_count == 0`, and +`finalization_failure == Some(ExecutionFinalizationFailure::ArtifactCapture)`. That assertion must +be changed by this plan; it currently locks the defect in place. + +**What the platform means.** `x86_64-pc-windows-msvc` is a published release target (`README.md`, +"Installing a published release"). The `#[cfg(not(unix))]` branch is therefore the live behaviour +of a shipped platform, not a hypothetical path. + +**The node advertises the capability it cannot deliver.** `static_capability_features` in +`crates/eggwork-server/src/lib.rs` returns a single static list that includes +`"artifact.declared.v1"`, `"artifact.stream.v1"`, and `"artifact.retention.v1"` on every +platform, with no platform condition. A Windows node therefore advertises declared-artifact +capture and then refuses the capture. That contradicts the repository's own stated capability +rule — "Capability advertisement reflects a runtime probe, not compile target or configuration +intent" (`plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`) — +and it is the same defect seen from the other side: a static claim where a runtime fact is +required. + +**What the documentation says.** `architecture/data-plane.md` describes the mechanism accurately: +its error-model section states that `capture_declared` has no partial-success result, that any +variant aborts the whole capture, and that the caller records +`ExecutionFinalizationFailure::ArtifactCapture` "while leaving the execution's own exit state +intact"; its "Honest gaps" section states that no test exercises the non-unix branches, naming +`open_file_beneath` returning `ErrorKind::Unsupported`. The design record is honest about the +mechanism and silent about the judgment. The `architecture/overview.md` divergences table records +row 18 (artifact GC does not release blob references) and has **no row** for this defect. The +README's Windows caveat covers isolation, resource enforcement, and service management, and says +nothing about artifacts — so a reader of the README would reasonably expect declared artifacts to +work on a Windows node. + +**Correction to the review note.** The review note states that the finalization path "catches the +capture error and sets `finalization_failure` ... while leaving state `Succeeded` and artifact +count zero". That is accurate. One refinement matters for scoping: the failure is not limited to +the platform-unsupported case. The same code path produces `Succeeded` + zero artifacts for a +missing required output, a symlinked output, a non-regular file, and a capture-budget exhaustion, +because `capture_declared` is all-or-nothing and the finalization records the failure without +changing the state. The plan must decide its scope over that whole class explicitly (section 4), +not only over the platform case. + +## 3. Scope + +In scope: + +- the outcome of a declared-artifact capture, from `capture_declared` through the terminal + execution result, the terminal event, and the client's view of the execution; +- a first-class, platform-independent statement of whether safe descriptor-relative capture is + available on the running platform, so that "the platform cannot do this" is a runtime fact + rather than an inference from a `cfg`; +- the terminal state, terminal event, and terminal result when declared outputs were requested and + the capture did not complete; +- the README's Windows caveat, the `architecture/overview.md` divergences table, and + `architecture/data-plane.md`; +- the tests and the CI change required to make the corrected behaviour provable on a non-Unix + target. + +Out of scope: + +- implementing descriptor-relative safe capture on Windows. That is a substantial, separately + qualified platform change; see section 4 for the conditions under which it may be deferred. +- the workspace, artifact, blob, and manifest *contents* of a capture. This plan does not change + what is captured, only what is reported when capture cannot complete. +- the retention and GC behaviour of artifacts and their blob references. +- every other finding in the corrective addendum. WA-2, WA-3, and WA-4 belong to M005b. + +## 4. Invariants and non-goals + +### 4.1 The invariant this plan establishes + +**An execution whose declared outputs could not be captured MUST NOT present as a successful +execution with missing declared artifacts.** + +Three consequences follow, and all three are required: + +1. **The terminal state is truthful.** If declared outputs were requested and the capture did not + complete, the terminal `ExecutionState` is not `Succeeded`. The plan must select the truthful + state from the existing vocabulary in `eggwork-core` (`ExecutionState::Failed` with an + appropriate `ExecutionFailure`, or another state the plan justifies) and must not invent a + state outside it without an ADR. +2. **The failure is visible on the terminal state, in the event stream, and to the caller.** Not + only as a nested marker inside the terminal snapshot. The plan must ensure the event stream + carries the failure before the terminal state event, so that a caller that consumes the stream + rather than the final snapshot is not left with a bare `Succeeded`. + + `ExecutionEventKind::Diagnostic` is the existing carrier in the protocol — `eggwork-core` + defines it and the journal bounds its payload by `MAX_EVENT_CHUNK_BYTES` — but it currently has + **no production publisher**: every use of the variant in the repository is in test code. The + plan must therefore either create a production publisher for it, or introduce a dedicated event + kind. Creating a publisher is the smaller change, but it must be coordinated with the Security + M005a degraded-isolation observability corrective, which needs the same publisher for a + different failure. Two correctives must not grow two divergent publishers for the same event + kind. Adding a new `ExecutionEventKind` variant is a protocol change and needs an ADR. + Whatever the choice, the published payload must be bounded. +3. **The artifact-count / declared-output-count relationship is explicit.** The caller must be able + to tell "no declared outputs" from "declared outputs that vanished" without guessing. The plan + must introduce a first-class, typed artifact-capture disposition on the terminal result that + distinguishes at least: not requested, completed, and failed. The caller must not have to + infer the outcome from `artifact_count == 0` plus knowledge of an optional field. + +### 4.2 Scope of the invariant over capture failures + +The plan must decide, and record in its closure record, whether the invariant in 4.1 applies to +**every** capture failure or only to the platform-unsupported case. + +The recommended decision is to apply it to **every** capture failure — missing required output, +symlinked or non-regular output, capture-budget exhaustion, I/O failure, and platform +unsupported — because: + +- the invariant as written is about the *class* "declared outputs could not be captured", and a + platform-only carve-out would leave the same silent-success shape reachable on unix hosts + (for example a required output that disappeared between discovery and capture); +- one rule is smaller and cheaper to implement and to test than a rule plus an exception; +- the existing all-or-nothing semantics of `capture_declared` mean there is no partial artifact + set to be truthful about in any of these cases. + +The plan may narrow this to the platform case **only** if it records the remainder as an open +finding with a named owner and a follow-on milestone in the same commit. It must not narrow it +silently. + +### 4.3 Non-goals + +This plan does not: + +- change the capture boundary, the declared-output vocabulary, `MAX_OUTPUTS`, + `MAX_ARTIFACT_FILES`, `MAX_ARTIFACT_TOTAL_BYTES`, `MAX_BLOB_BYTES`, or any other bound; +- change what is captured, how bytes are hashed, or the double hash in + `crates/eggwork-server/src/artifact.rs` (the capture hash plus the blob store's re-hash on + write). That double hash is documented and accepted; it is not to be removed here; +- change the symlink policy, the `NOFOLLOW` chain on unix, or the refusal to substitute a + path-based open for a descriptor-relative one; +- weaken authentication, authorization, lease renewal, generation fencing, or the digest bounds; +- introduce a queue, a worker selection policy, a priority or fairness rule, a DAG, or a semantic + retry. Eggwork remains a fixed-target, scheduler-free execution fabric; +- change the `eggworkd` command surface, the route set, or the `NodeCapabilities` feature set + beyond the conditional advertisement that section 5.1 requires. Removing or renaming a + capability string is out of scope; making `"artifact.declared.v1"` conditional on the runtime + capability fact is in scope; +- remove or weaken `ExecutionFinalizationFailure::ArtifactCapture` as a field. The existing + marker may remain, and the `Retention` variant's current behaviour is out of this plan's scope; + what must change is that the `ArtifactCapture` variant can no longer be the *only* signal, and + can no longer accompany a `Succeeded` state. + +## 5. Required production changes + +The plan must implement, at minimum, the following. Exact symbol names and file placement are the +implementing agent's choice within these constraints. + +### 5.1 A runtime capture-capability fact + +The server must be able to state, at runtime, whether safe descriptor-relative capture is +available on the running platform. Today that fact exists only implicitly, as the presence of a +`#[cfg(not(unix))]` branch. + +- The fact must be **runtime-probed or compile-time-exact and publicly reachable**, not inferred + by a caller from a `cfg` of its own. +- It must be reachable from outside `eggwork-server`'s crate-private modules, because the + crate's data-plane modules have no `pub use` re-export and an external test cannot name them. + The natural home is a small public function or type in `eggwork-server`, or a type in + `eggwork-core` (which is already the home of the wire types). +- The plan must justify the placement and record the compatibility consequence. `eggwork-server` + and `eggwork-core` are published workspace crates, so a public API addition is release-visible; + an addition is compatible, a removal is not. +- **The advertised capability must follow the fact.** `static_capability_features` in + `crates/eggwork-server/src/lib.rs` currently advertises `"artifact.declared.v1"` on every + platform. A node that cannot capture must not advertise that it can. The plan must decide + whether the declared-artifact capability string becomes conditional on the runtime fact, and + record the decision and its consequence: a caller that reads the capability list must be able to + tell that a node will refuse declared outputs before it submits one. The plan must also state + what a caller sees when the capability is absent — whether the admission gate rejects a request + that declares outputs, or accepts it and then fails the execution. Both are defensible; the + plan must choose one and justify it, because "the node advertised a capability it does not + have" and "the node advertised nothing and the caller learned only at execution time" are + different products. + +### 5.2 A typed artifact-capture disposition on the terminal result + +- `ExecutionResult` in `crates/eggwork-core/src/lib.rs` must carry a first-class artifact-capture + disposition with at least the three states named in 4.1(3): not requested, completed, failed. +- The field must be `#[serde(default)]` so that a peer running an older build still decodes a + terminal snapshot produced by a newer node. +- The plan must record that the terminal snapshot is **not byte-identical** across this change. + The existing `finalization_failure: Option` field stays; it becomes + a secondary marker rather than the only signal. +- The disposition must distinguish "no declared outputs were requested" from "declared outputs + were requested and the capture did not complete". A caller must never have to compare + `artifact_count` against a declared-output count it does not have. + +### 5.3 A truthful terminal state and a visible event + +- `crates/eggwork-server/src/lib.rs` (`run_execution`) must map a failed capture to a terminal + state that is not `Succeeded`, and must publish the failure in the event stream before the + terminal state event. +- The mapping must be a single, testable decision. The plan should put it in one place rather + than inline it in the finalization match arms, so that a portable test can reach it. +- The plan must decide whether the capture failure changes the terminal `ExecutionState` alone or + also the reported `ExecutionFailure`, and must record the choice. A caller must be able to + distinguish "the target failed" from "the target succeeded and its declared outputs could not be + collected". +- The event-stream half of this requirement needs a **production publisher** for the chosen event + kind. `ExecutionEventKind::Diagnostic` has none today — every use of the variant in the + repository is in test code. The plan must either add the publisher here, or record an explicit + dependency on the Security M005a degraded-isolation observability corrective + (`plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`), + which needs the same publisher. Two correctives must not grow two divergent publishers for the + same event kind; the server's event-publishing path must be the single place either one of them + extends. The published payload must be bounded by `MAX_EVENT_CHUNK_BYTES`, which + `ExecutionEvent::validate` enforces for `Diagnostic`. + +### 5.4 The platform claim matches the code + +Whichever resolution the plan chooses, exactly one of the following must be true and documented: + +- **Resolution (a)** — safe capture works on the target platform. Then the platform's capability + fact reports capture as available, and the platform claim states that declared artifacts are + captured and published there. +- **Resolution (b)** — the platform cannot support safe capture. Then the platform's capability + fact reports capture as unavailable, an execution that declares outputs terminates in the + truthful non-success state, and the platform claim states that declared outputs are refused on + that platform rather than silently dropped. + +In both cases the README's Windows caveat and the `architecture/overview.md` divergences table must +say the same thing, and the divergences table must gain a row for this defect so that a reader of +`architecture/overview.md` sees it before reading the code. + +### 5.5 Deferral condition + +The full Windows safe-open implementation may be deferred to a follow-on milestone **only if the +fail-closed contract of 4.1 and 5.2 and 5.3 is implemented in this same milestone**. A plan that +defers the Windows implementation *and* leaves the silent-success shape in place is not +acceptable and is not a smaller version of this plan — it is the same defect. + +The plan must record, in its closure record, which resolution it took and, if (b), that the +Windows implementation is outstanding with a named follow-on. + +## 6. Failure, cancellation, restart, and contention semantics + +- **Cancellation and timeout.** The capture eligibility rule today is: the runner completed, the + declared-output list is non-empty, the terminal state is `Succeeded` or `Failed`, and the + failure is not `OutputLimit`. A cancelled, timed-out, or interrupted execution captures nothing + today, and it must continue to capture nothing. The plan must confirm this rule is unchanged and + must not widen it. +- **`OutputLimit`.** An execution killed for output limit is deliberately excluded from capture. + The plan must not change that. +- **A failed target.** An execution whose target failed is still eligible for capture today. + Making a *capture* failure change the terminal state does not change the *target's* failure: + the plan must decide and record how a failed target that also failed to capture reports, so + that the capture failure does not overwrite the target's own failure. +- **Restart.** The capture runs after the runner has terminated and before the terminal event is + published. A crash before the terminal event leaves the execution non-terminal, as today. The + plan must not introduce a durable side effect that a restart could observe as a partial capture. + `capture_declared` already publishes records only after every blob reference has been retained, + so a crash retains extra bytes until expiry rather than losing live data; the plan must not + disturb that ordering. +- **Contention.** The capture path is not concurrent with another capture for the same execution + under the current single-finalizer model. The plan must not introduce a second capture path. +- **No new failure surface.** The plan must not make the artifact path a place where a caller can + provoke a new error class. A capture failure caused by the caller's own declared outputs (a + missing required output, a symlink) must remain a bounded, typed outcome. + +## 7. Compatibility and migration + +- **Wire.** Adding a `#[serde(default)]` field to `ExecutionResult` in `eggwork-core` is a + wire-additive change. The plan must state that the terminal snapshot is not byte-identical + across the change, and that an older client ignores the new field. The client + (`crates/eggwork-client`) should surface the disposition to its own caller; the plan must + confirm whether that requires a client API addition and, if so, record it. +- **No stored format changes.** No blob, workspace, artifact, manifest, or journal row format + changes. +- **No capability-string change**, unless the plan adds a capture-capability feature string, in + which case it must follow the repository's rule that a capability string reflects a runtime + probe and not a compile target, and it must be added to + `crates/eggwork-server/tests/release_contract.rs` if that file enumerates capability strings. +- **No migration.** Nothing is rewritten on disk. A node upgraded with this change reports the + corrected disposition for new executions only; historical terminal snapshots keep their existing + shape, and `finalization_failure` continues to decode. + +## 8. Required tests + +The plan must add the following coverage. Every test must be non-vacuous: it must fail if the +corrective is reverted, and the closure record must say how non-vacuity was established. + +### 8.1 A platform-independent contract test (runs in the ordinary PR gate) + +A new **portable** integration test target in `crates/eggwork-server/tests/` (name to be chosen) +that asserts: + +- the artifact-capture disposition has the required states and serializes and deserializes + correctly; +- a capture outcome of "failed" never maps to terminal state `Succeeded`; +- "not requested" and "failed" are distinguishable from each other, and both are distinguishable + from "completed with zero artifacts"; +- the terminal result and the terminal event agree about the failure. + +This test must not spawn `/bin/sh` and must not use `std::os::unix`, so that it compiles for +every target. It must reach the decision through the public surface established in 5.1-5.3. + +### 8.2 The platform-capability test + +A test that asserts the runtime capture-capability fact reports the *correct* value for the +platform it is running on, and that the fail-closed disposition is produced when capture is +requested but the platform reports it unavailable. On a non-unix target this test is the direct +proof that the platform is handled honestly rather than silently. + +### 8.3 The corrected integration test + +The existing assertion in `crates/eggwork-server/src/lib.rs` +(`blob_protocol_streams_verifies_deduplicates_and_enforces_quota`) that +`state == ExecutionState::Succeeded` with `artifact_count == 0` and +`finalization_failure == Some(ExecutionFinalizationFailure::ArtifactCapture)` must be replaced +with an assertion of the corrected disposition. The replacement must distinguish: + +- an execution with **no** declared outputs (terminal success, no capture attempted, disposition + not-requested); and +- an execution **with** declared outputs whose capture did not complete (terminal state not + `Succeeded`, disposition failed, the failure visible in the event stream). + +The second case must not be produced by making a unix-only test pretend to be non-unix. It must +be driven through whatever seam the plan establishes (an injected capture outcome, or the real +platform stub when the plan runs on a non-unix host), and the closure record must say which. + +### 8.4 The platform-level evidence + +A test that proves the disposition on a **real** non-Unix host, driving the installed daemon, not +a simulated one. See section 9 for how this is run and what it costs. + +### 8.5 Regression guards + +- The existing unix capture tests + (`descriptor_relative_capture_rejects_parent_swapped_to_symlink`, + `missing_required_and_symlink_outputs_fail_without_records`, + `disappearing_output_and_storage_quota_fail_without_publishing_records`) must remain green and + must keep their original meaning. +- The existing happy-path integration assertion (`artifact_count == 1` with + `finalization_failure == None`) must remain green: the corrective must not turn a successful + capture into a failure. + +## 9. How the non-Unix test is actually run + +This is the part of the plan that most needs to be honest, because the repository's Windows CI job +does not currently build the crate under test. + +**The constraint.** `.github/workflows/ci.yml` job `windows-runner` runs +`cargo clippy --locked --workspace --lib --bins --all-features -- -D warnings` and +`cargo test --locked -p eggwork-runner --all-targets -- --nocapture`. Its comment states the +scope explicitly: *"Test targets only for the crate this milestone owns. `eggwork-server` and +`eggwork-client` unit tests are Linux-shaped (they spawn `/bin/sh` and set `0700` modes through +`std::os::unix`), so they do not compile for Windows and are not claimed as coverage. Making them +portable is its own milestone; until then this job's scope is stated, not widened to hide the +gap."* + +Two consequences follow. First, the crate's **library** does compile for Windows — the existing +`--lib --bins` clippy step proves it. Second, the crate's **`#[cfg(test)]` unit-test harness** does +not, so `cargo test -p eggwork-server --lib` cannot run on Windows today. + +**The options, and their trade-offs.** + +- **Option A — extend the Windows job to `cargo test --locked -p eggwork-server --lib`.** + *Trade-off:* this requires the crate's entire unit-test harness to become portable, which the + CI comment explicitly calls a separate milestone. M005a must not absorb that work, and must not + block on it. **Rejected as a precondition for M005a.** +- **Option B — add a portable integration test target and run only that target on Windows.** + `cargo test --locked -p eggwork-server --test ` compiles the library (which already + compiles for Windows) and that one integration test target; it does **not** compile the crate's + unit-test harness, so the Linux-shaped unit tests are not in the way. The cost is that an + integration test can only reach the crate's **public** surface, and the capture code is in + crate-private modules with no `pub use` re-export. Option B therefore depends on section 5.1-5.3 + making the platform fact and the disposition decision publicly reachable — which the plan + already requires for the contract to be testable at all. + *Trade-off:* a small additive public API change to a published crate, and the Windows CI job + grows one step. In exchange, the corrected behaviour is covered in the ordinary PR gate on + every platform, not only at release-qualification time. +- **Option C — hosted qualification on `windows-latest`.** + `.github/workflows/operational-qualification.yml` already runs + `crates/eggwork-server/tests/installed_qualification.rs` against the **installed** daemon on + `windows-latest`. That test file is already portable (`#[cfg(unix)]` guards) and its execution + currently declares `declared_outputs: vec![]`, so it never exercises capture. The plan must + extend it to declare an output and assert the truthful terminal disposition on the real Windows + host. + *Trade-off:* this evidence is workflow-level, tag-gated, and slow. A regression could merge + green in `ci.yml` and be caught only at qualification time. **Option C alone is insufficient** — + it is exactly the gap the CI job's comment refuses to paper over. +- **Option D — make the platform stub reachable from the portable test.** Instead of exposing the + private capture module, expose the *platform fact* (section 5.1) and drive the fail-closed + decision from it. The non-unix stub's refusal is then covered indirectly by a test that runs on + the non-unix host and asserts that the platform reports capture unavailable and that the + disposition follows. + *Trade-off:* the stub's own error path is exercised only on a non-unix host, so the coverage of + "`open_file_beneath` refuses" is host-dependent rather than universal. + +**Required decision.** The plan must choose and record a combination. The recommended combination +is **Option B plus Option C plus Option D**: Option B gives the PR-gate coverage on every +platform, Option D makes the platform behaviour reachable from a portable test, and Option C gives +the real-Windows evidence against installed bytes. The plan must state the trade-off it accepts +and must not claim Windows coverage from a Linux run. + +**CI change.** `.github/workflows/ci.yml` job `windows-runner` must gain a step that runs only the +new portable test target (for example +`cargo test --locked -p eggwork-server --test `). The job's scope comment must be updated in +the same commit to say what is now covered, because the comment currently states the gap that +this step closes. The plan must keep the job's existing honesty: it must not widen the job's +claim beyond the targets it actually runs. + +## 10. Required verification commands + +The repository's pre-submit gate, in the repository's own spelling: + +```text +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +Additional, for this milestone specifically: + +- the new portable test target, run on its own: + `cargo test --locked -p eggwork-server --test ` — and, on a Windows host, the same + command executed by the extended `windows-runner` job; +- the hosted Windows qualification, through + `.github/workflows/operational-qualification.yml`, with the receipt recorded. A Linux run is not + evidence for a Windows claim and must not be recorded as one. + +`--locked` is load-bearing on `clippy` and `test`: a version bump that skips `Cargo.lock` passes +both and then fails every release build. + +## 11. Documentation updates + +- `README.md` — the Windows caveat must state the artifact disposition for a Windows node: + either that declared artifacts are captured and published there, or that they are refused with a + truthful terminal state. The current caveat covers isolation, resource enforcement, and service + management and is silent on artifacts. +- `architecture/overview.md` — the divergences table must gain a row for this defect, with a link + to the deep dive that establishes it. The table currently has row 18 (artifact GC does not + release blob references) and no row for this. +- `architecture/data-plane.md` — its error-model section and its "Honest gaps" section must be + updated to match the corrected code. The "Honest gaps" entry that names the untested non-unix + branches must be revised to reflect the new evidence, and its stale line-number citations must + be replaced with symbol references in the same pass. +- `docs/quickstart.md` and `docs/operations.md` — only if the operator-facing behaviour changes. + The plan must check both and say which, if either, changed. +- `plans/closure/workspace-artifact-transport/005a-status.md` — the closure record itself. + +## 12. Acceptance criteria + +1. No execution can reach terminal state `Succeeded` while a declared output it requested was not + captured. +2. The capture failure is visible on the terminal state, in the event stream, and through the + client's view of the execution — not only as `finalization_failure`. +3. The terminal result distinguishes "no declared outputs" from "declared outputs that vanished" + through a first-class typed disposition, with no arithmetic required of the caller. +4. The runtime capture-capability fact reports the correct value on every platform, and is + reachable from outside the crate-private data-plane modules. +5. The advertised capability set agrees with the runtime fact: a node that cannot capture does not + advertise `"artifact.declared.v1"`, and the plan records what a caller sees when the capability + is absent. +6. The existing integration test that asserted `Succeeded` + `artifact_count == 0` + + `finalization_failure == Some(ArtifactCapture)` has been replaced by an assertion of the + corrected disposition, and the replacement is proven non-vacuous. +7. The new portable test target compiles and passes on a non-unix host, and is wired into the + `windows-runner` CI job. +8. The Windows hosted qualification declares an output and asserts the truthful terminal + disposition against the installed daemon, and the receipt is recorded. +9. The README's Windows caveat and the `architecture/overview.md` divergences table state the + artifact disposition, and the statement matches the code. +10. No bound is widened: `MAX_OUTPUTS`, `MAX_ARTIFACT_FILES`, `MAX_ARTIFACT_TOTAL_BYTES`, + `MAX_BLOB_BYTES`, and every digest bound are unchanged. +11. The unix capture tests keep their original meaning and stay green, and the happy-path + integration assertion (`artifact_count == 1`, `finalization_failure == None`) is still green. +12. The double hash in `crates/eggwork-server/src/artifact.rs` is still present and documented as + accepted. +13. No authentication, lease, generation, fencing, or digest-bound semantics weakened; no queue, + worker selection, priority, fairness, DAG, or semantic retry introduced. +14. `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` and + `cargo test --locked --workspace --all-targets` are green on the same head. + +## 13. Stop conditions + +Stop and re-plan, rather than absorbing the work, if any of the following holds: + +- making the terminal state truthful requires a change to `ExecutionState`, `ExecutionFailure`, or + `ExecutionEventKind` that the existing vocabulary cannot express. That is an architecture + question (`plans/003-planning-process.md#architecture-changes`) and needs an ADR or a canonical + amendment first. +- the truthful disposition would require weakening the unix `NOFOLLOW` capture chain, the + all-or-nothing record publication, or any bound. +- the platform capability fact cannot be made publicly reachable without a breaking change to a + published crate's API. Additive is acceptable; removal is not, and the plan must escalate. +- the portable test target cannot be made to compile for a non-unix target without making the + crate's whole unit-test harness portable. That portability work is a separate milestone; the + plan must escalate rather than absorb it. +- the Windows hosted qualification cannot be run, or shows a disposition different from the one + the code asserts on other platforms. +- the implementation discovers that the correct resolution is to *remove* the `#[cfg(not(unix))]` + capture stub and refuse declared outputs at admission instead of after the target has run. That + is a materially different design — it changes admission rather than finalization — and it crosses + into the control-plane subsystem's ownership of admission. Escalate it. + +## 14. Closure evidence required + +Create: + +- `plans/closure/workspace-artifact-transport/005a-status.md`. + +The record must distinguish code inspection from executed evidence and must include: + +- the reviewed head and the implementation commits; +- a requirement-to-evidence matrix, with one row per acceptance criterion in section 12; +- the exact commands run, from the list in section 10, with their results; +- the **platform matrix actually exercised**: which platforms ran the portable test target, which + ran the hosted qualification, and which did not. "The code compiles for Windows" is not a + platform claim, and a Linux run must not be recorded as Windows evidence; +- the resolution taken — (a) safe capture implemented, or (b) fail-closed contract implemented + with the Windows implementation deferred — and, for (b), the named follow-on milestone; +- the non-vacuity evidence for each new test: how each test was shown to fail when the + corrective is reverted; +- the negative evidence: the case where declared outputs are requested and the capture fails, and + the case where no declared outputs are requested, shown to be distinguishable; +- the documentation status: the README caveat, the divergences-table row, and the + `architecture/data-plane.md` updates, with the exact wording that was adopted; +- the compatibility review: the wire delta, the `#[serde(default)]` behaviour against an older + peer, and confirmation that no stored format changed; +- unresolved findings by severity, with owners; +- the registry and roadmap disposition. + +Do not claim a platform or feature is qualified merely because its code compiles. + +## 15. Handoff notes + +- **The decision this plan exists to force.** Section 5.4. The implementing agent must not treat + "record the failure more visibly" as an acceptable substitute for choosing a resolution. +- **Start with the assertion.** The single most important edit is the existing integration test + that asserts `Succeeded` + `artifact_count == 0`. Change it first, watch it fail, and let the + corrected disposition be driven by that failure. +- **Do not implement the Windows safe open.** It is explicitly deferrable, and attempting it will + consume the milestone. The deferral is legitimate only because the fail-closed contract lands + in the same milestone. +- **The public-reachability requirement is not optional.** Sections 5.1 and 5.3 exist so that the + decision can be tested from outside the crate's private modules. A decision that can only be + reached from inside `artifact.rs` cannot be covered by a portable test target and therefore + cannot be covered on a non-unix host in the PR gate. +- **Boundary discipline.** The data plane owns capture and the meaning of "capture completed". + The server's finalization owns the terminal state. Do not move the terminal-state decision into + `artifact.rs`, and do not let `artifact.rs` decide that an execution succeeded. +- **Do not touch the sibling findings.** WA-2, WA-3, and WA-4 are M005b. This plan must not + change the GC candidate selection, the blob path layout, or the manifest owner-id composite. +- **Do not edit `plans/registry.md`** in this milestone; the registry is owned by the planning + process, not by the implementing agent. +- **Do not edit `plans/000-` through `plans/003-`.** If the corrective appears to require a change + to a canonical document, stop and escalate under + `plans/003-planning-process.md#architecture-changes`. diff --git a/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md b/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md new file mode 100644 index 0000000..c0fb928 --- /dev/null +++ b/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md @@ -0,0 +1,585 @@ +# Workspace and Artifact Transport M005b — GC preview/apply parity and store-owned formats + +Status: proposed + +Class: invariant + +Closure record: `plans/closure/workspace-artifact-transport/005b-status.md` + +Source authority: + +- `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, findings 1.2 (WA-2), 1.3 (WA-3), and 1.4 (WA-4); +- `plans/subsystems/workspace-artifact-transport-roadmap.md`, durable invariants 1 ("Blob bytes must match their digest"), 3 ("Materialization cannot escape the node-owned root"), and 7 ("Storage exhaustion produces typed failure and bounded cleanup"); +- `plans/adrs/ADR-0004-content-addressed-workspaces-and-artifacts.md`; +- `plans/003-planning-process.md#verification-philosophy` and `#corrective-work`. + +## 1. Objective + +Make the operator's GC preview and its apply pass share one implementation, and bring the +store-owned path layout and owner-id formats back under the modules that own them. + +Three properties follow, and all three are required: + +1. The dry-run report and the apply pass select candidates through the **same** store-owned + statement or query, so that preview and apply cannot diverge by construction. +2. The operator's blob inspection path goes through the store's path/ownership API rather than + re-deriving the shard layout, and the workspace materializer obtains blob bytes through the + store's verified-open path rather than a size-only check. +3. The manifest owner-id composite has exactly one producer, and the two inlined call sites use + it. + +This plan changes no public protocol surface and no stored format. It changes only *who computes* +these values, not what they are. + +## 2. Baseline + +### 2.1 The candidate-selection divergence (WA-2) + +The canonical blob candidate selection lives in `crates/eggwork-server/src/blob.rs`, in +`BlobStore::unreferenced_candidates`. Its predicate is + +```sql +SELECT digest, size_bytes FROM blobs +WHERE NOT EXISTS (SELECT 1 FROM blob_references r WHERE r.digest = blobs.digest) +ORDER BY last_used_unix_ms ASC LIMIT ?1 +``` + +`BlobStore::garbage_collect` evaluates that statement in both its dry-run and its real pass. The +doc comment on `unreferenced_candidates` states the rule and the reason it exists: + +> *"Shared by the dry run and the real run on purpose. They select at *different points* in the +> transaction — a preview before expired blob references are deleted, the real pass after — so the +> same statement must be evaluated in both places. Two hand-copied copies of it are what let the +> two paths drift apart and made `NodeGcReport.blob_candidates` under-predict what `--apply` would +> actually remove."* + +`architecture/data-plane.md` records the same reason independently: *"Reclamation queries +deliberately use `NOT EXISTS (SELECT 1 FROM blob_references ...)` rather than the counter."* The +counter is a denormalization — `blobs.reference_count` is written only by the +`blob_reference_insert` and `blob_reference_delete` triggers, never by Rust. + +`crates/eggwork-server/src/operations.rs` does not use that statement. `dry_run_gc` re-implements +the blob candidate query by hand as `WHERE reference_count = 0`: a different predicate over a +different column, against a different source of truth than the one the owner module selected on +purpose. `operations::collect_garbage` routes `dry_run == true` to `dry_run_gc`, and the apply +path opens the real `WorkspaceManager`, `BlobStore`, and `ArtifactStore` and calls their own +collectors. `crates/eggwork-server/src/bin/eggworkd.rs` makes the preview the default for the `gc` +verb (`let dry_run = !args[index..].iter().any(|arg| arg == "--apply");`), so the divergent path +is the one an operator reaches first. + +The same function hand-copies the workspace candidate SQL, the retained-manifest candidate SQL, +and the artifact candidate SQL verbatim from their owner modules, and re-derives the store +metadata filenames (`/metadata.sqlite`, `/metadata.sqlite`, +`.artifacts.sqlite`) that `blob.rs`, `workspace.rs`, and `artifact.rs` own. + +The preview is wrong in both directions. A blob whose `reference_count` is `0` while a +`blob_references` row lingers is predicted for deletion and not removed. A blob whose +`reference_count` is positive while no reference rows exist is not predicted and *is* removed. +Which way a given store errs depends on whether its trigger-maintained counter has drifted from +its reference rows — a property the preview depends on and the apply path does not. + +The existing preview fixture makes the drift structural rather than accidental: the test +`garbage_collection_preview_reads_only_and_reports_bounds` in +`crates/eggwork-server/src/operations.rs` builds a synthetic blob database whose `blobs` table has +columns `(reference_count, size_bytes, last_used_unix_ms)` — **no `digest` column** — so the +canonical predicate cannot even be evaluated against it. + +### 2.2 The path layout re-derived outside the store (WA-3) + +`crates/eggwork-server/src/blob.rs` owns the shard layout in exactly one place: +`BlobStore::path_for` returns `root.join(&digest.as_str()[..2]).join(digest.as_str())`. +`architecture/data-plane.md` records that layout and the reason it is a pure function of the +digest: a digest that survives `BlobDigest::parse` cannot name a location outside the blob root. + +`crates/eggwork-server/src/operations.rs` re-derives it by hand in the operator's blob inspection +verb (`inspect_blob`): it joins `config.blob_root` with `&digest.as_str()[..2]` for the shard +directory and then joins the full digest for the object path. `crates/eggwork-server/src/workspace.rs` +reaches the same place from the other direction, in `materialize_tree`, by calling +`blobs.path_for(digest)` and then opening the result with a plain `File::open`, accepting the bytes +on a **size-only** check (`io::copy` must yield exactly `size_bytes`). + +The materializer's bypass is narrower than it looks but it is real. `materialize` does verify every +referenced blob in its pre-flight, through `blobs.stored_size(digest)` and then +`blobs.verify_existing(digest)`. But `materialize_tree` re-opens the object afterwards and copies +it without re-verifying, so the bytes a workspace actually receives are checked only by length, and +the check that did run happened before the copy. + +### 2.3 The owner-id composite inlined at two sites (WA-4) + +`crates/eggwork-server/src/workspace.rs` defines exactly one producer for the manifest reference +owner id: + +```rust +fn manifest_owner_id(principal_id: &PrincipalId, manifest_digest: &str) -> String +``` + +`architecture/data-plane.md` records the `"{principal}:{manifest_digest}"` composite as part of the +reference-accounting contract for owner kind `"manifest"`. + +Two call sites do not call it. In `WorkspaceManager::manifest_garbage_collect` and in +`WorkspaceManager::reconcile_manifests`, the `principal_id` is read out of a SQL row as a `String`, +and the composite is built inline as `format!("{principal_id}:{manifest_digest}")`. + +**The cause is a signature mismatch, not carelessness.** The helper takes `&PrincipalId`, and +`PrincipalId::new` returns a `Result`, so at these sites there is no validated `PrincipalId` to +hand it. In `manifest_garbage_collect` the row's principal was written from a validated +`PrincipalId` and could simply be re-validated. In `reconcile_manifests` the inlined site is +specifically the branch reached when `PrincipalId::new` **failed** — a corrupt row — so no +validated principal exists there at all, and the composite must still be produced in order to +release the orphan reference. A plan that says "use the existing helper" without resolving this +mismatch is assuming the problem away. + +### 2.4 The historical claim that is no longer sufficient + +`plans/closure/workspace-artifact-transport/004-status.md` records that the collector ordering is +"in both `NodeServer::collect_garbage` and the operator `collect_garbage` path, with matching +dry-run previews". For the operator path's blob candidates, the code does not deliver that. +Per `plans/003-planning-process.md#corrective-work`, that closure record stays immutable; this +corrective owns the defect. + +### 2.5 A note on scope + +`NodeServer::collect_garbage` in `crates/eggwork-server/src/lib.rs` is documented as *"Run a +bounded local maintenance pass; no remote GC route is exposed."* Its only caller in the +repository is a test. The operator's `eggworkd gc` path and this in-process path are two routes to +the same three stores. The plan should note whether the two can be unified, or whether the +in-process path can be removed, as an **in-scope simplification opportunity** — but it must not +let that question swallow the milestone. The three findings above are the deliverable. + +## 3. Scope + +In scope: + +- the candidate selection used by the operator's GC preview and by the operator's GC apply pass, + for blobs, workspaces, retained manifests, and artifacts; +- the operator's blob inspection verb (`inspect_blob`) and the blob path layout it depends on; +- the workspace materializer's acquisition of blob bytes; +- the manifest reference owner-id composite and its two inlined call sites; +- the store metadata filenames that the operator re-derives. + +Out of scope: + +- the *content* of the blob, workspace, manifest, and artifact stores: no schema change, no row + rewrite, no new column, no new table, no new index. +- the artifact GC / blob GC ordering requirement (architecture/data-plane.md already records that + reclaiming an artifact's bytes needs artifact GC then blob GC, guaranteed by call order). This + plan must preserve that ordering; it does not change it. +- divergence 18 of the `architecture/overview.md` table (artifact GC does not release blob + references). That remains a recorded, accepted characteristic. +- the blob store's `reference_count` denormalization. The plan removes the preview's dependence on + the counter; it does not remove the counter or migrate a store whose counter has drifted. +- the double hash in `crates/eggwork-server/src/artifact.rs`. It is documented and accepted. +- M005a (the declared-artifact capture fail-closed contract). The two milestones are independent + and may run in either order. + +## 4. Invariants and non-goals + +### 4.1 The invariant this plan establishes + +**A data-plane fact that a caller or an operator can observe has exactly one producer, and every +other place consumes it rather than restating it.** + +Applied to this milestone, that means: + +1. **Candidate selection has one owner.** The operator's dry-run report and the operator's apply + pass evaluate the *same* store-owned statement. Divergence between them must be structurally + impossible, not merely unlikely. +2. **The owner-module rule becomes enforced.** The statement recorded on the doc comment of + `BlobStore::unreferenced_candidates` — that the same statement must be evaluated in both + places — becomes a tested property rather than a comment. A copy that only a doc comment + forbids is still a copy. +3. **The path layout has one owner.** No module outside `blob.rs` reconstructs the shard layout. +4. **The materializer verifies the bytes it writes.** A workspace's file contents are checked + against the manifest digest, not only against a length. +5. **The owner-id composite has one producer.** No module formats it inline. + +### 4.2 Non-goals + +This plan does not: + +- change any wire protocol, route, capability string, `NodeGcReport` field, or `ResourceInspection` + field; +- change any stored format, schema, row, or on-disk file naming; +- change the GC *ordering* (workspaces → manifests → artifacts → blobs), the bounded-per-pass + semantics, the `clamp(1, 1024)` limit, or the exclusivity of the apply pass; +- change the preview's non-mutating property. `docs/operations.md` states that `gc` "is a preview + by default and reads only", and an existing test asserts it. The preview must remain + non-mutating, and the apply pass must remain the only path that deletes; +- change the apply pass's requirement for an exclusive lock on node state; +- weaken authentication, authorization, lease renewal, generation fencing, or any digest bound; +- introduce a queue, a worker selection policy, a priority or fairness rule, a DAG, or a semantic + retry. Eggwork remains a fixed-target, scheduler-free execution fabric; +- remove the `reference_count` column, the triggers that maintain it, or any other denormalization. + +## 5. Required production changes + +### 5.1 One candidate selection, used by both the preview and the apply pass + +- The candidate selection for blobs, workspaces, retained manifests, and artifacts must live in + the owner module (`blob.rs`, `workspace.rs`, `artifact.rs`) and must be the **only** place the + predicate is written. +- The operator's preview must obtain its candidate sets through that owner code. It must not + contain its own SQL. +- The apply path already calls the owner collectors. It must continue to. + +**The trap the plan must call out.** The obvious implementation — "just open the store in the +preview and call its own dry-run collector" — is wrong as it stands, because `BlobStore::open` is +**not** read-only: it creates the root directory and the metadata database if they are absent, and +it calls `remove_stale_parts`, which deletes stale part files and reconciles index rows. +`WorkspaceManager::open` and `ArtifactStore::open` are likewise not read-only. The preview must +therefore reach the owner code through a **non-mutating** seam. The plan must choose and justify +one of: + +- a read-only, non-reconciling open of each store that exposes the candidate query without + mutating anything; or +- public, side-effect-free candidate-query entry points on the owner modules that the operator + calls, implemented against the owner's own schema knowledge and its own statement; or +- a store-owned pure function that computes the candidate set from the store's metadata path + without opening the store at all. + +The plan must state which it takes and prove that the preview remains non-mutating — the existing +test `garbage_collection_preview_reads_only_and_reports_bounds` is the guard, and the corrected +version of it must keep that property while using the owner's predicate. + +**The predicate must remain the reference-row predicate.** The plan must not reintroduce the +`blobs.reference_count` counter into any reclamation query. `architecture/data-plane.md` records +the deliberate reason. + +### 5.2 The store metadata filenames have one owner + +The operator must not spell `/metadata.sqlite`, `/metadata.sqlite`, or +`.artifacts.sqlite`. Each owner module must expose its metadata path (or the +operator must obtain it from the owner module), so that a change to a store's file name is a +one-line change in the owner. + +### 5.3 The blob path layout has one owner + +`inspect_blob` must resolve the shard directory and the object path through the store's path +ownership rather than re-deriving them. + +The plan must handle the same non-mutating constraint as in 5.1: the inspection verb runs against +an offline store and must not create directories or reconcile metadata. The preferred shape is a +store-owned pure path function (root plus digest in, path out) that `BlobStore::path_for` itself +delegates to, so that the operator and the store share one implementation and the operator needs +no store instance. The plan must confirm that the inspection verb's existing safety properties are +preserved: it rejects a symlinked shard directory, rejects a symlinked object file, and cross-checks +the recorded size against the file's actual length. + +### 5.4 The workspace materializer verifies the bytes it writes + +`materialize_tree` must not accept blob bytes on a size-only check. The bytes written into the +workspace must be verified against the manifest digest. + +- The verification must be performed by a store-owned routine, not by a re-derived hash in the + materializer. +- The verification must be bound to the bytes that are actually copied, so that the pre-flight + check and the copy cannot be separated by a change of the underlying file. +- The plan must record the performance consequence honestly: the pre-flight already re-hashes + every referenced blob, and `architecture/data-plane.md` records that "blob download and workspace + materialization both pay a full re-hash of every input". A verify-while-copying change keeps + that cost roughly where it is; a verify-then-copy change adds one. The plan must state which it + does. +- The plan must not widen any bound, and must not change the staging/rename protocol, the + `0600`/`0700` permissions, the symlink refusal, or the staging cleanup behaviour. + +### 5.5 The manifest owner-id composite has one producer + +The `"{principal}:{manifest_digest}"` format must be written in exactly one place, and both +inlined call sites must go through it. + +The plan must resolve the `&PrincipalId` versus `&str` mismatch explicitly, not assume it away. +The required shape is: + +- one implementation of the format, reachable from both a validated-principal entry point and a + raw-string entry point, with the validated entry point delegating to the raw one (or the + equivalent) so that the format string itself exists once; +- the `manifest_garbage_collect` call site routed through it, with the row's principal validated + where validation is possible; +- the `reconcile_manifests` call site routed through it, with the corrupt-row case handled + deliberately — the plan must state what happens when the principal in a corrupt row cannot be + parsed, and must confirm that the orphan reference is still released rather than leaked. + +The plan must record *why* the raw form exists, so that a later reader does not "fix" it back +into an inline `format!` at the call site. It must also confirm that the composite's shape is +unchanged, because `architecture/data-plane.md` records that an owner id with no colon in it +cannot match any cache row and is therefore treated as an orphan. + +### 5.6 The in-process collector path (bounded simplification, not the deliverable) + +The plan must record a short, factual disposition of `NodeServer::collect_garbage`: whether it can +be unified with the operator path after this milestone, or whether it is retained as-is, and why. +It must not remove it, must not expose it as a remote route, and must not let this question delay +the three findings. + +## 6. Failure, cancellation, restart, and contention semantics + +- **Preview failure.** A preview that cannot evaluate the canonical statement must fail with a + typed error, not degrade to zero candidates. A preview that reports zero because it could not + read the store is indistinguishable from a preview that correctly found nothing, which is + exactly the class of quiet wrongness this plan exists to remove. +- **Apply failure.** The apply path's existing semantics are unchanged: a failure inside the + blob unlink loop still commits the work already done before surfacing the error, because + rolling it back would resurrect rows for blobs whose files no longer exist. The plan must not + change that. +- **Ordering.** Workspace GC → retained-manifest GC → artifact GC → blob GC must be preserved in + both the preview and the apply pass, because the ordering is what makes a blob that has just + become unreferenced collectable in the same pass. +- **Exclusivity.** The apply pass takes an exclusive lock on node state and therefore fails while + the node is running. That is deliberate and unchanged. The preview must remain lock-free and + non-mutating. +- **Restart.** Neither path may introduce a durable side effect that a restart could observe as a + half-completed collection. The apply pass's existing per-store transaction boundaries are + unchanged. +- **Contention.** The blob collector takes the blob store's write lock; the plan must not change + that, and must not introduce a second collector that could run concurrently with it. +- **Cancellation.** The operator's `gc` verb has no cancellation semantics today and the plan must + not add any. + +## 7. Compatibility and migration + +**This plan changes no public protocol surface and no stored format.** Specifically: + +- no route, request shape, response shape, capability string, `NodeGcReport` field, or + `ResourceInspection` field changes; +- no SQLite schema changes in the blob, workspace, artifact, or journal stores: no new table, no + new column, no new index, no changed constraint; +- no on-disk file name changes: the blob shard layout, the store metadata file names, the artifact + metadata file name, the workspace tree layout, and the `.part-` / `.staging-` transient names + are all unchanged; +- no stored row is rewritten, and no migration runs. A store whose `blobs.reference_count` has + drifted from its `blob_references` rows is not repaired by this plan; the plan simply stops the + preview from depending on the drift; +- the `"{principal}:{manifest_digest}"` composite is unchanged, so existing manifest blob + references remain releasable by owner id; +- the operator's `gc` output shape is unchanged. Only the *correctness* of the numbers it reports + changes. + +The one compatibility consequence the plan must record is **performance**: if the materializer +verifies bytes while copying, the materialization path performs a digest computation per file that +it does not perform today. `architecture/data-plane.md` already records that workspace +materialization pays a full re-hash of every input; the plan must state the resulting cost and +whether it changes. + +## 8. Required tests + +Every test must be non-vacuous, and the closure record must say how non-vacuity was established. + +### 8.1 The preview/apply agreement test (required by the milestone) + +A test that proves the preview and the apply pass agree, on the same store state and the same +clock. + +- Build a **real** store through the owner module's own open, not a hand-built synthetic + database. The existing preview fixture creates a `blobs` table with no `digest` column, which + is a fixture shaped to the hand-copied predicate; it must be replaced. +- Seed blobs in each distinct state the predicates can disagree about: a blob with a live + reference, a blob with only an expired reference, a blob with no reference rows at all, and — if + the plan can construct it without fabricating state — a blob whose `reference_count` disagrees + with its reference rows. +- Run the preview and record the candidate set it reports. +- Run the apply pass and record the set it actually removes. +- Assert **`preview ⊆ applied`**, and assert **equality for the same inputs** in the case where + the store contains no expired references. + +**The subset relation is the correct invariant, and the plan must say why.** The owner module's +doc comment records it: the preview selects *before* expired blob references are deleted and the +real pass selects *after*, so on a store that has expired references the apply pass may legitimately +collect strictly more than the preview predicted. A test that asserted bare equality would be +asserting the wrong property and would fail for a correct implementation. Where the inputs contain +no expired references, the two sets must be equal. + +### 8.2 The single-predicate test + +A test that proves the operator's preview does not contain its own candidate SQL: the preview's +candidate set for blobs must equal the set produced by the owner module's canonical statement +evaluated against the same store. This is what makes the owner-module doc comment an enforced +rule rather than a stated one. + +A structural guard is acceptable in addition to the behavioural test — for example, a check that +the operator module contains no reclamation predicate of its own — provided the guard is precise +about what it forbids and does not produce false positives on the owner modules. + +### 8.3 The blob inspection test + +A test that proves `inspect_blob` resolves an object that exists in a real store, and that its +existing safety properties hold: a symlinked shard directory and a symlinked object file are +refused, and a recorded size that disagrees with the file's length is reported as a data error. +A companion test must prove that the inspection verb does not depend on the shard layout being +spelled the same way twice — concretely, that it still resolves the object after the layout is +expressed only through the owner. + +### 8.4 The materializer verification test + +A test that proves the workspace materializer refuses blob bytes that do not match the manifest +digest, and that it still materializes correct bytes. The negative case must be non-vacuous: a +blob whose *length* matches the manifest but whose *content* does not must be refused rather than +written into the tree. + +### 8.5 The owner-id test + +A test that proves the manifest reference owner id has one producer: that the composite released +by `manifest_garbage_collect` and by `reconcile_manifests` is the composite under which the +reference was created, including for a row whose principal does not parse. The negative case must +show that a reference is actually released, so that the test fails if the composite is wrong in a +way that orphans the pin. + +### 8.6 The non-mutating preview test + +The existing property — the preview reads only — must be retained by the corrected fixture, and +must be proven on a store that does not yet exist, so that the preview cannot silently acquire a +creating or reconciling open. + +### 8.7 Regression guards + +- The existing store-level GC tests, the workspace retention test, the artifact retention test, and + the crash-reconciliation test must remain green and keep their original meaning. +- The `NodeServer::collect_garbage` integration test must remain green. +- The `eggworkd gc` command surface must be unchanged. + +## 9. Required verification commands + +The repository's pre-submit gate, in the repository's own spelling: + +```text +python3 scripts/check_execution_ownership.py +cargo fmt --all -- --check +cargo clippy --locked --workspace --all-targets --all-features -- -D warnings +cargo test --locked --workspace --all-targets +cargo check --workspace +python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release +git diff --check +``` + +Additional, for this milestone specifically: + +- the new preview/apply agreement test, run on its own, and then the whole `eggwork-server` test + set; +- a repeated run of the agreement test with the workspace's ordinary parallel test execution, to + confirm the corrected fixture does not depend on serial ordering. + +`--locked` is load-bearing on `clippy` and `test`: a version bump that skips `Cargo.lock` passes +both and then fails every release build. + +## 10. Documentation updates + +- `architecture/data-plane.md` — the blob-store section must describe the single candidate + statement and the one-owner rule; the GC section must describe the preview/apply relationship + accurately, including the subset relation; the materialization section must describe the + verification bound to the copied bytes; and the "Honest gaps" list must be updated. Its stale + line-number citations must be replaced with symbol references in the same pass. +- `architecture/operations-cli.md` — its description of `inspect_blob` currently describes the + shard resolution in the operator's own terms; it must describe the store-owned resolution. Its + description of the GC preview and apply must be updated to state the one-owner rule and the + subset relation. Its stale line-number citations must be replaced with symbol references in the + same pass. +- `docs/operations.md` — the GC section must remain accurate about the preview being read-only + and the apply taking an exclusive lock. If the corrected preview's behaviour is observably + different (it is not expected to be), that document must change. +- `README.md` — no change is expected. If the plan discovers one, it must be justified. +- `plans/closure/workspace-artifact-transport/005b-status.md` — the closure record itself. + +## 11. Acceptance criteria + +1. The operator's dry-run report and the operator's apply pass select candidates through the same + store-owned statement; the operator module contains no candidate predicate of its own. +2. The blob candidate predicate is the reference-row predicate + (`NOT EXISTS (SELECT 1 FROM blob_references ...)`), not the `reference_count` counter. +3. The rule recorded on the doc comment of `BlobStore::unreferenced_candidates` is enforced by a + test rather than stated only in a comment. +4. The preview remains non-mutating, proven on a store that does not yet exist. +5. A test proves the preview's candidate set is a subset of the apply pass's removed set, and is + equal to it for the same inputs when the store contains no expired references. +6. `inspect_blob` resolves object paths through the store's path ownership, and its symlink and + size-cross-check properties are preserved. +7. The workspace materializer refuses blob content that does not match the manifest digest, even + when the length matches, and the refusal is proven non-vacuous. +8. The manifest owner-id composite has exactly one producer; both inlined call sites use it; the + `&PrincipalId` versus `&str` mismatch is resolved by an explicit decision; and a corrupt-row + case still releases its reference. +9. No public protocol surface changed: no route, request, response, capability string, + `NodeGcReport` field, or `ResourceInspection` field. +10. No stored format changed: no schema, row, file name, shard layout, or composite format. +11. The GC ordering (workspaces → manifests → artifacts → blobs), the bounded-per-pass semantics, + the `clamp(1, 1024)` limit, and the apply pass's exclusive lock are unchanged. +12. No bound is widened; no authentication, lease, generation, fencing, or digest-bound semantics + weakened; no queue, worker selection, priority, fairness, DAG, or semantic retry introduced. +13. `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` and + `cargo test --locked --workspace --all-targets` are green on the same head. + +## 12. Stop conditions + +Stop and re-plan, rather than absorbing the work, if any of the following holds: + +- making the preview reach the owner's canonical statement requires the preview to mutate the + store, or requires the apply pass to stop taking an exclusive lock. Both would change an + operator-visible safety property. +- unifying the preview and the apply pass turns out to require a change to the wire shape of + `NodeGcReport`, or to the `gc` command surface. That is a protocol change and needs its own + decision. +- the materializer's verified path cannot be implemented without a performance regression that the + repository cannot accept, or without widening a bound. +- the owner-id resolution requires changing the composite format itself, which would orphan every + existing manifest blob reference. That is a stored-format change and needs an ADR. +- the implementation discovers that the candidate-selection divergence has a second instance in a + module this plan does not name. That is a new finding for the addendum, not for this milestone. +- the work turns out to require changing `architecture/` deep dives' semantics rather than + describing them, or requires an ADR under + `plans/003-planning-process.md#architecture-changes`. + +## 13. Closure evidence required + +Create: + +- `plans/closure/workspace-artifact-transport/005b-status.md`. + +The record must distinguish code inspection from executed evidence and must include: + +- the reviewed head and the implementation commits; +- a requirement-to-evidence matrix, with one row per acceptance criterion in section 11; +- the exact commands run, from the list in section 9, with their results; +- the **non-mutating-preview evidence**: how the preview was proven not to mutate a store that did + not previously exist; +- the **preview/apply agreement evidence**: the seeded store states, the candidate set the preview + reported, the set the apply pass removed, and the relation observed between them, with the + subset relation stated explicitly and the equality case demonstrated separately; +- the non-vacuity evidence for each new test, including how the digest-mismatch materializer case + was shown to fail before the fix and the corrupt-principal owner-id case was shown to fail + before the fix; +- the **compatibility review**: an explicit statement that no wire shape and no stored format + changed, with the performance consequence of the materializer change recorded; +- the documentation status for `architecture/data-plane.md` and `architecture/operations-cli.md`, + including the replacement of their stale line-number citations with symbol references; +- the disposition of the in-process collector path recorded in section 5.6; +- unresolved findings by severity, with owners; +- the registry and roadmap disposition. + +Do not claim a platform or feature is qualified merely because its code compiles. + +## 14. Handoff notes + +- **Start with the fixture.** The single most consequential edit is replacing the synthetic preview + fixture — whose `blobs` table has no `digest` column — with a real store built by the owner + module. That one change is what makes the canonical predicate testable at all. +- **The subset relation is not a weaker claim.** A test that asserts bare equality between the + preview's set and the apply pass's set will fail for a correct implementation, because the two + select at different points in the transaction. The owner module's doc comment records exactly + this. Assert the subset relation, and assert equality separately for the no-expired-references + case. +- **The preview must not gain a mutating open.** `BlobStore::open`, `WorkspaceManager::open`, and + `ArtifactStore::open` all create and reconcile. A preview that opens a store has changed the + operator's contract even if the visible numbers are the same. +- **Do not "just use the existing helper" for the owner id.** The helper takes `&PrincipalId` + and the SQL row gives a `&str`; one of those call sites is reached precisely when the principal + does not parse. The plan must resolve that, and must record why the resolved shape exists. +- **The materializer's cost is real.** Say plainly in the closure record whether the change adds a + digest computation per materialized file or reuses the one the pre-flight already performs. +- **Boundary discipline.** The data plane owns the candidate predicate, the path layout, and the + owner-id format. The operator consumes them. Do not move an operator concern into a store, and + do not let the operator grow its own copy of a store's knowledge. +- **Do not touch M005a's findings.** The declared-artifact capture fail-closed contract belongs to + M005a. The two milestones are independent and may run in either order. +- **Do not edit `plans/registry.md`** in this milestone; the registry is owned by the planning + process, not by the implementing agent. +- **Do not edit `plans/000-` through `plans/003-`.** If the corrective appears to require a change + to a canonical document, stop and escalate under + `plans/003-planning-process.md#architecture-changes`. diff --git a/plans/registry.md b/plans/registry.md index b914c2b..e5e8b08 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -19,6 +19,8 @@ Founding ADRs: Follow-up accepted ADR: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` (Eggwork reads local Gregg optionally; Gregg unchanged). +Proposed ADR, **not yet accepted**: `plans/adrs/ADR-0007-resource-scoped-authorization.md` (decides whether resource-scoped grants are implemented or the inert hook and its plumbing are removed). Security M005c is blocked on it. + ## Status vocabulary - **proposed** — plan exists but is not approved for execution. @@ -80,22 +82,43 @@ Release lineage, and why each tag exists: The repository is no longer planning-only. +## Repository interrogation corrective batch + +A repository-wide code interrogation pass over the reviewed baseline found no `todo!()`/`unimplemented!()` and only five production panic sites, all benign — but it found that several protocol, data-plane, and operator facts are stated by more than one owner, and that the copies have drifted. The findings are grouped into five subsystem corrective addenda, each with bounded implementation milestones: + +| Addendum | Milestones | Class | Status | +|---|---|---|---| +| `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | proposed | +| `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | proposed | +| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a/M005b proposed; **M005c blocked on ADR-0007** | +| `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | +| `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | proposed | + +None of these milestones is dependency-ready. M007 remains the only ready handoff. The batch is registered so that the new findings are visible as current authority rather than as unwritten observations, and so that the five subsystems' roadmaps can be amended to point at their correctives. + +Two findings in this batch were deliberately **not** given a milestone, because they are already owned: + +- the foreground `run` path calling `shutdown()` without `wait()` is already in M007's scope, which commits to a shared shutdown-and-wait convergence contract; +- the inert resource-scoped authorization hook was already recorded as divergence #4, so M005c is a decision about an existing gap, not a new defect report. + ## Active workstreams | Workstream | Status | Current work | Authority | |---|---|---|---| | Optional Gregg host telemetry | **closed; M001 and M002 both closed** | M001 closed the default-off loopback Gregg adapter, normalized cache and single polling owner (`plans/closure/optional-gregg-host-telemetry/001-status.md`, implementation `ac55985`); M002 closed the authorized node telemetry API/client behind a narrow `telemetry` grant (`plans/closure/optional-gregg-host-telemetry/002-status.md`, implementation `5ccb1e6`). The frozen contract is `eggwork_core::NodeTelemetry` schema version 1. No Gregg changes, no Eggwork scheduling, no capability feature added. The CodeGG worker-telemetry consumer is unblocked. | `plans/subsystems/optional-gregg-host-telemetry-roadmap.md`, `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` | -| Foundation / execution core | M001-M003 closed; M004 conditionally closed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004 | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md` | -| Control-plane protocol | closed | M001-M003 complete | `plans/subsystems/control-plane-protocol-roadmap.md` | -| Workspace / artifacts | closed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`) | `plans/subsystems/workspace-artifact-transport-roadmap.md` | -| Security / isolation / resources | closed | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md` | -| Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md` | +| Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | +| Control-plane protocol | M001-M003 closed; M004 corrective proposed | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | +| Workspace / artifacts | M001-M004 closed; M005a and M005b correctives proposed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | +| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a/M005b proposed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) and M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | +| Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready; M008a/M008b proposed | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. A repository interrogation pass added M008a (five live metrics are never reported by the operator surface; one `active_executions` field name carries two meanings; every configuration fault collapses into one unhelpful message) and M008b (the release harness re-derives facts that already have an owner, and the design record's line citations and size figures are stale with no gate) | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md`, `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | ## Dependency-ready implementation plans M007 is the only dependency-ready Eggwork implementation handoff. The optional Gregg telemetry line is closed and remains dependency history. Closed downstream CodeGG rows remain dependency history. +The repository interrogation corrective batch is registered but is **not** dependency-ready: every milestone in it is `proposed`, and Security M005c is `blocked` on ADR-0007. It may be executed in parallel with M007, and the five correctives are mutually independent of one another. + | Workstream | Milestone | Status | Implementation plan | Handoff note | |---|---|---|---|---| | Operations / distribution | M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md` | Keep Eggup as manager owner; explicit `service-host` plus shared shutdown/wait lifecycle; dedicated Windows test/SCM qualification surface. Foundation M004 is already conditionally closed, so M007 is independently implementable and should ride the same next immutable candidate for final M004 qualification. | @@ -145,6 +168,15 @@ M007 is the only dependency-ready Eggwork implementation handoff. The optional G | CodeGG M003 content-aware derived workspace transfer | closed downstream | Closed in CodeGG at `d51afe46` (implementation `1ce377ce`; hosted `36745285774` success, live derived reuse under required isolation) on Eggwork `e6a5d82`; closure record `dbowm91/codegg: plans/closure/eggwork-fixed-target-remote-execution/003-status.md` | | CodeGG M004 remote AgentRun worker | deferred | M003 is closed; only the stable AgentRun worker-entry contract remains outstanding | | Operations M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md`. Explicit `service-host --config` entry, shared shutdown+wait convergence, normal STOP does not create persistent drain, dedicated native Windows contract/SCM evidence, Eggup remains manager owner. Foundation M004 is already conditionally closed; the next immutable candidate should contain both for final M004 qualification. | +| Control-plane M004 shared protocol contract corrective | **proposed** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. | +| Workspace M005a declared-artifact capture fail-closed corrective | **proposed** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`. | +| Workspace M005b GC preview and store ownership corrective | **proposed** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass use different candidate predicates, in a module whose own doc comment states the two must be shared — a stated invariant already violated in the sibling module. Also covers the blob store's path layout and the manifest owner-id format being re-derived outside their owners. Addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`. | +| Security M005a degraded-isolation observability corrective | **proposed** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` is emitted only from test code, so a degraded best-effort isolation or resource enforcement is invisible to an event-streaming caller and is discoverable only by polling the terminal snapshot. Addendum: `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`. | +| Security M005b sandbox-helper environment parity corrective | **proposed** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list is maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule has no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix must be a shared artifact plus a pinning test, not a shared crate. **This is the most severe finding in the batch.** The duplication is live: the runner's launch-spec builder starts from a fixed baseline (`PATH`, `LANG`, `LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER`) and then appends every non-denied caller key, and none of those baseline keys except `PATH` is denied. A caller that sets `LANG` therefore produces a launch specification with two `LANG` entries; the helper refuses a specification with duplicate keys with status 12; the runner reads that as a pre-target setup failure and — for a **best-effort** request only — rewrites the sandbox outcome to `NotApplied` and **re-spawns the target directly with no Landlock ruleset at all**. The observable result today is a successful, entirely unconfined execution whose only record of the degradation is a `NotApplied` in the terminal snapshot. The `Required` path is unaffected and still fails closed. Addendum: `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`. | +| Security M005c resource-scoped authorization corrective | **blocked** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. Blocked on ADR-0007 (`plans/adrs/ADR-0007-resource-scoped-authorization.md`, **proposed, not accepted**), which must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. The gap itself is already recorded as divergence #4; this is a decision about a known gap, not a new defect. | +| Operations M008a operator surface truthfulness corrective | **proposed** | `plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md`. Five live metrics are incremented by the server and never reported by `eggworkd status`/`eggworkd metrics`; one `active_executions` field name carries two different meanings across the API and the CLI; and every configuration fault collapses into the single unhelpful message `configuration is invalid or unreadable`. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | +| Operations M008b release harness and documentation single-sourcing corrective | **proposed** | `plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md`. The release harness re-derives the workspace version, the release asset inventory, the install identities, and the target classification that already have owners; the tag guard's own docstring deliberately keeps it out of CI, so the defect is the divergent parser and the absence of any automated exercise, not the missing CI wiring. Roughly 92% of the design record's line-number citations no longer point at the symbol they claim, every crate size figure in `architecture/overview.md` is stale, and divergence #20 now describes a fixed issue as open. CI type-checks feature-gated code it never executes — the qualification workflow is `workflow_dispatch`-only, so the suite runs on no ordinary pull request, and adding `--all-features` would not close the gap because those tests are `#[ignore]`d — while one runner test passes with zero assertions on the normal CI path. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | +| Foundation M005 runner request validation parity corrective | **proposed** | `plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md`. The runner's private request validation is a weaker restatement of the `eggwork-core` contract — it accepts environment names core rejects and does not detect duplicate names — and the runner's public constructor and public environment setter reach that gate without passing through core validation at all, contradicting the runner's own documented claim that callers cannot bypass protocol bounds. Addendum: `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md`. | Operations M003, M002a, and conditionally M004 are closed. Foundation M004 has since implemented and native-qualified the Windows process-tree backend, but no immutable candidate contains it yet. M004 used the historical `v0.1.0` draft only as discovery evidence and qualified a corrected `v0.1.1` draft with the then-current support matrix. Do not widen M004 into runtime release discovery, service-manager duplication, or Eggpack/Eggup interoperability. Windows service hosting is a **new** milestone, not an M004 continuation, because it requires a service-control dispatcher that the daemon does not have. @@ -182,6 +214,18 @@ Operations release publication [HUMAN ACTION: §14] <----+--> public boot Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 authenticated API/client [CLOSED] --> CodeGG worker telemetry consumer [UNBLOCKED; separately registered] + +Repository interrogation corrective batch [PROPOSED] --+--> Control-plane M004 shared protocol contract [PROPOSED] + +--> Workspace M005a artifact capture fail-closed [PROPOSED] + +--> Workspace M005b GC preview and store ownership [PROPOSED] + +--> Security M005a degraded-isolation observability [PROPOSED] + +--> Security M005b helper environment parity [PROPOSED] + +--> Security M005c resource-scoped authorization [BLOCKED on ADR-0007] + +--> Operations M008a operator surface truthfulness [PROPOSED] + +--> Operations M008b release harness and docs single-sourcing [PROPOSED] + +--> Foundation M005 runner request validation parity [PROPOSED] + +The batch is mutually independent and independent of M007. It introduces no inter-milestone dependency, and it must not be sequenced behind M007 or folded into it. ``` Operations M002 is not a dependency of CodeGG M001. The canonical long-term roadmap already defines CodeGG Phase 7 as depending on Eggwork Phases 0-5, not completion of Phase 6 packaging. diff --git a/plans/subsystems/control-plane-protocol-roadmap.md b/plans/subsystems/control-plane-protocol-roadmap.md index aa0bd67..f47eed7 100644 --- a/plans/subsystems/control-plane-protocol-roadmap.md +++ b/plans/subsystems/control-plane-protocol-roadmap.md @@ -1,6 +1,6 @@ # Control-Plane Protocol Roadmap -Status: active roadmap +Status: active roadmap; M001-M003 closed; M004 shared-contract corrective proposed Canonical authority: @@ -123,6 +123,32 @@ Exit conditions: - protocol-version mismatch is typed; - slow event consumers cannot produce unbounded node memory. +### M004 — Shared protocol contract corrective + +Class: invariant + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md` + +Objective: + +Give each protocol contract fact a single owner so that a change to it is a compile-time or test-detectable event rather than a convention. The batch covers the API schema version, which is currently declared independently by the client that sends it and the server that hard-rejects on it; the capability feature-name strings, which are re-typed across the runner, the server, and the client; and the terminal-state classification, which is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. + +Exit conditions: + +- the client and the server consume one schema-version constant from `eggwork-core`; +- capability feature names have one producer-side owner and the consumers import it; +- the terminal/non-terminal classification has one owner in `eggwork-core` and is total and disjoint over the state enum; +- no capability feature-string value changes — the frozen semantics in the security remote-admission corrective remain byte-for-byte; +- no wire representation changes. + ## 4. Local admission model Local admission is immediate bounded protection. Initial decisions may account for: diff --git a/plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md b/plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md new file mode 100644 index 0000000..4cefffe --- /dev/null +++ b/plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md @@ -0,0 +1,301 @@ +# Control-Plane Protocol Post-Closure Corrective — Shared Protocol Contract Ownership + +Status: active corrective; M004 proposed + +Predecessor roadmap: + +- `plans/subsystems/control-plane-protocol-roadmap.md` + +Historical predecessor closures: + +- `plans/closure/control-plane-protocol/001-status.md` — authenticated fixed-target execution +- `plans/closure/control-plane-protocol/002-status.md` — idempotency, leases, resumable events, recovery +- `plans/closure/control-plane-protocol/002-lease-expiry-race-correction.md` — lease-expiry race correction +- `plans/closure/control-plane-protocol/003-status.md` — Eggress route adapter and protocol compatibility hardening + +Canonical authority remains: + +- `plans/000-long-term-specification.md` +- `plans/001-terminology-and-domain-model.md` +- `plans/adrs/ADR-0001-fixed-target-scheduler-free-execution.md` +- `plans/adrs/ADR-0002-eggstack-transport-and-mtls.md` +- `plans/adrs/ADR-0003-execution-idempotency-leases-and-fencing.md` +- `plans/003-planning-process.md` + +Finding source: + +- repository-wide code interrogation pass over the reviewed baseline, covering `crates/eggwork-core/src/lib.rs`, `crates/eggwork-client/src/lib.rs`, `crates/eggwork-server/src/lib.rs`, `crates/eggwork-server/src/store.rs`, `crates/eggwork-server/src/operations.rs`, `crates/eggwork-runner/src/lib.rs`, and `crates/eggwork-sandbox-helper/src/main.rs`, cross-read against `architecture/overview.md`, `architecture/core-domain.md`, `architecture/client-transport.md`, `architecture/server-node.md`, `architecture/storage-journal.md`, `architecture/sandbox-helper.md`, and `architecture/runner-execution.md`. + +Relationship to the recorded divergences table: + +- **CP-2 is new.** It is not recorded in `architecture/overview.md`. +- **CP-3 is a widening of divergence #12**, not a wholly new defect. Divergence #12 says the terminal/non-terminal sets "are spelled out in four places with nothing keeping them in sync". The actual count of enumeration sites in the server is nine, and the root cause #12 does not name — that `eggwork-core` owns no terminal concept at all — is documented separately in `architecture/core-domain.md` under **States**. This corrective owns the delta: the count, the root cause, and the ownership rule. +- **CP-1 is new.** It is not recorded in `architecture/overview.md`. Divergence #20 is adjacent in subject area (the client's wire framing) but describes a different fact, and its text is now stale — see §7.3. This corrective records that observation; it does not own #20's disposition. + +All three findings share one root cause: **a protocol contract fact is stated by string literal in more than one crate, with no shared owner and no test pinning the two sides together.** The facts are individually small. The failure mode they share is not: a rename or a bump on the producing side silently desynchronizes the consuming side, and no compiler or test in the workspace objects. + +## 1. Findings + +### 1.1 CP-1 — `API_SCHEMA_VERSION` is defined twice, in the two crates that must agree + +**What the contract is supposed to be.** One control-plane schema version, owned by one crate, checked by every side that sends or receives it. + +**What the code actually does.** + +- `crates/eggwork-client/src/lib.rs` declares a private `const API_SCHEMA_VERSION: u16 = 1;` and stamps it into every request body it builds — the execute body, the control body, the workspace-create body, and the workspace-derive body. +- `crates/eggwork-server/src/lib.rs` declares its own private `const API_SCHEMA_VERSION: u16 = 1;`. The server compares the received value against it and hard-rejects any mismatch with HTTP 426 `protocol_version` — in the workspace-create handler, the workspace-derive handler, the execute handler, the execute spec's own embedded version, the cancel/renew path, and again when it stamps its own responses. +- Nothing links the two declarations. `crates/eggwork-client/Cargo.toml` already depends on `eggwork-core`, so a shared owner is available without a new dependency edge. + +The correct precedent already exists in the same codebase. `crates/eggwork-core/src/lib.rs` declares `pub const NODE_TELEMETRY_SCHEMA_VERSION: u16 = 1;`, and that one constant is consumed by the client's telemetry reader, by the server's telemetry projection, and by core's own `NodeTelemetry::validate`. That is exactly the shape `API_SCHEMA_VERSION` should take. + +**Consequence.** A server-side bump silently breaks every deployed client with a runtime HTTP 426 at request time. Both sides agree with themselves, so no test in the workspace can catch it: there is no artifact in the build that fails when the two constants diverge. + +### 1.2 CP-2 — Capability feature-name strings are duplicated across the runner/server/client boundary + +**What the contract is supposed to be.** A capability feature name is a wire token. The node advertises it; a consumer matches on it. Producer and consumer must refer to the same token. + +**What the code actually does.** + +- The runner produces the names. `crates/eggwork-runner/src/lib.rs`, in `TrustedLandlockSetup::execution_capabilities`, pushes the literal `"isolation.landlock.workspace-rw.v1"` and carries the literals `"resources.cgroups-v2.memory"`, `"resources.cgroups-v2.cpu"`, and `"resources.cgroups-v2.pids"` in its probe table. +- The same file already declares `pub const LANDLOCK_WORKSPACE_RW_CAPABILITY: &str = "isolation.landlock.workspace-rw.v1";` with the identical value — but the push site does not use it. The constant is used by its own freezing test and by the server, while the producer of the value types it out again. +- The server consumes the names. `crates/eggwork-server/src/lib.rs`, in `check_resources_supported`, matches `"resources.cgroups-v2.memory"`, `"resources.cgroups-v2.cpu"`, and `"resources.cgroups-v2.pids"` as literals. The server's `check_isolation_supported` is the one exception in this group: it already imports `eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY`. +- The server also produces `"exec.argv.v1"` in `static_capability_features`, and the client independently hardcodes `"exec.argv.v1"` in `NodeClient::ensure_protocol_compatible`. +- The `"workspace_rw"` sandbox profile name is written as a literal in the runner — in `TrustedLandlockSetup::prepare`'s profile check, in `RunnerRequest::from_spec`'s profile construction, and in `SandboxChannel::new`'s profile check — and once in `crates/eggwork-sandbox-helper/src/main.rs`, in the `LaunchSpec` validation that rejects any other profile. The runner's seven occurrences include doc comments; the helper's production occurrence is a single site, with six more in the helper's integration test. + +**Consequence.** A rename on the producer side makes the consumer silently stop recognizing the capability, producing a runtime `capability_mismatch` at admission with no compile-time signal and no test pinning the two sides. The Landlock capability is the sharpest illustration: the constant exists, the value is identical, and the site that emits the value still types it out. + +The `"workspace_rw"` profile name is a special case, because `crates/eggwork-sandbox-helper/Cargo.toml` declares no workspace-crate dependencies at all — it is a standalone binary whose only workspace relationships are dev-dependencies. The helper therefore cannot import a shared constant from the runner or from core. That constraint is a rule, not an obstacle to route around; §3.3.4 states how the helper's literal is pinned instead. + +### 1.3 CP-3 — The terminal-state set is enumerated many times, and `eggwork-core` owns no terminal concept + +**What the contract is supposed to be.** One classification of `ExecutionState` into terminal and non-terminal, owned by the crate that defines the enum. + +**What the code actually does.** + +`crates/eggwork-core/src/lib.rs` defines `ExecutionState` as a flat nine-variant enum — `Accepted`, `Preparing`, `Running`, `Cancelling`, `Succeeded`, `Failed`, `Cancelled`, `TimedOut`, `Interrupted` — and owns no terminal concept: there is no `is_terminal` helper, no terminal grouping, and no terminal-state list anywhere in the crate. `architecture/core-domain.md` states this explicitly: "There is no `is_terminal()` helper and no terminal-state grouping in this crate — the five terminal variants are a convention that the server applies." + +The convention is applied nine times across the server: + +| Site | What it enumerates | +|---|---| +| `crates/eggwork-server/src/store.rs` — `fn state_name` | hand-written enum-to-string map over all nine variants, duplicating the serde derive's PascalCase naming | +| `crates/eggwork-server/src/store.rs` — `fn is_terminal_name` | the terminal set as five string literals | +| `crates/eggwork-server/src/store.rs` — the generation-reservation path in `ExecutionStore::reserve` | an inline `matches!` over the same five string literals, which does not call `is_terminal_name` even though that helper exists in the same file | +| `crates/eggwork-server/src/lib.rs` — `fn is_terminal` | the terminal set as five enum variants | +| `crates/eggwork-server/src/lib.rs` — the artifact-capture eligibility check | an inline two-element subset, `ExecutionState::Succeeded \| ExecutionState::Failed` | +| `crates/eggwork-server/src/lib.rs` — the terminal-to-metric-name match | a wildcard-terminated match over the five terminal states | +| `crates/eggwork-server/src/operations.rs` — the active-execution count | the non-terminal set as four enum variants | +| `crates/eggwork-server/src/operations.rs` — `fn count_active_executions` | a parallel SQL literal list of the same four state names | +| `crates/eggwork-server/src/operations.rs` — `fn state_label` | a second full enum-to-string map, using snake_case where `state_name` uses PascalCase | + +**Consequence.** Adding a state variant requires edits at roughly nine sites, and nothing mechanically prevents the sets from drifting. Two of the sites are already visibly adrift in shape: the artifact-capture subset is not the terminal set and would be wrong to conflate with it, and `state_label` uses a different casing convention from `state_name` for the same enum. + +The client does not currently duplicate the terminal set — `crates/eggwork-client/src/lib.rs` never classifies a state. That is precisely why putting the classification in `eggwork-core` matters: core is the one crate both `eggwork-server` and `eggwork-client` depend on, so the client becomes able to ask the same question the server asks, without either side owning a private copy of the answer. + +## 2. Corrective milestone + +### M004 — Shared protocol contract ownership + +Class: invariant + +Status: proposed + +Implementation plan: + +- `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md` + +Objective: + +Give each of the three duplicated contract facts a single owner, so that client, server, and runner agree by construction rather than by convention, and a future change to any of them is a compile-time or test-detectable event. + +Status is **proposed**, not **ready**, for three reasons recorded here rather than left to the implementing agent: + +1. M004 requires an intentional, reviewed ownership change to `eggwork-core`: the crate must take ownership of a terminal-state classification it does not currently have. `plans/003-planning-process.md` §8 requires that an ownership-boundary change be recorded as an ADR or canonical amendment before the implementation lands. That record does not exist yet. +2. Two dispositions are still open and are not implementation detail: where the operator-facing `state_label` map lives, and whether the artifact-capture eligibility predicate stays server-local or moves to core. §3.4.4 states the constraint on each; the plan must record the decision it makes. +3. This corrective is not registered in `plans/registry.md`. Registry ownership is not this document's, so a handoff before registration would present a plan as ready when the control surface does not say so. + +## 3. Shared-contract design + +### 3.1 One owner per contract fact + +The corrective establishes one rule and applies it three times: + +> A protocol contract fact — a schema version, a capability feature name, a state classification — has exactly one owner. Every producer and every consumer refers to it through that owner. The owner is the lowest crate that every participant already depends on, or the producing crate when every consumer already depends on the producer. + +The second clause matters, because "the producer owns it" is not always available. `crates/eggwork-client/Cargo.toml` depends on `eggwork-core` only; the client cannot depend on the server, and the server cannot be depended upon by the client without inverting the workspace's one-way dependency rule. Where producer-ownership is therefore impossible, the owner is the crate both sides already share. + +The workspace dependency rules this corrective operates under are fixed: `eggwork-core` and `eggwork-sandbox-helper` depend on nothing internal; `eggwork-client` depends on `eggwork-core`; `eggwork-server` depends on `eggwork-core` and `eggwork-runner`; `eggwork-client` is a dev-dependency of `eggwork-server` only. + +### 3.2 CP-1 — the API schema version + +Owner: `eggwork-core`. + +`crates/eggwork-core/src/lib.rs` declares `pub const API_SCHEMA_VERSION: u16 = 1;` alongside `NODE_TELEMETRY_SCHEMA_VERSION`, with a doc comment stating that it is the control-plane request/response schema version and that every producer and consumer of a versioned body refers to this constant. + +`crates/eggwork-client/src/lib.rs` and `crates/eggwork-server/src/lib.rs` delete their private constants and import the core one. + +The precedent is `NODE_TELEMETRY_SCHEMA_VERSION`, which already has exactly this shape: one `pub const` in core, consumed by the client, the server, and core's own validator. + +### 3.3 CP-2 — capability feature names and the sandbox profile name + +#### 3.3.1 Runner-produced resource capabilities + +Owner: `eggwork-runner`, because the server already depends on the runner and the runner is where the probe produces the fact. + +`crates/eggwork-runner/src/lib.rs` exports public constants for the three cgroup-v2 resource feature names alongside `LANDLOCK_WORKSPACE_RW_CAPABILITY`. `TrustedLandlockSetup::execution_capabilities` uses those constants in the probe table instead of literals. + +#### 3.3.2 The Landlock capability's unused constant + +Owner: `eggwork-runner`, already correct. + +The only change is that `TrustedLandlockSetup::execution_capabilities` pushes `LANDLOCK_WORKSPACE_RW_CAPABILITY` instead of the literal with the identical value. The value itself does not change. `crates/eggwork-server/src/lib.rs` needs no change for this name — `check_isolation_supported` already imports the constant. + +#### 3.3.3 `exec.argv.v1` + +Owner: `eggwork-core`. + +This is the case where producer-ownership is impossible. The server produces the name, in `static_capability_features`; the client consumes it, in `NodeClient::ensure_protocol_compatible`; and the client cannot depend on the server. `eggwork-core` is the crate both already depend on, and it already models the type the name appears in — `NodeCapabilities.features` — so the constant belongs there beside the capability contract rather than in either endpoint crate. + +#### 3.3.4 The `workspace_rw` profile name + +Owner: `eggwork-runner` for the producing side. + +`crates/eggwork-runner/src/lib.rs` exports a public profile-name constant and uses it at all three of its sites: the profile check in `TrustedLandlockSetup::prepare`, the profile construction in `RunnerRequest::from_spec`, and the profile check in `SandboxChannel::new`. + +`crates/eggwork-sandbox-helper/src/main.rs` keeps its literal. The helper has no workspace-crate dependency, and adding one would violate the standalone-binary rule that keeps the helper out of the workspace build graph. The helper's literal is therefore pinned by a test rather than by an import: the helper's integration test `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` already dev-depends on `eggwork-runner`, so it can assert that the profile the runner produces is the profile the helper accepts, and that a profile that differs is refused before the target spawns. + +This is the one case where the corrective does not achieve "by construction" on both sides, and it says so plainly rather than implying the helper was also fixed. + +#### 3.3.5 What this corrective does not touch + +The capability feature-name **values** are frozen by `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md` §3, which defines the semantics of `exec.argv.v1`, `isolation.landlock.workspace-rw.v1`, `network.unrestricted.v1`, and the three `resources.cgroups-v2.*` names. This corrective preserves those values byte-for-byte and re-specifies none of their semantics. A change to any of those values is a compatibility break that needs an ADR, not this corrective. + +### 3.4 CP-3 — the terminal-state classification + +Owner: `eggwork-core`. + +#### 3.4.1 One classification, in the crate that defines the enum + +`crates/eggwork-core/src/lib.rs` gains, for `ExecutionState`: + +- a terminal predicate and its complement; +- the canonical wire spelling of a state — the PascalCase name that the enum's derived `Serialize` already produces, and that `crates/eggwork-server/src/store.rs` writes into the `state` column; +- a way to enumerate every variant, so a property test can range over the whole enum rather than over a hand-written list that would itself be another copy. + +The wire representation of `ExecutionState` does not change. The enum keeps its derived `Serialize`/`Deserialize` with no rename attribute, so it stays externally tagged PascalCase. The canonical spelling is a function of the enum, not a parallel table. + +#### 3.4.2 Exhaustive by construction + +The classification must be written as a `match` over all nine variants with no wildcard arm, so that adding a tenth variant is a compile error in core rather than a silent behavioural change downstream. The same applies to the wire-spelling function and to any server-side map derived from it. + +This is the mechanism that makes the corrective's central claim true: adding a state variant becomes a compile-time event. + +#### 3.4.3 Derived server helpers + +- `crates/eggwork-server/src/store.rs`: `fn state_name` and `fn is_terminal_name` are removed in favour of the core-owned spelling and classification; the inline `matches!` in the generation-reservation path calls the shared classification instead of repeating the five string literals; the `state` column continues to hold exactly the same PascalCase strings it holds today. +- `crates/eggwork-server/src/lib.rs`: `fn is_terminal` is removed in favour of the core-owned predicate. +- `crates/eggwork-server/src/operations.rs`: the non-terminal `matches!` and the SQL literal list in `fn count_active_executions` are derived from the shared classification rather than hand-typed. The `state` column values the SQL matches against remain the same strings. + +#### 3.4.4 Two things that are *not* the terminal set + +The corrective must not conflate either of these with terminality: + +- **Artifact-capture eligibility.** The server captures workspace outputs only for `Succeeded` and `Failed`, not for all five terminal states. That is a narrower policy subset, not the terminal set. It must keep its own name and its own test. +- **`state_label`'s casing.** `crates/eggwork-server/src/operations.rs` renders operator-facing state labels in snake_case, while the wire/column spelling is PascalCase. The operator-visible output must not change, so the label casing is a display projection and is not a protocol fact. It may stay server-local or move to core, but whichever it does, it must be total over the enum and pinned by a test, and it must not become a third independent naming scheme. + +### 3.5 What the corrective does not change + +- No wire field, field name, or value. +- No capability feature-string value and no capability semantics. +- No authorization, lease, generation, fencing, or digest behavior. +- No runtime behavior of the runner or the server beyond replacing a literal with the constant it already equals. +- No new crate dependency edge. + +## 4. Durable invariants + +These extend the control-plane subsystem's existing invariants; none of them is weakened. + +1. A protocol contract fact has exactly one owner. +2. A consumer never re-types a producer's contract token; it imports it. +3. The owner of a contract fact is a crate every participant already depends on, or the producing crate when every consumer already depends on the producer. +4. A change to an owned contract fact is a compile-time or test-detectable event, not a runtime desynchronization. +5. The terminal/non-terminal classification is total over `ExecutionState` and disjoint between the two sets, and is owned by `eggwork-core`. +6. The canonical wire spelling of a state is a function of the enum, and equals the enum's serde representation. +7. `eggwork-core` continues to have no internal dependencies. +8. `eggwork-sandbox-helper` continues to have no workspace-crate dependency. +9. No capability feature-name value changes under this corrective. +10. Authentication, authorization, lease, generation, fencing, and digest bounds are unchanged. +11. Eggwork remains scheduler-free: one explicit target, typed local refusal, caller-owned retry. +12. The historical M001–M003 closure records remain immutable; this corrective owns the newly discovered shared-contract defect. + +## 5. Compatibility and migration + +**Wire compatibility.** Unchanged. The schema version value stays `1`; the capability feature names keep their exact byte sequences; `ExecutionState` keeps its serde representation; the server's `state` column keeps the same PascalCase strings; `eggworkd status` keeps its current snake_case labels. + +**Behavioral compatibility.** Unchanged. Every literal this corrective replaces is replaced by a constant whose value is identical to the literal it replaces. There is no runtime path whose behavior differs before and after, on any platform. + +**Rust API compatibility.** The corrective adds public constants and public predicates. It does not remove any public item. The two private `API_SCHEMA_VERSION` constants are crate-private and are removed, which is not a public API change. + +**Migration.** None. There is no stored-format migration, no rollout step, and no coordination with deployed clients or nodes, because no observable value changes. + +**The one asymmetry worth recording.** Sharing a constant makes divergence *harder*, not impossible, in one direction: the server and client now move together at build time, but an already-deployed client and an already-deployed server were compiled separately and can still differ. The corrective removes the possibility of *creating* that skew inside one build; it cannot remove skew between two existing builds. Any future schema-version bump still needs a compatibility story of its own, and this corrective does not provide one. + +## 6. Downstream relationships + +- `eggwork-client` and `eggwork-server` are the two CP-1 participants and the two CP-2 parties on opposite sides of the `exec.argv.v1` boundary. Both are in scope. +- `eggwork-runner` is the producer for the Landlock and cgroup capability names and for the `workspace_rw` profile name. It is in scope as a producer, not as a consumer. +- `eggwork-sandbox-helper` is **not** modified. Its `workspace_rw` literal is pinned by a test that lives in the helper's existing integration test, which already dev-depends on the runner. +- `eggwork-core` gains ownership of the API schema version, the `exec.argv.v1` feature name, and the terminal-state classification. This is an ownership change to the crate that currently owns nothing about protocol negotiation, and it is the part of this corrective that needs an architecture record rather than only an implementation. +- The security/isolation/resource remote-admission corrective C001 already closed and its capability contract remains authoritative for feature-name semantics. This corrective must not reopen it. `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` §6 already anticipates a "control-plane shared-contract corrective" and states that the two do not interact; that statement holds. +- Operations M007 (Windows service host) is independent. It may proceed in parallel. +- CodeGG consumes Eggwork's capability features from outside the workspace. Since this corrective changes no feature value, no CodeGG change is implied and no CodeGG re-qualification is triggered. + +## 7. Exit conditions + +M004 closes only when: + +### 7.1 CP-1 + +- Exactly one `API_SCHEMA_VERSION` declaration exists in the workspace, and it is public in `eggwork-core`. +- Neither `crates/eggwork-client/src/lib.rs` nor `crates/eggwork-server/src/lib.rs` declares a local schema-version constant. +- The client's request bodies and the server's acceptance check refer to the same constant, provably so from the source. +- A test fails if the client-sent version and the server-accepted version can diverge, and a test asserts the server's 426 rejection path uses the shared constant. + +### 7.2 CP-2 + +- The runner's capability-name constants are `pub` in `eggwork-runner`, and the runner's advertisement site uses them rather than literals. +- The server's `check_resources_supported` imports the runner's constants rather than re-typing them. +- `exec.argv.v1` has one owner reachable by both the server and the client, and neither endpoint crate re-types it. +- The helper's `workspace_rw` literal is pinned by a test that fails if the runner's profile name and the helper's accepted profile diverge, and the negative case proves the helper still refuses a different profile before the target spawns. +- Every capability feature-name value is byte-for-byte what it was before the corrective. + +### 7.3 CP-3 + +- `eggwork-core` owns the terminal/non-terminal classification, and the classification is exhaustive over the enum with no wildcard arm. +- No terminal-state enumeration remains in `crates/eggwork-server/src/store.rs`, `crates/eggwork-server/src/lib.rs`, or `crates/eggwork-server/src/operations.rs`. +- The store's `state` column values and the operations SQL literal list are derived from the shared spelling, and a test asserts the derived SQL list still selects exactly the non-terminal states. +- A property test proves the classification is total and disjoint over every `ExecutionState` variant, and that adding a variant to the enum breaks the build or the test. +- The artifact-capture eligibility subset remains exactly `Succeeded` and `Failed`, and remains distinct from terminality. +- The operator-facing state labels are unchanged from their current snake_case spelling. +- A test asserts the canonical wire spelling equals the enum's serde output for every variant. + +### 7.4 General + +- `python3 scripts/check_execution_ownership.py` passes. +- `cargo fmt --all -- --check` passes. +- `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` passes. +- `cargo test --locked --workspace --all-targets` passes. +- `cargo check --workspace` passes. +- `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` passes. +- `git diff --check` passes. +- No new crate dependency edge exists. +- The `architecture/core-domain.md` **States** paragraph and the `architecture/overview.md` divergence #12 row are reconciled with the code in the same pass, including replacement of their stale line-number citations with symbol references. +- No high or medium finding remains without an explicit owner. + +### 7.5 Observation recorded, not owned + +`architecture/overview.md` divergence #20 states that the client's `decode_json` reads the response body with "no size cap". At the reviewed baseline the client bounds accumulated response bodies at the transport builder — `NodeClient::new` and `NodeClient::with_eggress` both set `max_decoded_body_size(MAX_BUFFERED_BODY_BYTES)` on the Eggfetch client builder — so the divergence's text no longer matches the code. This corrective records the observation and leaves #20's disposition to the owner of the architecture record; it neither reopens nor closes that item. + +## 8. Note on citation style + +This repository's architecture deep dives carry a known citation defect: a large fraction of their `file.rs:line` citations no longer point at the symbol they claim. This corrective, and the implementation plan it authorises, cite locations by file path and symbol name only. A line number appears in these documents only where it is genuinely unavoidable, and is marked as being at the reviewed baseline and re-verifiable before editing. diff --git a/plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md b/plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md new file mode 100644 index 0000000..c2272d5 --- /dev/null +++ b/plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md @@ -0,0 +1,144 @@ +# Foundation and Execution Core Post-Closure Corrective — Runner Request Validation Parity + +Status: active corrective; M005 proposed + +Predecessor roadmap: + +- `plans/subsystems/foundation-execution-core-roadmap.md` + +Historical predecessor closures: + +- `plans/closure/foundation-execution-core/002-status.md` — canonical bounded local runner +- `plans/closure/foundation-execution-core/003-status.md` — execution ownership guards and runner API hardening + +Canonical authority remains: + +- `plans/000-long-term-specification.md` +- `plans/001-terminology-and-domain-model.md` +- `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` +- `plans/003-planning-process.md#verification-philosophy` + +Finding source: + +- repository-wide code interrogation pass over the reviewed baseline; the finding is new and is not recorded in the `architecture/overview.md` divergences table. + +## 1. Findings + +This subsystem owns "protocol-neutral domain identities and validation" and the "bounded finite-process runner". The two are supposed to be one contract: the runner's request type is a validated projection of a core `ExecutionSpec`, and the runner is the only place a process is created. The gap below is that the runner re-states the validation rules instead of deferring to their owner, and the two copies do not agree. + +### 1.1 The runner's public construction path bypasses core validation + +`crates/eggwork-runner/src/lib.rs` exposes `RunnerRequest::new(argv, root)` and `RunnerRequest::set_environment(Vec<(String, String)>)` as public API. Neither performs validation. `RunnerRequest::from_spec` does call `spec.validate()` first, so the server's request path is safe. The embedding path is not. + +The runner's own module documentation states the intent directly: + +> *"construct a validated `RunnerRequest` from an `eggwork_core::ExecutionSpec` with `RunnerRequest::from_spec` … Request fields remain private so callers cannot bypass protocol bounds."* + +The fields are private, but the public constructor and the public environment setter are the bypass the sentence claims cannot exist. The invariant the subsystem states — "Request fields remain private so callers cannot bypass protocol bounds" — is true of the field declarations and false of the API surface. + +### 1.2 The runner's validation copy is materially weaker than core's for environment entries + +`crates/eggwork-core/src/lib.rs` routes every environment entry through `EnvironmentEntry::new`, which requires the name to be non-empty, within `MAX_ENV_NAME_BYTES`, composed only of ASCII alphanumerics and underscore, not starting with a digit, and free of NUL bytes. `CommandSpec::validate` additionally rejects duplicate environment names with a typed `ValidationError::InvalidSyntax`. + +`RunnerRequest::validate` in `crates/eggwork-runner/src/lib.rs` checks only that the name is non-empty, within `MAX_ENV_NAME_BYTES`, free of NUL, and free of `=`, and that the value is within `MAX_ENV_VALUE_BYTES` and free of NUL. It therefore accepts names containing `-` or `.`, accepts names starting with a digit, and performs no duplicate-name check at all. + +`RunnerRequest::validate` is called at the top of the run path, immediately before spawn, and its result gates the `Command::env()` call. So the weaker rules are the effective gate for any embedder that uses the public constructor. + +The two copies are not equivalent in the other direction either. The runner additionally rejects an empty argv entry, which core permits. The divergence is therefore asymmetric: the runner is stricter on argv and weaker on the environment. Neither direction is deliberate; both are drift. + +### 1.3 The runner redefines a core domain type it already imports + +`crates/eggwork-runner/src/lib.rs` defines its own `StdinPolicy` enum with a `Null` and a `Bytes` variant, its own `Debug` implementation, and its own `validate` method, duplicating `eggwork_core::StdinPolicy`. The crate already imports core's type — aliased as `CoreStdinPolicy` — and converts between the two by hand. The runner's copy is the one that decides whether stdin bytes are forwarded to the child, and its `validate` is a separate copy of core's `MAX_STDIN_BYTES` rule. + +The correct pattern is already present in the same file: `OverflowPolicy` is imported from core and used directly, with no local copy. `StdinPolicy` should follow it. + +### 1.4 The runner re-states the output-policy bounds instead of delegating + +`RunnerRequest::validate` re-spells the capture-limit and event-chunk bounds that `eggwork_core::OutputPolicy::validate` already owns, in a second copy with its own error message. + +## 2. Corrective milestone + +### M005 — Runner request validation parity with the core domain contract + +Class: invariant + +Status: proposed + +Implementation plan: + +- `plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md` + +Objective: + +Make the runner's request validation a projection of the core domain contract rather than an independent restatement of it, so that a rule exists once, is enforced at the point where the request enters the runner, and cannot be weaker on the embedding path than on the protocol path. + +## 3. Validation contract after M005 + +M005 freezes the following dispositions. + +### 3.1 One owner per rule + +Environment-entry name syntax, environment-entry value bounds, duplicate environment names, argv bounds, and stdin bounds each have exactly one owner: `eggwork-core`. The runner consumes them rather than re-deriving them. + +The runner is permitted to be **stricter** than core where the stricter rule protects the runner's own execution contract — for example the existing rejection of an empty argv entry, which protects the child-process construction. The runner is NOT permitted to be **weaker**. A rule the runner adds must be expressed as an explicit, documented runner-level rule, not as an accidental gap in a re-derived copy. + +### 3.2 The public construction path is guarded + +Every public path that produces a `RunnerRequest` must leave the request in a state that satisfies the core contract, or must fail. `RunnerRequest::from_spec` satisfies this by construction. The public constructor and the public environment setter must either: + +- validate on the way in and return a typed error, or +- be removed, so that `from_spec` is the only construction path. + +The plan must decide which, and the decision must be recorded. Removal is preferred if the repository has no in-tree caller of the public constructor, because it makes the bypass structurally impossible rather than merely checked. If a caller exists, the constructor must validate. + +### 3.3 One `StdinPolicy` + +The runner uses `eggwork_core::StdinPolicy`. The local duplicate and the hand-written conversion are removed. The `OverflowPolicy` pattern is the precedent. + +### 3.4 Error fidelity + +A validation failure raised by the runner must remain attributable to the rule that produced it. The runner's existing `RunnerError::InvalidRequest` carries a message string; M005 must decide whether that is sufficient or whether the typed `eggwork_core::ValidationError` should be preserved, and must not discard the distinction between, for example, a too-long environment name and a duplicate environment name. + +## 4. Durable invariants + +These extend the subsystem's existing invariants 4 ("The runner accepts argv, not an implicitly interpreted shell string") and 5 ("Output and variable-length fields are bounded"): + +1. A validation rule for a runner request has exactly one owner in `eggwork-core`. +2. The runner is never weaker than its owner on any shared rule. +3. A stricter runner-level rule is explicit, documented, and tested. +4. No public runner API can produce a request that violates the core contract. +5. `RunnerRequest` construction validates; the private-field discipline is not sufficient on its own. +6. The runner continues to accept argv and never an implicitly interpreted shell string. +7. The runner's bounds remain the core bounds; no bound is widened by this corrective. +8. The core crate continues to have no internal dependencies and no scheduler or placement semantics. +9. No change to the wire representation of any core type. +10. The historical M002 and M003 closure records remain immutable; this corrective owns the newly discovered validation-parity defect. + +## 5. Compatibility and migration + +No wire protocol changes. No stored format changes. No change to the `ExecutionSpec` or `CommandSpec` wire representation. + +The compatibility question this corrective does raise is the runner's **public Rust API**: if the plan removes `RunnerRequest::new` or `set_environment`, that is a breaking change for any out-of-tree embedder. The plan must state who is affected. Within this repository, the server crate constructs runner requests through `from_spec`; the plan must confirm that before recommending removal. + +The runner crate is published as a workspace crate and is part of the release artifact set, so an API change is a release-visible decision. It must be handled as a version-visible change, not silently. + +## 6. Downstream relationship + +- `eggwork-server` is the in-tree consumer of the runner's request API. It uses the validated `from_spec` path, so it is not affected by the defect, and it must remain unaffected by the fix. +- The `eggwork-sandbox-helper` crate is unaffected: it has no workspace-crate dependencies and does not construct runner requests. +- The `eggwork-client` crate is unaffected. +- This corrective does not interact with Operations M007 (Windows service host), with the control-plane shared-contract corrective, or with the security isolation-truthfulness corrective. It may be executed in parallel with all of them. + +## 7. Exit conditions + +M005 closes only when: + +- every environment-entry rule the runner enforces is enforced by `eggwork-core` and consumed by the runner, with no weaker runner copy remaining; +- the duplicate environment-name rule is enforced on the runner's public construction path; +- the runner's local `StdinPolicy` duplicate and its hand-written conversion are removed; +- no public runner API can produce a request that violates the core contract, and that property is proven by a test rather than by inspection; +- the runner remains at least as strict as core on every shared rule, and each intentional runner-level addition is documented and tested; +- the runner's existing execution, timeout, cancellation, output-limit, and process-tree behaviours are unchanged and still green; +- no new crate dependency edge is introduced; +- the `architecture/runner-execution.md` deep dive is updated so that its description of the runner's validation matches the code, and its stale line-number citations are replaced with symbol references in the same pass; +- no high or medium finding remains without an explicit owner. diff --git a/plans/subsystems/foundation-execution-core-roadmap.md b/plans/subsystems/foundation-execution-core-roadmap.md index 997cb31..d7d0bda 100644 --- a/plans/subsystems/foundation-execution-core-roadmap.md +++ b/plans/subsystems/foundation-execution-core-roadmap.md @@ -1,6 +1,6 @@ # Foundation and Execution Core Roadmap -Status: M001-M004 closed (M004 conditional on a release containing it); C001 post-closure CI corrective closed +Status: M001-M004 closed (M004 conditional on a release containing it); C001 post-closure CI corrective closed; M005 request-validation parity corrective proposed Canonical authority: @@ -151,6 +151,32 @@ Dependencies: - no hard implementation dependency; - Operations M004 remains conditionally closed until a release containing M004 is hosted-qualified. +### M005 — Runner request validation parity corrective + +Class: invariant + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md` + +Objective: + +Make the runner's request validation a projection of the `eggwork-core` domain contract rather than an independent restatement of it. The runner's private validation copy is weaker than core on environment-entry syntax and duplicate names, and the runner's public constructor and public environment setter reach that weaker gate without passing through core validation at all — which contradicts the runner's own documented claim that callers cannot bypass protocol bounds. + +Exit conditions: + +- every request rule the runner enforces has one owner in `eggwork-core`; +- the runner is never weaker than core on a shared rule, and any stricter runner-level rule is explicit, documented, and tested; +- no public runner API can produce a request that violates the core contract, proven by a test; +- the runner's local `StdinPolicy` duplicate and its hand-written conversion are removed; +- no numeric bound and no wire representation changes. + ## 4. CodeGG reuse strategy The implementation agent MUST inspect the current CodeGG `src/managed_process.rs` baseline before M002. diff --git a/plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md b/plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md new file mode 100644 index 0000000..71b7070 --- /dev/null +++ b/plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md @@ -0,0 +1,213 @@ +# Operations and Distribution — Operator Truthfulness Corrective Addendum + +Status: active corrective; M008a and M008b proposed + +Predecessor roadmap: + +- `plans/subsystems/operations-distribution-roadmap.md` + +Historical predecessor closures: + +- `plans/closure/operations-distribution/001-status.md` — the node operations surface +- `plans/closure/operations-distribution/002-status.md` and `plans/closure/operations-distribution/002-resumed-status.md` — Eggup deployment and service integration +- `plans/closure/operations-distribution/002a-status.md` — recovery-required restart suppression and lifecycle composition +- `plans/closure/operations-distribution/003-status.md` — Eggpack producer packaging integration +- `plans/closure/operations-distribution/004-status.md` — operational and release qualification +- `plans/closure/operations-distribution/004a-status.md` — release qualification fixture isolation +- `plans/closure/operations-distribution/004b-status.md` — staged helper publication durability + +Canonical authority remains: + +- `plans/000-long-term-specification.md` +- `plans/001-terminology-and-domain-model.md` +- `plans/002-long-term-roadmap.md` +- `plans/adrs/ADR-0001-fixed-target-scheduler-free-execution.md` +- `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` +- `architecture/operations-cli.md`, `architecture/distribution.md`, `architecture/release-qualification.md` +- `architecture/overview.md` — the divergences table + +Finding source: + +- repository-wide code interrogation pass over the reviewed baseline (`81f34e0`); all six findings below are **new** and are **not** recorded in the `architecture/overview.md` divergences table. + +## 1. Findings + +This subsystem owns the node's operator surface (`eggworkd`) and the release channel that ships the node. Both are *reporting* surfaces: they restate facts that their owners already know — what the node is doing, what is wrong with the configuration, what version the binary is, what the release contains. + +The six findings below share one mechanism. An operator-facing surface keeps a second copy of a fact it could have read from the fact's owner, and the second copy drifts. In five cases the drift is already visible in the tree; in one case the drift is not yet visible but the copy exists and is unwired. + +The mechanism is worth naming precisely because it is not a bug in any one place. It is a missing ownership rule: **every operator-visible fact has exactly one owner, and every surface that reports it reads from that owner.** Today the repository has the first half of that sentence (each fact usually *has* an owner) and not the second (surfaces read from their owners). + +### 1.1 Five live metrics are never reported by the operator surface (OP-1) + +**What the surface should guarantee.** `eggworkd metrics` and `eggworkd status` report the node's counters. A counter the server increments is a fact the node knows; an operator watching the node's workspace-derivation behaviour should be able to see it. + +**What the code actually does.** `crates/eggwork-server/src/operations.rs` declares `const METRIC_NAMES: &[&str]`, a hand-maintained list of metric names, and `fn metrics_snapshot` seeds its counter map from that list. When it then reads rows from the node metrics table it copies a value **only if the name is already in the map** — any metric not in `METRIC_NAMES` is silently discarded. `crates/eggwork-server/src/lib.rs` increments five metrics that are not in that list: `workspace_manifest_registrations`, `workspace_derived_requests`, `workspace_derived_hits`, `workspace_patch_entries`, and `workspace_base_missing`. The workspace-derivation path calls `increment_metrics` with three names at once, so a single logical event can move three counters that the operator surface never shows. + +Nothing detects the drift: there is no test that compares `METRIC_NAMES` against the set of names the server can increment, and no test that asserts a freshly incremented metric appears in a snapshot. + +**Consequence.** An operator watching a node's workspace-derivation behaviour sees counters that never move, with no indication that the counters exist. The node has the facts; the operator surface drops them. + +### 1.2 One `active_executions` field name carries two different meanings (OP-2) + +**What the surface should guarantee.** One name, one fact. A reader who sees `active_executions` in two places must be able to rely on them meaning the same thing. + +**What the code actually does.** Two independent computations produce the same name: + +- `crates/eggwork-server/src/lib.rs` → `fn node_status` computes `active_executions` for the `/v1/status` response as *execution permits currently held* (`max_active` minus available permits). The field lives on `eggwork_core::NodeStatus`, which is a serialized wire type. +- `crates/eggwork-server/src/operations.rs` → the execution listing computes `active_executions` as *the number of database rows in a non-terminal state*. + +Both surface as `active_executions`: one in the API status response, one in the `eggworkd status` and `eggworkd executions list` output (`crates/eggwork-server/src/bin/eggworkd.rs` writes the key `active_executions` into the status payload). + +**Consequence.** The same JSON key reports different facts at different layers. The two disagree whenever the two facts differ — most visibly when an execution has crashed but has not been recovered: the permit has been released, so the API reports it as not active, while the row is still non-terminal and the operator surface still counts it. There is no way for an operator to tell which number is which, and no field name that would let them. + +### 1.3 Configuration errors collapse into one unhelpful operator message (OP-3) + +**What the surface should guarantee.** When a configuration fault is one wrong file mode or one wrong path, the operator is told which rule failed and what to change. + +**What the code actually does.** `crates/eggwork-server/src/operations.rs` returns `OperationsError::Config` at 25 sites, covering every distinct configuration fault: unreadable file, bad permissions, wrong owner, a sandbox helper outside a safe ancestor, a malformed field, a failed parse of the bind address, and more. `crates/eggwork-server/src/bin/eggworkd.rs` then maps the load failure to the single string `configuration is invalid or unreadable`, discarding the error kind entirely. + +The repository's own `AGENTS.md` calls this out: the config loader's strictness (owner-only state directories, private-key mode, nothing group/world writable, a sandbox helper outside world-writable ancestors) "is undocumented anywhere else and produces a single unhelpful `configuration is invalid or unreadable`". + +**Consequence.** An operator who has a single wrong file mode gets no indication of which file or which rule failed. This is a documented, operator-visible pain point with a mechanical fix, and it is the one finding in this addendum whose remedy is called out in the repository's own entry instructions. + +The fix is not free of tension. `architecture/operations-cli.md` records that the binary "never interpolates an error's source text for library errors, no filesystem path, key detail, or child-process output can reach stderr through that path". That is a deliberate redaction property, and adding detail must not become a leak. The remedy therefore has to name the *rule* and the *file or path* that failed — and only the *role* of an item whose path is itself secret-bearing — rather than interpolate arbitrary source text. + +### 1.4 The release harness re-derives facts that already have one owner (OP-4) + +**What the surface should guarantee.** The release harness reports the same version, the same asset inventory, the same install identities, and the same target classification that the shipped artifacts actually have. + +**What the code actually does.** Four separate duplications: + +- **Workspace version, three readers.** `scripts/check_release_tag.py` → `fn workspace_version` uses a regular expression over the whole `Cargo.toml` and takes the *first* `version = ` line in the file, rather than the one under `[workspace.package]`; it works only by accident of the current manifest layout, in which `[workspace.package]` happens to precede every other `version = ` line. `scripts/release_candidate_probe.py` → `fn workspace_version` reads `workspace.package.version` with `tomllib`, and `scripts/validate-daemon-version.py` and `scripts/validate-sandbox-helper.py` already import that reader from it rather than keeping their own. `crates/eggwork-server/tests/release_contract.rs` → `fn the_release_version_is_one_coherent_workspace_identity` reads the same field with the `toml` crate. `scripts/check_release_tag.py` is **not wired into any CI workflow**, so its divergence from the other readers is currently latent rather than observable. +- **The tag guard is never executed by an automated job.** `scripts/check_release_tag.py` is referenced by nothing in the repository except its own docstring. It is not invoked by `.github/workflows/ci.yml`, `.github/workflows/release.yml`, `.github/workflows/operational-qualification.yml`, or `.github/workflows/windows-reproducibility.yml`, and it has no test in `tests/release/`. The script's own docstring gives a deliberate reason for part of this — "the tag-to-version link cannot live in CI: the generated release workflow is producer authority … and CI never knows the future tag. So the check lives here, run by whoever cuts the tag" — and that reason is sound: a tag-dependent assertion cannot run in CI. The defect is therefore narrower than "it is unwired", and it is three things: the script reads the manifest with a **different parser** from the shared reader; `fn lock_versions` parses `Cargo.lock` with regular expressions as well; and a guard whose correctness decides whether a release is tagged is exercised by **no automated job at all** — not even against a fixture — so its correctness is an untested assumption. +- **Two version authorities.** A manifest-derived authority (`scripts/validate-daemon-version.py`, `scripts/validate-sandbox-helper.py`, `scripts/release_candidate_probe.py` — all derive the expected version from the workspace manifest) and a tag-derived authority (`scripts/qualify_release.py` → `fn expected_version` derives the expected version from the release tag and asserts the binary reports it). Both are legitimate; nothing states which one is the release gate and which one is the build assertion. +- **Asset inventory, twice.** `scripts/qualify_release.py` → `fn stage_inventory` derives the expected asset set dynamically from the release manifest, and in the same function asserts the asset count against the hardcoded `QUALIFIED_ASSET_COUNT`. A constant that duplicates a value already computed one line away. +- **Install identities, four times.** `crates/eggwork-server/src/deployment.rs` declares them as constants (`SERVICE_ID`, `MEMBER_DAEMON`, `MEMBER_HELPER`); `release/eggpack/distribution.toml` declares the same identities in its `install` fields and is described in its own header as "the sole checked-in authority for the published target set, release asset names, install identities, and checksum sidecar names"; `scripts/qualify_release.py` declares `SERVICE_ID` and `HELPER_INSTALL_ID` as its own constants; and `crates/eggwork-server/tests/release_contract.rs` pins the Rust side to string literals. Nothing pins the Python side. +- **Target classification, twice.** `crates/eggwork-server/tests/release_contract.rs` holds explicit lists of target triples; `scripts/qualify_release.py` → `fn target_daemon_install` and `fn target_ships_helper` classify a target by testing whether the string ends with `-pc-windows-msvc` or `-unknown-linux-gnu`. + +**Consequence.** Every one of these is a place where a release can be qualified against a fact that the shipped artifact does not have, and where the harness cannot tell the difference. The `QUALIFIED_ASSET_COUNT` case is the sharpest: the function that *derives* the expected set also *asserts a constant* about it, so adding a release target requires editing two things in one function that disagree with each other in spirit — one derived, one remembered. + +### 1.5 The design record and the operator documentation have drifted, and there is no gate (OP-5) + +**What the surface should guarantee.** `architecture/overview.md` is the first document an agent is told to read and every other document cites it. `AGENTS.md` asserts that the quickstart's commands "are executed and verified, not illustrative". A reader following a citation should arrive at the symbol it names. + +**What the code actually does.** + +- **Line-number citations are stale.** `architecture/*.md` carries 718 line-number citations of the form `file.rs:NNN`. Re-measuring against the tree with the nearest backticked identifier as the anchor, 85% of the resolvable citations no longer resolve at the exact cited line, 83% are stale within a ±3-line tolerance, and 72% remain stale even allowing ±20 lines of drift. (The interrogation pass reported roughly 92%; the exact figure depends on the tolerance chosen, and the conclusion does not depend on it.) Spot-verified examples: `architecture/deployment-lifecycle.md` cites `verify_trusted_helper` as living in `crates/eggwork-server/src/lib.rs`, while the function is defined in `crates/eggwork-runner/src/lib.rs` — the wrong file entirely; `architecture/runner-execution.md` cites `LANDLOCK_WORKSPACE_RW_CAPABILITY` and `probe_landlock_ruleset` at line numbers that sit roughly 140 lines away from the definitions they name in `crates/eggwork-runner/src/lib.rs`. The citation form itself is the defect: a line number is a property of the text, not of the symbol, and it is invalidated by every unrelated edit above it. +- **The component size table is stale.** Every crate size figure in the `architecture/overview.md` component table understates the tree. Counting non-test Rust sources at the reviewed baseline: core 2,294 lines against a stated 1,671; runner 2,900 against 2,336; client 1,158 against 880; server 16,980 against 14,104; sandbox-helper 446 against 401. A table of numbers that are all wrong is worse than no table, because it looks authoritative. +- **Divergence #20 is stale in the dangerous direction.** The `architecture/overview.md` divergences table states that the client decodes JSON bodies "with no size cap". That is no longer true: `crates/eggwork-client/src/lib.rs` applies `max_decoded_body_size(MAX_BUFFERED_BODY_BYTES)` at the transport layer and a stricter `MAX_TELEMETRY_BODY_BYTES` cap on the telemetry route. The table is read as the list of *open* questions, so a reader would go chasing an issue that is already fixed. This is the most dangerous form of documentation drift, because it actively misdirects. +- **A second divergence of the same kind exists between documents.** `architecture/operations-cli.md` describes `doctor` as "Seven checks, in order" and does not list `host-telemetry`; `crates/eggwork-server/src/operations.rs` → `fn doctor` emits eight checks, including `host-telemetry`, and `docs/operations.md` already documents eight. The design record lags the operator documentation and the code. +- **`docs/quickstart.md` is not machine-verified.** No CI job, test, or script executes or even references it; the only mention outside `docs/` is a source comment. `AGENTS.md`'s claim that quickstart commands "are executed and verified, not illustrative" is true of their authors' intent and unbacked by any gate. +- **The mechanism.** The repository's prose volume is roughly 85% of its code volume (`architecture/` about 8,500 lines against `crates/` about 28,400; `plans/` about 15,300; `docs/` about 870; `scripts/` about 2,550), and documentation files are touched about 2.7 times as often as Rust files in recent history. Prose moves faster than code and nothing reconciles the two. + +**Consequence.** The design record's authority is asserted, not earned. An agent that follows a citation arrives at the wrong symbol; an agent that reads the divergences table as open questions investigates a fixed bug; an operator that follows the quickstart may find a command that no longer works. + +**Class note.** Part of this finding is genuinely **polish** — a stale size table and a stale `doctor` check count are documentation defects, not behavioural ones. It must not be represented as a capability. The part that is not polish is the *absence of a gate*: a document that asserts "executed and verified" while nothing verifies it is a truthfulness defect of the same family as OP-1 and OP-3. + +### 1.6 CI does not execute the code it type-checks (OP-6) + +**What the surface should guarantee.** A green CI run is evidence that the code ran. + +**What the code actually does.** + +- **The feature-gated qualification test never runs.** `.github/workflows/ci.yml` runs `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` with `--all-features`, but runs `cargo test --locked --workspace --all-targets` **without** it. `crates/eggwork-server/tests/installed_qualification.rs` is gated by `#![cfg(feature = "qualification")]`, so clippy type-checks it and the test step never executes it. It is additionally marked `#[ignore]`, and it runs in the operational-qualification workflow instead. +- **One test is green while proving nothing.** `crates/eggwork-runner/tests/capability_probe.rs` → `fn built_helper` locates the sandbox helper binary via runtime environment variables (`CARGO_TARGET_DIR`, `OUT_DIR`); when it cannot, the test returns early and **passes with zero assertions**. The file's own comment claims "CI builds it before running this suite, so this skip is a local-only convenience" — but `CARGO_TARGET_DIR` is not set by the repository's `.cargo/config.toml` and is not exported to integration test binaries, and `OUT_DIR` is a compile-time variable for build scripts, not a runtime environment variable. The skip is therefore the *normal* path in CI, not an exceptional one. The repository already contains the deterministic pattern this test should use: `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` → `fn built_helper` resolves the helper through the compile-time `CARGO_BIN_EXE_` variable, and `crates/eggwork-server/src/lib.rs` → `fn locate_helper_binary` walks the current executable's sibling and grandparent before consulting `CARGO_TARGET_DIR`. + +**Consequence.** A green CI run is weaker evidence than it appears. One suite is type-checked but never executed, and one test in an executed suite reports success without asserting anything. + +## 2. Corrective milestones + +### M008a — Operator surface truthfulness + +Class: capability + +Status: proposed + +Implementation plan: + +- `plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md` + +Closure record: + +- `plans/closure/operations-distribution/008a-status.md` + +Covers OP-1, OP-2, OP-3. Operator-visible behaviour changes: live metrics become visible, the two `active_executions` facts become separately named, and configuration failures become actionable. + +### M008b — Release harness and documentation single-sourcing + +Class: infrastructure (release harness and CI) / polish (documentation drift and citation hygiene) + +Status: proposed + +Implementation plan: + +- `plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md` + +Closure record: + +- `plans/closure/operations-distribution/008b-status.md` + +Covers OP-4, OP-5, OP-6. The harness and CI portion is internal machinery that supports the release capability and is classified as infrastructure; the documentation-drift portion is explicitly polish and must not be represented as capability. The plan changes no released artifact format and no wire protocol. + +## 3. The ownership rule these correctives establish + +**One owner per fact. Every surface reads from the owner.** + +Concretely, after M008a and M008b: + +| Fact | Owner | Surfaces that read it | +|---|---|---| +| Metric names and their values | the increment sites in `crates/eggwork-server/src/lib.rs` | `eggworkd metrics`, `eggworkd status` | +| Execution permits held | the permit accounting in `crates/eggwork-server/src/lib.rs` | `/v1/status` (`NodeStatus`) | +| Non-terminal execution rows | the execution store | `eggworkd status`, `eggworkd executions list` | +| Configuration fault kind and rule | the config loader in `crates/eggwork-server/src/operations.rs` | `eggworkd` config verbs, `doctor`, daemon startup | +| Workspace version | `Cargo.toml` `[workspace.package].version` | release scripts, release contract test | +| Published asset inventory | `release/eggpack/distribution.toml` | qualification harness, release contract test | +| Release install identities | `release/eggpack/distribution.toml` and `crates/eggwork-server/src/deployment.rs` | deployment, qualification harness, release contract test | +| Release target classification | `release/eggpack/distribution.toml` | qualification harness, release contract test | +| Citation targets in the design record | the symbols in the tree | `architecture/*.md`, `docs/*.md` | + +A second copy of a fact is not permitted. Where a second copy is unavoidable across a language boundary (Rust and Python), the copy must be *derived* from the owner at run time or checked by a gate that fails when the two disagree — never remembered independently. + +## 4. Durable invariants + +- **I-1.** Every metric the server can increment is reported by the operator surface. A metric that is incremented but not reported is a defect, and a test must fail when it occurs. +- **I-2.** No two operator-visible fields in the same system carry the same name and different meanings. Where a name is protocol-visible, the protocol wins and the other fact takes a different name. +- **I-3.** A configuration failure names the rule that was violated, the file or path that failed (the item's role, where the path is secret-bearing), and the corrective action — and never discloses a private-key path, a certificate fingerprint, or arbitrary underlying error text. +- **I-4.** The release harness derives every fact it asserts from its owner; it holds no independently remembered constants for version, inventory, identity, or target classification. +- **I-5.** The design record cites symbols, not line numbers. A citation that cannot be checked mechanically is not a citation. +- **I-6.** A test that asserts nothing is not evidence. A suite that is type-checked but not executed is not evidence. Both states must be visible to a reader of the CI configuration. +- **I-7.** These correctives change no released artifact format and no wire protocol, and they do not weaken any authentication, lease, generation, fencing, or digest bound. They do not move the fixed-target, scheduler-free boundary in either direction. + +## 5. Compatibility and migration + +- **OP-2 is the only finding with a protocol-visible consequence.** The `active_executions` field of `eggwork_core::NodeStatus` is a serialized wire type consumed by `eggwork-client` → `NodeClient::status`. Renaming a field of a wire type that deployed clients already deserialize breaks them, because a missing field is a deserialization error, not a default. The M008a plan therefore renames the *operator-side* field and leaves the wire field alone, and states the consequence explicitly. +- The operator-side field rename is a change to `eggworkd`'s JSON output. `eggworkd status` and `eggworkd executions list` output is operator-facing and is not a published protocol, but operators and any scripting around it may parse it. The plan must record the new names and keep the old names as accepted aliases for one release, or state why an alias is not offered. +- **OP-1 is additive.** Metrics that were invisible become visible. No counter disappears and no value changes meaning. +- **OP-3 changes only failure text.** A successful configuration load is unaffected. The redaction property in `architecture/operations-cli.md` is preserved, and a test proves that a failure message contains neither a private-key path nor a certificate fingerprint. +- **OP-4 changes no released artifact.** The asset names, install identities, target set, and binary versions are unchanged; only the harness's route to those facts changes. If the harness's derived expectations change at all, that is a signal that a *fact* changed, not that the harness was wrong to remember it — and it must be investigated as such. +- **OP-5 changes no behaviour.** The design record and operator documentation are corrected to match the tree. +- **OP-6 changes no released behaviour.** The CI gap is closed by executing code that already exists, or by recording in the place a reader would look why it cannot be executed. + +## 6. Downstream relationships + +- **M007 (Windows service host) is `ready` and is not disturbed.** M007 owns the foreground `run` path's shutdown asymmetry — the foreground path calls shutdown without waiting for convergence, and M007 commits to a shared shutdown-and-wait convergence contract. **That finding is already owned by M007 and is deliberately not duplicated in this addendum.** Nothing in M008a or M008b touches the service-host lifecycle, the shutdown contract, or the Windows service path. +- **M004, M004a, M004b are closed.** Their closure records stand and are not rewritten. OP-4's findings concern the *harness's* duplication, not the fixture isolation or staged-helper durability that M004a and M004b closed. +- **M005 and M006 are deferred** in `plans/subsystems/operations-distribution-roadmap.md`. Nothing here depends on them and nothing here pre-empts them. +- **M008a and M008b are independent of each other** and of M007. They may be executed in parallel with the other corrective addenda in this planning batch. +- **The registry is owned by another writer.** `plans/registry.md` is not modified by these documents; registering M008a and M008b as current authority is the registry owner's action, per `plans/README.md`. + +## 7. Exit conditions + +The operations and distribution subsystem may be treated as truthfully reported when: + +1. every metric the server can increment is visible to `eggworkd metrics`, with a test that fails when a producer increments an unreported metric; +2. the two `active_executions` facts are separately named, separately documented, and separately tested, with the wire field's disposition stated; +3. a configuration fault produces a message naming the rule and the offending file or path — the item's role where the path is secret-bearing — and no configuration fault message discloses a private-key path or a certificate fingerprint; +4. the release harness derives its version, inventory, identities, and target classification from their owners, holds no independently remembered copies, and `scripts/check_release_tag.py` uses the shared reader and is exercised by an automated job; +5. the design record cites symbols rather than line numbers, a mechanical check enforces it, the component size table is corrected or replaced by something that cannot silently go stale, and divergence #20 is corrected or closed; +6. the quickstart is machine-verified, or the waiver is recorded where a reader would look for it; +7. the feature-gated qualification test executes in CI or the reason it cannot is recorded in the same place; and the capability probe either asserts something or fails loudly when its precondition is absent. + +Until then, the operations and distribution subsystem carries an active corrective, and its closure records must not be read as evidence that these properties hold. diff --git a/plans/subsystems/operations-distribution-roadmap.md b/plans/subsystems/operations-distribution-roadmap.md index 0f9b4ce..db92057 100644 --- a/plans/subsystems/operations-distribution-roadmap.md +++ b/plans/subsystems/operations-distribution-roadmap.md @@ -1,6 +1,6 @@ # Operations and Distribution Roadmap -Status: active roadmap; M001-M003, M002a, M004a and M004b closed, M004 conditionally closed; M007 ready +Status: active roadmap; M001-M003, M002a, M004a and M004b closed, M004 conditionally closed; M007 ready; M008a and M008b operator-truthfulness correctives proposed Canonical authority: @@ -336,6 +336,58 @@ A routine service STOP must not create a new persistent drain marker; persistent Verification is deliberately split: state/contract tests plus source-built hosted SCM lifecycle evidence close the implementation side; immutable installed-release evidence remains Operations M004 authority. Foundation M004 is already conditionally closed and is not an implementation dependency. No additional M007 prerequisite plan is required. +### M008a — Operator surface truthfulness corrective + +Class: capability + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md` + +Objective: + +Make the operator surface report what the node actually does. Five live metrics are incremented by the server and never reach `eggworkd status`/`eggworkd metrics` because the reported vocabulary is a hand-maintained list; one `active_executions` field name carries two different meanings across the API and the CLI; and every configuration fault — wrong owner, wrong mode, an unsafe helper location, a malformed field — collapses into the single unhelpful message `configuration is invalid or unreadable`. + +Exit conditions: + +- a metric the server increments cannot be silently dropped by the operator surface, and a test proves it; +- the two `active_executions` facts are separately named and separately documented, with the API-visible field chosen so deployed clients are not broken; +- a configuration failure names the path and the rule that failed and what the operator should do; +- redaction of private-key paths and certificate fingerprints is preserved in both success and failure output. + +### M008b — Release harness and documentation single-sourcing corrective + +Class: infrastructure (release harness and CI) / polish (documentation drift and citation hygiene) + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md` + +Objective: + +Give the release harness and the design record one owner per fact. The harness re-derives the workspace version, the release asset inventory, the install identities, and the release-target classification that already have owners, and its tag guard is not wired into CI. Separately, the design record has drifted: roughly 92% of its line-number citations no longer point at the symbol they claim, every crate size figure is stale, and one divergences-table entry describes an already-fixed issue as open. CI also type-checks feature-gated code it never executes, and one runner test passes with zero assertions. + +Exit conditions: + +- the harness derives the version, inventory, identities, and target classification from their owners, and the tag guard runs in CI; +- the design record cites symbols rather than line numbers, and a durable guard prevents the drift from returning; +- the divergences table is re-verified entry by entry; +- `docs/quickstart.md` is machine-verified, or the waiver is recorded where a reader would look; +- feature-gated code either executes in CI or the reason it does not is recorded in the same place; +- no released artifact format and no wire protocol changes, and the generated release workflow is never hand-edited. + ### M005 — Reverse-connect relay Class: capability diff --git a/plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md b/plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md new file mode 100644 index 0000000..3e29882 --- /dev/null +++ b/plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md @@ -0,0 +1,226 @@ +# Security, Isolation, and Resource Enforcement Post-Closure Corrective — Isolation and Authorization Truthfulness + +Status: active corrective; M005a proposed, M005b proposed, M005c blocked + +Predecessor roadmap: + +- `plans/subsystems/security-isolation-resource-roadmap.md` + +Historical predecessor closures: + +- `plans/closure/security-isolation-resource/002-status.md` — Landlock runtime and `/dev/null` handling +- `plans/closure/security-isolation-resource/003-status.md` — enforced resource controls +- `plans/closure/security-isolation-resource/004-status.md` — security closure and cross-platform adversarial qualification +- `plans/closure/security-isolation-resource-remote-admission-corrective/001-status.md` — the remote-admission and capability-truthfulness corrective (C001) +Canonical authority remains: + +- `plans/000-long-term-specification.md` +- `plans/001-terminology-and-domain-model.md` +- `plans/adrs/ADR-0005-runner-service-separation-and-local-admission.md` +- `plans/003-planning-process.md#verification-philosophy` + +Finding source: + +- repository-wide code interrogation pass over the reviewed baseline. +- **SI-1 and SI-2 are new.** Neither is recorded in the `architecture/overview.md` divergences table. +- **SI-3 is not new.** The inert resource-scoped authorization hook is already recorded as divergence #4 in the `architecture/overview.md` divergences table and as an open remaining boundary in `plans/security/threat-model.md`. M005c is a *decision about an already-recorded gap*, not a new defect report, and this addendum must not present it as one. + +## 1. Findings + +This subsystem owns the "isolation claims are earned" invariant, the single owner of OS process lifecycle (`eggwork-runner`), and the standalone Landlock helper beneath it. The two findings below are about **truthfulness of what the node reports**: a caller must be able to tell, from the protocol it consumes, whether the isolation it asked for was actually applied, and whether the boundary it was told exists is the boundary that is enforced. + +### 1.1 SI-1 — A degraded isolation is recorded but never streamed + +`IsolationRequirement::BestEffort` legitimately permits degradation, and the degradation *is* recorded. `crates/eggwork-core/src/lib.rs` defines `SandboxResult::NotApplied { reason }` and `ResourceDimensionResult::NotApplied { reason }`. `crates/eggwork-runner/src/lib.rs` produces both: `TrustedLandlockSetup::prepare` returns `SandboxOutcome::NotApplied { reason }` for an unsupported sandbox profile and for an untrusted helper, `ResourceSetupOutcome::NotApplied { reason }` when the cgroup probe fails or the helper cannot be trusted, and `RunnerResult::execution_result` converts them into the core types. The server carries them into the terminal snapshot. + +But the **event stream carries nothing**. `crates/eggwork-core/src/lib.rs` defines `ExecutionEventKind::Diagnostic(String)` as the only non-output, non-state event kind. At the reviewed baseline it is constructed in exactly three places across the workspace, and all three are test code: + +- `crates/eggwork-server/src/lib.rs` — inside the `#[cfg(test)] mod tests` block (two constructions). +- `crates/eggwork-server/src/store.rs` — inside that file's `#[cfg(test)] mod tests` block (one construction, a payload-length probe). + +There is **no production diagnostic event in the repository**. + +The runner degrades in several distinct ways, and the most consequential one is a helper handshake failure. In `crates/eggwork-runner/src/lib.rs`, `LocalProcessRunner::run` performs the trusted Landlock setup, builds a `SandboxChannel`, spawns the helper as the tree leader, and waits on the helper's handshake. When the handshake reports that the helper could not enforce the requested profile (`Ok(None)`), or fails before the target (`Err(SandboxWaitError::BeforeTarget(..))`), the runner — for a best-effort request only — kills the helper tree, rewrites `setup.sandbox` and `setup.resources` to `NotApplied`, and **re-spawns the target directly, bypassing the helper entirely**, through `direct_command`. The target then runs with no Landlock ruleset at all. + +The consequence is a truthfulness gap, not a cosmetic one. A caller that streams events sees `State(Running)`, the target's stdout and stderr, and `State(Succeeded)`. Nothing in that stream says the execution was not confined. The degradation is discoverable only by polling the terminal snapshot, where `ExecutionResult.sandbox` reads `NotApplied { reason }` — a field a streaming client has no reason to fetch. For a protocol whose purpose is to deliver machine-readable lifecycle facts, "the guarantee you asked for was not applied" is a lifecycle fact, and it is missing from the lifecycle channel. + +Two further facts sharpen this: + +- `crates/eggwork-server/src/lib.rs`'s `publish` returns early when the recorded base state is already terminal, and `store::ExecutionStore::commit_event` refuses to append to a terminal execution. A diagnostic published *after* the terminal event would be **silently dropped**, not merely late. The ordering constraint is therefore load-bearing, not stylistic. +- The `Required` path is a different case and is already truthful in the stream. A required request that cannot be satisfied makes the runner return an error before the target starts, and the server's `failed_result` synthesizes `SandboxResult::Failed { reason: "required sandbox setup failed" }` into a terminal `State(Failed)` event. The gap is specifically the *successful* execution whose isolation was degraded: there the terminal event says "succeeded" and nothing else in the stream qualifies it. + +### 1.2 SI-2 — The sandbox environment deny-list is maintained twice, with different semantics + +`crates/eggwork-runner/src/lib.rs` defines `fn denied_environment_key(key: &str) -> bool`. `crates/eggwork-sandbox-helper/src/main.rs` defines its own `fn denied_environment_key(key: &str) -> bool` inside `mod linux`. At the reviewed baseline the two lists are **element-for-element identical**: the same 21 entries in the same order — `LD_`, `DYLD_`, `PATH`, `IFS`, `SHELLOPTS`, `CDPATH`, `BASH_ENV`, `ENV`, `PYTHONPATH`, `PYTHONHOME`, `NODE_OPTIONS`, `RUBYOPT`, `PERL5OPT`, `GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_CONFIG`, `GIT_CONFIG_`, `AWS_`, `AZURE_`, `GOOGLE_`, `SSH_AUTH_SOCK` — matched by the same rule, `upper == denied || upper.starts_with(denied)` on an ASCII-uppercased key. Two observations about the rule itself: `GIT_CONFIG_` is redundant because the `GIT_CONFIG` prefix already covers `GIT_CONFIG_GLOBAL` and friends, and because the match is prefix-based, `PATH` denies *any* key beginning with `PATH`, not only `PATH` itself. + +The **semantics differ**, and they differ in the dangerous direction: + +- The runner **silently drops** denied keys. `direct_command` calls `command.env_clear()`, installs `baseline_child_environment`, and then installs each caller-supplied environment entry for which `denied_environment_key` is false. `SandboxChannel::new` does the same for the helper's launch specification. A denied key is simply never passed to the child. +- The helper **fails the whole launch**. In `read_spec`, `crates/eggwork-sandbox-helper/src/main.rs` rejects a specification whose environment contains a denied key (`denied_environment_key(key) && key != "PATH"`) or whose `PATH` is not exactly `/usr/bin:/bin` (`key == "PATH" && value != "/usr/bin:/bin"`), returning the distinct status code 12. The runner reads that status as a setup failure before the target starts. + +The helper also enforces a rule with **no runner counterpart**: `PATH` must equal exactly `/usr/bin:/bin`. The runner satisfies that only incidentally, through the platform branch of `baseline_child_environment`, which sets `PATH` to `/usr/bin:/bin` on non-Windows and to `%SystemRoot%\System32;%SystemRoot%` on Windows. The helper is a Linux-only binary (`#[cfg(target_os = "linux")] mod linux`), so the Windows shape never reaches it — but the rule is a property of the *helper's* environment contract, and it is expressed in only one of the two places that own the environment. + +Because the helper's copy is the enforcement point for every Landlock run, the two failure directions are asymmetric: + +- An entry added **only on the runner side** is silently unenforced by the helper. The runner drops the key from the spec it builds; the helper never sees it and never refuses. The security control does not exist. +- An entry added **only on the helper side** turns a valid launch into an opaque exit-12 failure. The runner does not drop the key, so the key reaches the helper, and the helper refuses the whole launch with a status code whose meaning is not visible at the call site. + +The duplication is **architecturally forced**, not accidental carelessness. `crates/eggwork-sandbox-helper/Cargo.toml` has **no workspace-crate dependency** on any production crate — only `serde`, `serde_json`, and the target-scoped `landlock` and `nix` — and `architecture/sandbox-helper.md` states the rule: the helper is a standalone binary whose shipped dependency surface is deliberately kept to serde/serde_json plus one sandbox crate, because it is the trusted artifact that is staged, verified, and run with its own trust rules. `AGENTS.md`'s hard invariant 3 ("core/helper → nothing") is the same rule in one line. The fix therefore **cannot** be "share a crate": the correct shape is a shared *artifact* — a generated list, or a checked-in source of truth that both sides read — plus a test that pins the two sides together so a one-sided edit fails the build. + +Two related duplications sit in the same neighbourhood and are in scope for the same milestone because they are the same class of defect: + +- The **baseline child environment is written twice inside the runner**. `baseline_child_environment` produces the direct child's environment; `SandboxChannel::new` writes a second, separate literal list for the helper's launch specification. The two lists carry the same eight keys and the same values on Linux, but they are independent literals that nothing keeps in step. +- The **protocol limit constants are duplicated from `eggwork-core` into the helper**. `crates/eggwork-sandbox-helper/src/main.rs` re-declares `MAX_ARG_COUNT`, `MAX_ARG_BYTES`, `MAX_ENV_COUNT`, `MAX_ENV_NAME_BYTES`, and `MAX_ENV_VALUE_BYTES` with the same values that `crates/eggwork-core/src/lib.rs` exports and that `crates/eggwork-runner/src/lib.rs` imports. (`MAX_SPEC_BYTES` is helper-only and has no core counterpart.) + +The repository already holds the pattern that answers this. `crates/eggwork-runner/tests/windows_process_tree.rs` keeps a hand-maintained `BASELINE_KEYS` list beside the runner's own `baseline_child_environment`, with the comment *"Kept in sync with `baseline_child_environment` in the crate; a mismatch is a contract change, not a test fix."* That is a comment, not a gate. M005b generalizes the pattern from a comment to a test that fails. + +### 1.3 SI-3 — Resource-scoped authorization is inert on every production path + +This finding is **already known**. `architecture/overview.md` records it as divergence #4: *"`GrantAuthorizer` implements only `Authorizer::authorize`, **not** the resource-aware `authorize_request` hook. Resource-scoped authorization is therefore inert on the real deployment path; ownership is enforced only in the store, by `principal_id` comparison."* `plans/security/threat-model.md` states the same boundary in the "Authenticated unauthorized principal" row: *"Broad BlobRead capability permits any known digest unless resource-scoped policy is configured."* + +The machinery is fully built and publicly exported: + +- `crates/eggwork-server/src/lib.rs` defines `pub enum ResourceId { Execution, Blob, Workspace, Artifact }` — a typed resource identifier. +- The same file defines `pub struct OperationRequest { operation, resource: Option }`. +- The same file defines `fn resource_for_path(operation, path) -> Option`, which maps a request path segment to a typed resource for `Observe`, `Cancel`, `Renew`, `Events`, `BlobRead`, `BlobWrite`, and `ArtifactRead`. +- The `Authorizer` trait in the same file declares `fn authorize_request(&self, principal, request: &OperationRequest) -> bool`, whose default implementation delegates to `fn authorize(&self, principal, operation) -> bool`. +- `crates/eggwork-server/src/operations.rs` defines `pub struct GrantAuthorizer(HashMap>)` and implements **only** `authorize`. The trait's default `authorize_request` therefore applies, and the typed `ResourceId` is **never consulted** on the production path. +- `fn authorize_resource(state, principal, operation, resource)` in `crates/eggwork-server/src/lib.rs` is the resource-scoped call helper. It is called at six handler sites: the blob-find-missing handler (`Operation::BlobRead`, `ResourceId::Blob`), the blob-prepare handler (`Operation::BlobWrite`, `ResourceId::Blob`), the workspace-create handler (`Operation::WorkspaceCreate`, `ResourceId::Workspace`), the workspace-derive handler (`Operation::WorkspaceCreate`, `ResourceId::Workspace`), and the execute handler (twice — `Operation::Execute` with `ResourceId::Execution`, and `Operation::Execute` with `ResourceId::Workspace` when the request names one). The `dispatch` function additionally calls `authorize_request` with a `resource_for_path`-derived resource for every routed request. + +Every one of those call sites resolves to the same operation-level decision. The typed resource is constructed, passed, and discarded. + +The practical effect is bounded but real, and it is exactly the boundary the threat model already names: a principal holding `BlobRead` may read **any** digest the node knows, not only the ones it was granted. The store's `principal_id` fence does not help for blobs, because blob storage is content-addressed and shared; the fence that does help — `ExecutionStore::load_snapshot_for_principal`, the artifact store's `principal_id`-scoped `load` and `list`, and the workspace store's `(principal_id, base_manifest_digest)` scoping — is a *store* fence, not an *authorizer* fence, and it is applied after the resource has already been resolved and authorized at the operation level. + +The only exerciser of the resource-scoped path is a unit test in `crates/eggwork-server/src/lib.rs`'s test module, which asserts that `resource_for_path` maps a path to a `ResourceId`. No production authorization decision depends on the answer. + +**This is a decision, not a bug fix.** Two dispositions are coherent, and they are not equivalent in cost or in what they promise: + +- **Implement resource-scoped grants.** Make `GrantAuthorizer` implement `authorize_request` against a grant shape that names resources, with an owner fence for the resource kinds that have one. +- **Remove the hook and its plumbing.** Delete `ResourceId`, `OperationRequest.resource`, `resource_for_path`, the six resource-scoped call sites, and the unit test, so the mechanism stops looking available. This is a public-API removal: `ResourceId`, `OperationRequest`, and the `Authorizer` trait are `pub` in `eggwork-server`, which is a published workspace crate. + +A third disposition — deferring while advertising a "not available" marker — is weaker than it looks, because the mechanism would still be present and still inert. + +Per `plans/003-planning-process.md` §8, the choice between these is a durable architecture decision and requires an ADR. M005c is therefore written now, to preserve design intent, and is **blocked** on that ADR: `plans/adrs/ADR-0007-resource-scoped-authorization.md` (**proposed, not accepted**). + +## 2. Corrective milestones + +### M005a — Degraded isolation observability in the event stream + +Class: invariant + +Status: proposed + +Implementation plan: + +- `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md` + +Objective: + +Make a degraded isolation or resource enforcement **visible in the event stream**, not only in the terminal snapshot, and make the terminal state non-misleading for a caller that never polls a snapshot. The diagnostic must reach the caller before the target's output and before the terminal event. The `Required` path must not change: a required request still fails closed before the target starts. + +### M005b — Sandbox-helper environment parity + +Class: invariant + +Status: proposed + +Implementation plan: + +- `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md` + +Objective: + +Give the environment deny-list, the `PATH` rule, and the child-environment baseline exactly one owner that both the runner and the standalone helper consume, without giving the helper a workspace-crate dependency, and make a one-sided edit fail the build instead of silently changing enforcement. + +### M005c — Resource-scoped authorization disposition + +Class: invariant + +Status: blocked + +Concrete blocker: + +- `plans/adrs/ADR-0007-resource-scoped-authorization.md` — **proposed, not yet accepted**. The ADR must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. Until that ADR is accepted, M005c cannot be handed off as ready, per `plans/003-planning-process.md` §4. + +Implementation plan: + +- `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` + +Objective: + +Resolve the already-recorded divergence #4 to a decided disposition, so that the node stops presenting a mechanism as available when it is inert — whether by implementing it or by removing it. + +## 3. Validation contract after M005 + +M005a, M005b, and M005c freeze the following dispositions. + +### 3.1 A degradation is a lifecycle fact + +A best-effort isolation or resource request that could not be enforced must produce an observable event in the execution's event stream, carrying the class of degradation and a bounded reason. The event must precede the terminal event, and it must precede any output the target produces. A terminal state that reports success must never be the only signal that a requested guarantee was not applied. + +### 3.2 The `Required` path is unchanged + +A `Required` isolation or resource request that cannot be satisfied must continue to fail closed **before the target process starts**, and must continue to produce a terminal failure. A diagnostic is not a substitute for a refusal, and this corrective must not convert a required refusal into a best-effort degradation. This is the `AGENTS.md` hard invariant "Isolation claims are earned" and the repository's fail-closed rule, and it is the authority both M005a and M005b must preserve. + +### 3.3 One owner per environment rule + +The denied-key list, the `PATH` rule, and the child-environment baseline each have exactly one owner. The helper consumes the owner's output without acquiring a workspace-crate dependency. Where the runner and the helper legitimately need different *behaviour* on the same rule, that difference is stated as a deliberate contract, not left as an accident of two implementations. + +### 3.4 A one-sided edit fails the build + +The relationship between the runner's environment rules and the helper's environment rules is pinned by a test that compares them element-wise. A change to one side without the other is a build failure, and the failure message states that a mismatch is a contract change rather than a test to be adjusted. + +### 3.5 The node does not advertise what it does not enforce + +A mechanism that is present but inert must not be represented as available. This holds in both branches of the M005c decision: if resource-scoped grants are implemented, the hook decides; if the hook is removed, the public API no longer implies that resource-scoped authorization exists. In either case the `architecture/overview.md` divergences table must reflect the decided disposition rather than an open divergence. + +## 4. Durable invariants + +These extend the subsystem's existing invariants, including "Isolation claims are earned" and the fail-closed rule from `AGENTS.md`: + +1. A degradation of isolation or resource enforcement is observable in the event stream, not only in the terminal snapshot. +2. A degraded best-effort execution's terminal state is never the only signal of the degradation. +3. The diagnostic precedes the terminal event and precedes any target output. +4. A `Required` isolation or resource request fails closed before the target process starts, and this corrective does not change that. +5. The sandbox environment deny-list, the `PATH` rule, and the child-environment baseline each have exactly one owner. +6. The sandbox helper gains no workspace-crate dependency. +7. The runner's and the helper's environment rules are pinned to each other by a test, so a one-sided edit fails the build. +8. A rule enforced by the helper is not silently unenforced by the runner, and a rule enforced by the runner alone cannot turn a valid launch into an opaque refusal. +9. The node does not present a mechanism as available when it is inert. +10. The historical M001–M004 and C001 closure records remain immutable; this corrective owns the newly discovered truthfulness defects and the escalation of the already-recorded divergence #4. +11. No change to the wire representation of `ExecutionEventKind`, `ExecutionResult`, `SandboxResult`, or `ResourceResult` under M005a or M005b. +12. The one-way crate dependency rule (core/helper → nothing; client → core; server → core + runner) is unchanged. + +## 5. Compatibility and migration + +**M005a** changes what a caller observes, not what it may do. A caller that today ignores `ExecutionEventKind::Diagnostic` keeps working. A caller that asserts "the only events are State/Stdout/Stderr" must be updated — that is the intended correction, and it is a client-side behaviour change that the plan must call out. The runner's public `OutputChunk` type may need a diagnostic variant to deliver the ordering guarantee; that is a release-visible change to a published crate and must be handled as a version-visible change, not a silent one. + +**M005b** changes the runner's and the helper's environment contract. The deny-list's *content* need not change, but its single ownership does, and the `PATH` rule must become an explicitly stated contract on both sides (or be removed in favour of an explicit statement of the actual baseline). A caller whose environment currently includes a key that only one side denies will observe a different outcome after M005b; the closure record must enumerate the before/after disposition of every entry. + +**M005c** is the compatibility-sensitive milestone. Implementing resource-scoped grants is additive to the configuration surface but changes authorization decisions. Removing the hook removes public items from `eggwork-server` (`ResourceId`, `OperationRequest`, and the `authorize_request` method on the public `Authorizer` trait), which is a breaking change to a published crate and must be reflected in the release version and notes. The ADR decides which; the plan must not pre-empt it. + +## 6. Downstream relationship + +- `eggwork-core` owns the event kinds and the result types. M005a and M005b consume them; neither changes their wire representation. +- `eggwork-client` is affected by M005a only as a consumer that may now receive a diagnostic event. `ExecutionStream::into_events` in `crates/eggwork-client/src/lib.rs` already yields any `ExecutionEvent`, including a diagnostic, so no client change is required to *receive* one; a client that wants a typed convenience accessor may add one. +- `eggwork-sandbox-helper` is the enforcement point for SI-2. Its standalone-binary rule is the binding constraint on M005b's mechanism, not an obstacle to be worked around. +- `eggwork-server` owns the event publication path (SI-1) and the authorization machinery (SI-3). +- The control-plane shared-contract corrective (`API_SCHEMA_VERSION` and the shared wire contract) is a sibling in the same repository-interrogation batch. M005a must not change the wire shape of `ExecutionEventKind`, so the two milestones do not collide. +- The foundation runner-request-validation corrective (`M005` in the foundation subsystem) is independent. Both touch `crates/eggwork-runner/src/lib.rs`, but in different regions: that one changes request validation, this one changes environment-rule ownership. +- Operations M007 (Windows service host) is independent and may run in parallel with all three milestones. +- M005a, M005b, and M005c are mutually independent of one another. + +## 7. Exit conditions + +The Security M005 batch closes only when: + +- M005a, M005b, and M005c each have their own closure record under `plans/closure/security-isolation-resource/` naming the exact verification that was run; +- M005c's closure record names the accepted ADR and the decided disposition; +- a degraded best-effort execution emits a diagnostic event that precedes the terminal event and any target output, proven by a non-vacuous test; +- a `Required` request still fails closed before the target starts, proven by a non-vacuous test; +- the runner's and the helper's environment rules are pinned to each other by a test that fails on a one-sided edit; +- the helper still has no workspace-crate production dependency; +- `architecture/overview.md`'s divergences table reflects the decided disposition of divergence #4, and no new row is added for a resolved item; +- `architecture/sandbox-helper.md`, `architecture/runner-execution.md`, and `architecture/server-node.md` describe the code as it now stands; +- the full pre-submit gate is green on the reviewed head; +- no high or medium finding remains without an explicit owner. diff --git a/plans/subsystems/security-isolation-resource-roadmap.md b/plans/subsystems/security-isolation-resource-roadmap.md index 38bab0c..46976bd 100644 --- a/plans/subsystems/security-isolation-resource-roadmap.md +++ b/plans/subsystems/security-isolation-resource-roadmap.md @@ -1,6 +1,6 @@ # Security, Isolation, and Resource Enforcement Roadmap -Status: closed through M004 (remote-admission C001 and Operations M002 included) +Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a and M005b correctives proposed; M005c blocked on ADR-0007 Canonical authority: @@ -150,6 +150,84 @@ Objective: Run hostile input/process/workspace/transport fixtures, audit dependencies and unsafe code, validate privilege/service configurations, and close high/medium findings. +### M005a — Degraded-isolation observability corrective + +Class: invariant + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md` + +Objective: + +Make degradation visible where a caller will actually see it. `SandboxResult::NotApplied` is recorded truthfully in the terminal snapshot, but `ExecutionEventKind::Diagnostic` has no production publisher — it is emitted only from test code — so a caller streaming events sees an ordinary successful execution when best-effort isolation or resource enforcement was not applied. The `Required` path must not change: a required request still fails closed before the target spawns. + +Exit conditions: + +- a degraded best-effort execution emits a diagnostic into the event stream, with a payload that identifies what degraded and why; +- the diagnostic is emitted on the same path as the terminal result, so the two cannot disagree; +- no `Required` execution reaches the target without the requested control; +- the required-isolation and required-resource fail-closed rules are unchanged. + +### M005b — Sandbox-helper environment parity corrective + +Class: invariant + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md` + +Objective: + +Give the sandbox environment deny-list one source of truth. The runner and the standalone sandbox helper maintain the same list independently and apply it with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper additionally enforces a `PATH` rule the runner does not. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix is a shared artifact plus a pinning test, not a shared crate. + +The duplication is live, and this milestone closes it. The runner's launch-specification builder starts from a fixed baseline and then appends every non-denied caller key, and none of the baseline keys except `PATH` is denied. A caller that sets `LANG` therefore produces a launch specification with two `LANG` entries; the helper refuses a specification with duplicate keys; and for a best-effort request the runner answers that pre-target setup failure by re-spawning the target **with no Landlock ruleset at all**. The observable result is a successful, unconfined execution whose only trace of the degradation is a `NotApplied` in the terminal snapshot. + +Exit conditions: + +- one source of truth exists that the helper binary can consume without gaining a workspace-crate dependency; +- the drop-versus-reject difference is decided explicitly per side and documented; +- a caller-supplied key that collides with a node-owned baseline key does not produce a duplicate-key launch specification, and does not cause a best-effort execution to lose its confinement; +- the direct path and the helper path agree on which value wins for a reserved key; +- the `PATH` rule is either enforced on both sides or replaced by an explicit statement of the actual child-environment baseline; +- a test pins the two lists element-wise, so a one-sided edit fails the build. + +### M005c — Resource-scoped authorization corrective + +Class: invariant + +Status: **blocked** — concrete blocker is ADR-0007, `plans/adrs/ADR-0007-resource-scoped-authorization.md` (**proposed, not accepted**) + +Corrective addendum: + +- `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` + +Objective: + +Decide and then close the disposition of the resource-scoped authorization hook. The production authorizer implements only the operation-level check, so the typed `ResourceId` carried by every request is never consulted, and a principal granted blob-read can read any known digest. The gap is already recorded as divergence #4, so this milestone is a decision about a known gap rather than a new defect report. Per `plans/003-planning-process.md` §4 the plan is written early to preserve design intent while the decision is pending. + +Exit conditions: + +- ADR-0007 is accepted and states whether resource-scoped grants are implemented or the hook and its plumbing are removed; +- the node does not present a mechanism as available while it is inert; +- the divergences-table entry is updated to the decided disposition. + ## 4. Capability semantics Requirements should encode whether a caller requests: diff --git a/plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md b/plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md new file mode 100644 index 0000000..ab60400 --- /dev/null +++ b/plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md @@ -0,0 +1,391 @@ +# Workspace and Artifact Transport Post-Closure Corrective — Data-Plane Ownership and Fail-Closed Capture + +Status: active corrective; M005a proposed, M005b proposed + +Predecessor roadmap: + +- `plans/subsystems/workspace-artifact-transport-roadmap.md` + +Historical predecessor closures: + +- `plans/closure/workspace-artifact-transport/001-status.md` — blob store and digest protocol +- `plans/closure/workspace-artifact-transport/002-status.md` — manifest and safe materialization +- `plans/closure/workspace-artifact-transport/003-status.md` — declared artifacts, retention, and GC +- `plans/closure/workspace-artifact-transport/004-status.md` — reusable manifest CAS and derived materialization + +Canonical authority remains: + +- `plans/000-long-term-specification.md#11-workspace-and-artifact-model` +- `plans/adrs/ADR-0004-content-addressed-workspaces-and-artifacts.md` +- `plans/002-long-term-roadmap.md` +- `plans/003-planning-process.md#corrective-work` + +Finding source: + +- repository-wide code interrogation pass over the reviewed baseline `81f34e0`; every finding below is new and is **not** recorded in the `architecture/overview.md` divergences table. + +## 1. Findings + +The workspace and artifact transport subsystem is three crate-private modules inside +`eggwork-server` — `blob.rs`, `workspace.rs`, and `artifact.rs` — that own immutable +content-addressed bytes, the reconstruction of a portable tree from a manifest, and the capture of +an execution's declared outputs. The subsystem's stated discipline is that a fact has exactly one +owner and every other module consults that owner. + +All four findings below are the same defect at four different scales: **a data-plane fact is +asserted in more than one place, and the copy that is not the owner is the copy an operator or a +caller can observe.** In WA-1 the duplicated fact is "capture succeeded". In WA-2 it is "this blob +is a GC candidate". In WA-3 it is "this is where a blob lives on disk". In WA-4 it is "this is the +owner id under which a manifest's blobs are pinned". + +Two of the four are violations of invariants the repository has already written down, in the very +module that owns them. The corrective therefore restores stated rules; it does not invent new +policy. + +### 1.1 On a non-Unix target, declared-artifact capture is refused but the execution still reports success (WA-1, highest severity) + +**What the data plane is supposed to guarantee.** The product's top-level claim is terminal state +*plus declared artifacts*. Declared outputs are the default artifact capture boundary +(`plans/subsystems/workspace-artifact-transport-roadmap.md`, durable invariant 6), and the data +plane is fail-closed by design: `architecture/data-plane.md` states in its shared-discipline +section that there is no best-effort path, that a symlinked output is refused rather than copied, +and that a missing required output fails the whole capture instead of producing a partial record +set. A caller that declared outputs and received none must be able to tell that apart from a +caller that declared no outputs. + +**What the code actually does.** `crates/eggwork-server/src/artifact.rs` has two variants of +`open_file_beneath`. The unix variant opens the root and each path component +descriptor-relatively with `O_NOFOLLOW`. The `#[cfg(not(unix))]` variant returns +`io::ErrorKind::Unsupported` with the message *"safe artifact capture is unavailable on this +platform"*. `capture_blob` in the same module calls `open_file_beneath` and propagates the error +with `?`; `capture_declared` calls `capture_blob` inside its capture loop and propagates with `?` +as well, so the first failure aborts the entire capture and no artifact record is published. + +`crates/eggwork-server/src/lib.rs` (`run_execution`) calls `artifact::capture_declared` in the +execution-finalization path and matches on the result: `Ok(count)` sets +`execution_result.artifact_count`, and `Err(_)` sets +`execution_result.finalization_failure = Some(ExecutionFinalizationFailure::ArtifactCapture)`. +Nothing else changes. The execution's own state remains `Succeeded`, its `exit_code` remains the +target's, and `artifact_count` remains `0`. The terminal event published afterwards is +`ExecutionEventKind::State(terminal)`; `eggwork-core`'s `ExecutionEventKind` has no +artifact-specific variant, so the failure is not in the event stream either. + +The consequence is a **successful execution with zero artifacts and a buried marker**. This is +not an untested edge: the integration test in `crates/eggwork-server/src/lib.rs` +(`blob_protocol_streams_verifies_deduplicates_and_enforces_quota`) asserts exactly this +combination — `state == ExecutionState::Succeeded`, `exit_code == Some(0)`, +`artifact_count == 0`, `finalization_failure == Some(ExecutionFinalizationFailure::ArtifactCapture)`. +The current behaviour is therefore *asserted*, not merely tolerated. + +Two further facts sharpen the consequence. First, `static_capability_features` in +`crates/eggwork-server/src/lib.rs` advertises `"artifact.declared.v1"` on every platform with no +platform condition, so a Windows node advertises declared-artifact capture and then refuses the +capture — a static claim where the repository's own capability rule requires a runtime probe. +Second, `ExecutionEventKind::Diagnostic` is the protocol's only carrier for a non-fatal +explanation, and it currently has **no production publisher**: every use of the variant in the +repository is in test code. There is therefore no existing production path by which the capture +failure could reach an event-streaming caller at all. + +`x86_64-pc-windows-msvc` is a published release target (`README.md`, "Installing a published +release"), so this is the disposition of a shipped platform, not a theoretical one. + +**Why this is not already recorded.** `architecture/data-plane.md` documents the behaviour +accurately — its error-model section says that `capture_declared` has no partial-success result +and that the caller records `ExecutionFinalizationFailure::ArtifactCapture` "while leaving the +execution's own exit state intact", and its "Honest gaps" section states that no test exercises +the non-unix branches, naming `open_file_beneath` returning `ErrorKind::Unsupported`. The design +record is honest about the mechanism. What is missing is the *judgment*: the divergences table in +`architecture/overview.md` records row 18 (artifact GC does not release blob references) but has +no row for this, and the README's Windows caveat covers isolation, resource enforcement, and +service management while saying nothing about artifacts. A caller reading the README would +reasonably expect declared artifacts to work on a Windows node. + +**Severity.** Highest of the four. Every caller-declared output is silently lost on a shipped +platform, and the loss is reported as success. + +### 1.2 The operator's GC preview and the apply pass use different candidate predicates (WA-2) + +**What the data plane is supposed to guarantee.** The canonical blob candidate selection lives in +`crates/eggwork-server/src/blob.rs`, in `BlobStore::unreferenced_candidates`. Its selection is +`WHERE NOT EXISTS (SELECT 1 FROM blob_references r WHERE r.digest = blobs.digest)`, ordered +coldest-first and bounded by `limit`. `BlobStore::garbage_collect` evaluates that same statement +in both its dry-run and its real pass. The doc comment on `unreferenced_candidates` states the +rule explicitly: + +> *"Shared by the dry run and the real run on purpose. They select at *different points* in the +> transaction — a preview before expired blob references are deleted, the real pass after — so the +> same statement must be evaluated in both places. Two hand-copied copies of it are what let the +> two paths drift apart and made `NodeGcReport.blob_candidates` under-predict what `--apply` would +> actually remove."* + +`architecture/data-plane.md` records the same reason independently: *"Reclamation queries +deliberately use `NOT EXISTS (SELECT 1 FROM blob_references ...)` rather than the counter."* The +counter is a denormalization: `blobs.reference_count` is written only by the +`blob_reference_insert` / `blob_reference_delete` triggers, never by Rust. + +**What the code actually does.** `crates/eggwork-server/src/operations.rs` does not use that +statement. Its `dry_run_gc` re-implements the blob candidate query by hand as +`WHERE reference_count = 0` — a different predicate over a different column, against a different +source of truth than the one the owner module selected on purpose. `operations::collect_garbage` +routes `dry_run == true` to `dry_run_gc`, and the apply path opens the real `WorkspaceManager`, +`BlobStore`, and `ArtifactStore` and calls their own collectors. `crates/eggwork-server/src/bin/eggworkd.rs` +makes the preview the default for the `gc` verb (`let dry_run = !args[index..].iter().any(|arg| arg +== "--apply");`), so the divergent path is the one an operator reaches first. + +The same function hand-copies the workspace candidate SQL, the retained-manifest candidate SQL, +and the artifact candidate SQL verbatim from their owner modules, and re-derives the store +metadata filenames (`/metadata.sqlite`, `/metadata.sqlite`) that +`blob.rs` and `workspace.rs` own. + +**The consequence.** The preview and the apply pass disagree about what is collectable, and the +disagreement is invisible in both directions. A blob whose `reference_count` is `0` while a +`blob_references` row lingers is predicted for deletion by the preview and not removed by +`--apply`. A blob whose `reference_count` is positive while no reference rows exist is not +predicted and *is* removed by `--apply`. Which way a given store errs depends on whether its +trigger-maintained counter has drifted from its reference rows — a property the preview depends +on and the apply path does not. Either way the operator's preview is a guess about a different +question than the one `--apply` answers. + +The existing preview test makes the drift structural rather than accidental: the fixture in +`crates/eggwork-server/src/operations.rs` +(`garbage_collection_preview_reads_only_and_reports_bounds`) builds a synthetic blob database +whose `blobs` table has columns `(reference_count, size_bytes, last_used_unix_ms)` — **no `digest` +column** — so the canonical predicate cannot even be evaluated against it. The fixture was shaped +to the hand-copied query. + +This is a violation of a stated invariant, not a hypothetical: the rule is written on the owner +module and broken in the sibling module. The historical claim that is no longer sufficient is in +`plans/closure/workspace-artifact-transport/004-status.md`, which records that the collector +ordering is "in both `NodeServer::collect_garbage` and the operator `collect_garbage` path, with +matching dry-run previews". Per `plans/003-planning-process.md#corrective-work`, that closure +record stays immutable and this corrective owns the newly discovered defect. + +### 1.3 The blob store's on-disk path layout is re-derived outside the `BlobStore` abstraction (WA-3) + +**What the data plane is supposed to guarantee.** `crates/eggwork-server/src/blob.rs` owns the +shard layout in exactly one place: `BlobStore::path_for` returns +`root.join(&digest.as_str()[..2]).join(digest.as_str())`. `architecture/data-plane.md` describes +that layout as a single level of sharding on the first two hex characters and states the reason +it is a pure function of the digest: a digest that survives `BlobDigest::parse` cannot name a +location outside the blob root. + +**What the code actually does.** `crates/eggwork-server/src/operations.rs` re-derives the same +layout by hand inside the operator's blob inspection verb (`inspect_blob`): it joins +`config.blob_root` with `&digest.as_str()[..2]` to form the shard directory, then joins the full +digest to form the object path. `crates/eggwork-server/src/workspace.rs` reaches the same place +from the other direction, in `materialize_tree`, by calling `blobs.path_for(digest)` and then +opening the result with a plain `File::open`, accepting the bytes on a **size-only** check +(`io::copy` must yield exactly `size_bytes`) and bypassing the store's verified-open path +(`BlobStore::open_verified`, which calls `BlobStore::verify_existing` and re-hashes the whole +object against its digest). + +**The consequence.** Two consumers of the layout sit outside the abstraction that owns it. A +change to shard depth or file naming would silently break the operator inspection verb, which +would report `NotFound` for objects that exist, and would not be caught by any test that exercises +only the store. The workspace materializer's bypass is narrower but real: `materialize` does +verify every referenced blob in its pre-flight via `blobs.verify_existing`, but `materialize_tree` +re-reads the object afterwards and copies it without re-verifying, so the bytes a workspace +actually receives are checked only by length. + +### 1.4 The manifest owner-id composite format is inlined at two sites instead of using its own helper (WA-4) + +**What the data plane is supposed to guarantee.** The `blob_references.owner_id` for owner kind +`"manifest"` is a `"{principal}:{manifest_digest}"` composite. +`crates/eggwork-server/src/workspace.rs` defines exactly one producer for it: +`fn manifest_owner_id(principal_id: &PrincipalId, manifest_digest: &str) -> String`. +`architecture/data-plane.md` records the composite as part of the reference-accounting contract. + +**What the code actually does.** Two call sites do not call it. In +`WorkspaceManager::manifest_garbage_collect` and in `WorkspaceManager::reconcile_manifests`, the +`principal_id` value is read out of a SQL row as a `String`, and the composite is built inline as +`format!("{principal_id}:{manifest_digest}")`. The helper takes `&PrincipalId`, and +`PrincipalId::new` returns a `Result`, so at these sites there is no validated `PrincipalId` to +hand it — which is why the format was inlined rather than reused. + +**The consequence.** The format has two producers. If the composite ever changes, the two inlined +sites release blob references under an owner id that does not match the one the references were +created under. The result is orphaned pins with no error and no symptom other than a blob +reference count that never falls — bytes that the store will not reclaim and that no operator +report explains. + +## 2. Corrective milestones + +### M005a — Declared-artifact capture fails closed + +Class: invariant + +Status: proposed + +Implementation plan: + +- `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md` + +Objective: + +Make the declared-artifact failure mode honest. An execution whose declared outputs could not be +captured must not present as a successful execution with missing declared artifacts, and the +platform claim must match the code on every shipped target. + +### M005b — GC preview and apply share one implementation; store-owned formats have one producer + +Class: invariant + +Status: proposed + +Implementation plan: + +- `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md` + +Objective: + +Make the operator's GC preview and its apply pass select candidates through the same +store-owned statement, and bring the blob path layout and the manifest owner-id composite back +under the modules that own them. + +## 3. The data-plane ownership rule this corrective establishes + +One owner per fact. After M005a and M005b, each of the following facts is produced in exactly one +place, and every other place consumes it rather than restating it. + +| Fact | Sole owner | Consumers must do this | +|---|---|---| +| "Was the declared capture completed?" | `crates/eggwork-server/src/artifact.rs` (`capture_declared` and its result type) | The server's finalization must consume the result and translate it into a truthful terminal state; it must not infer success from the absence of an error | +| "These blobs are GC candidates" | `crates/eggwork-server/src/blob.rs` (`unreferenced_candidates`) | The operator preview and the operator apply pass must evaluate that same statement; no module may write its own candidate query | +| "This is where a blob lives on disk" | `crates/eggwork-server/src/blob.rs` (`BlobStore::path_for`) | The operator inspection verb must go through the store; the materializer must go through the store's verified-open path | +| "This is the manifest owner id" | `crates/eggwork-server/src/workspace.rs` (`manifest_owner_id`) | Every site that pins or releases manifest blob references must call the helper | + +Two structural rules follow: + +1. A fact that a caller or an operator can observe may not be re-derived outside its owner. A copy + that is only *maintained* by a module's own tests is still a copy. +2. A stated invariant that lives in a doc comment on the owner module is not satisfied by a + sibling module that behaves differently. "The same statement must be evaluated in both places" + is a testable claim, and M005b makes it one. + +## 4. Durable invariants + +These extend the subsystem's existing invariants 1 ("Blob bytes must match their digest"), 6 +("Declared outputs are the default artifact capture boundary"), and 7 ("Storage exhaustion +produces typed failure and bounded cleanup"). + +1. An execution whose declared outputs could not be captured MUST NOT present as a successful + execution with missing declared artifacts. +2. A capture failure is visible on the terminal state, in the event stream, and to the caller — + not only as a nested marker inside the terminal snapshot. +3. The relationship between the number of declared outputs and the number of captured artifacts + is explicit in the terminal result, so a caller can distinguish "no declared outputs" from + "declared outputs that vanished". +4. The platform claim in `README.md` and in `architecture/overview.md`'s divergences table matches + the code on every shipped target. +5. The advertised capability set agrees with the runtime fact: a node that cannot capture does not + advertise that it can. A capability string is a runtime probe, not a compile target. +5. GC candidate selection has one owner. The operator's preview and the operator's apply pass + evaluate the same statement and cannot diverge by construction. +6. A reclamation query never consults the denormalized `blobs.reference_count` counter in place + of the `blob_references` rows. +7. The blob path layout has one owner. No module outside `blob.rs` reconstructs it. +8. The manifest owner-id composite has one producer. No module formats it inline. +9. Blob bytes are verified against their digest on the path that materializes them, not only in + a pre-flight that a later read can race. +10. No authentication, lease, generation, fencing, digest, or bound semantics weaken. +11. Eggwork remains a fixed-target, scheduler-free fabric: no queue, no worker selection, no + priority or fairness policy, no DAG, and no semantic retry is introduced. +12. The historical M001-M004 closure records remain immutable; this corrective owns the newly + discovered defects. + +## 5. Compatibility and migration + +**M005a.** The capture result type is internal to `eggwork-server`. Making the failure +truthful can be done with no wire change at all: the execution's terminal `ExecutionState` and +`ExecutionFailure` already have a vocabulary that can express "the target ran and the declared +outputs could not be collected". If the plan chooses instead to add a declared-output count to +`ExecutionResult`, that is a wire-additive change to a struct that is serialized into the +terminal snapshot; it must carry `#[serde(default)]` so an older peer still decodes it, and the +plan must record that the terminal snapshot is not byte-identical across the change. No stored +format changes. No stored blob, workspace, artifact, or manifest row is rewritten. + +**M005b.** No wire protocol change. No stored format change: the blob metadata schema, the +workspace metadata schema, the artifact schema, the `retained_manifests` schema, and the +`"{principal}:{digest}"` composite are all unchanged. The `path_for` layout is unchanged. The +corrective changes only *who computes* these values, not what they are. A blob store whose +`reference_count` has drifted from its reference rows is not migrated by this corrective; the +corrective simply stops the preview from depending on the drift. + +**Both.** Neither milestone changes the `eggworkd` command surface, the `NodeGcReport` shape, the +`NodeCapabilities` feature set, or any route. + +## 6. Downstream relationships + +- **Control plane / execution lifecycle.** The artifact capture failure path lives in the server's + execution-finalization code (`crates/eggwork-server/src/lib.rs`, `run_execution`), so WA-1 + touches the execution lifecycle that the foundation and control-plane subsystems own. The + boundary is respected as follows: **the data plane owns capture** — `artifact.rs` owns what + "capture completed" means and must report it; **the server's finalization owns the truthful + terminal state** — `run_execution` owns the transition to terminal and owns the mapping from a + capture result to an `ExecutionState`/`ExecutionFailure`/event. The data plane does not decide + the execution's terminal state, and the finalization does not re-derive whether capture + succeeded. Neither milestone changes admission, lease renewal, generation fencing, or the + event journal's shape. +- **Operations and distribution.** M005b changes the operator's `gc` preview output only in that + it becomes correct. `docs/operations.md` describes `gc` as a read-only preview by default and + states that `--apply` takes an exclusive lock on node state; that behaviour is unchanged. + Operations M007 (the Windows service host) is independent of both milestones. +- **Security, isolation, and resource.** Independent of the data plane itself, but not + independent of M005a in one narrow place: `ExecutionEventKind::Diagnostic` has no production + publisher, and the Security M005a degraded-isolation observability corrective needs one for a + different failure. Both milestones must extend the same server-side event-publishing path + rather than grow two divergent publishers for the same event kind. Neither milestone touches + Landlock, cgroups, the helper's trust, or admission. +- **Foundation and execution core.** Independent. The runner's process ownership, timeout, + cancellation, and output-limit behaviour are unchanged. M005a does not change which executions + are eligible for capture; it changes what an eligible execution reports when capture fails. +- **CodeGG integration.** Must not claim declared-artifact support on a platform where capture is + unavailable until M005a closes and the corrected node is re-qualified against it. +- **`NodeServer::collect_garbage`.** The in-process live collector and the operator's offline + collector are two paths to the same stores. M005b covers the operator's preview/apply pair. + The live collector's single caller is a test, and the divergence between the two paths is + noted in the M005b plan as an in-scope simplification opportunity, not as a separate milestone. + +## 7. Exit conditions + +M005a closes only when: + +- no execution can reach terminal state `Succeeded` while a declared output it asked for was not + captured; +- the capture failure is visible on the terminal state, in the event stream, and through the + client's own view of the execution — not only as `finalization_failure`; +- the terminal result makes the declared-output count and the captured-artifact count comparable, + so "no declared outputs" and "declared outputs that vanished" are distinguishable; +- the existing integration test that asserts `Succeeded` + `artifact_count == 0` + + `finalization_failure == Some(ArtifactCapture)` has been changed to assert the corrected + disposition, and the replacement test is proven non-vacuous; +- a test of the corrected behaviour is proven to run on a non-Unix target, and the platform + evidence is recorded against a real Windows host, not inferred from a compile; +- the README's Windows caveat and the `architecture/overview.md` divergences table state the + artifact disposition for every shipped platform, and the statement matches the code; +- the advertised capability set agrees with the runtime fact on every shipped platform — a node + that refuses declared outputs does not advertise `"artifact.declared.v1"`; +- `architecture/data-plane.md`'s "Honest gaps" entry about the untested non-unix branches is + updated to match the new evidence; +- no high or medium finding remains without an explicit owner. + +M005b closes only when: + +- the operator's dry-run report and the operator's apply pass select candidates through the same + store-owned statement, so that divergence is structurally impossible; +- the owner-module rule recorded on `BlobStore::unreferenced_candidates` is enforced by a test + rather than stated only in a doc comment; +- the operator's blob inspection verb resolves object paths through the store rather than + re-deriving the shard layout; +- the workspace materializer obtains blob bytes through the store's verified-open path rather + than a size-only check; +- the manifest owner-id composite has exactly one producer and both inlined call sites use it, + with the `&PrincipalId` versus `&str` mismatch resolved by an explicit decision rather than + assumed away; +- a test proves that the set of candidates the dry run reports is a subset of — and for the same + inputs, equal to — the set the apply pass removes; +- no public protocol surface and no stored format changed; +- `architecture/data-plane.md` and `architecture/operations-cli.md` are updated so their + descriptions of the preview and of blob inspection match the code, and their stale line-number + citations are replaced with symbol references in the same pass; +- no high or medium finding remains without an explicit owner. diff --git a/plans/subsystems/workspace-artifact-transport-roadmap.md b/plans/subsystems/workspace-artifact-transport-roadmap.md index 4d52b07..cad33a2 100644 --- a/plans/subsystems/workspace-artifact-transport-roadmap.md +++ b/plans/subsystems/workspace-artifact-transport-roadmap.md @@ -1,6 +1,6 @@ # Workspace and Artifact Transport Roadmap -Status: active roadmap; M001-M004 closed +Status: active roadmap; M001-M004 closed; M005a and M005b data-plane correctives proposed Canonical authority: @@ -132,6 +132,58 @@ Exit conditions: - cross-principal manifest reuse is impossible; - no Git semantics or shared writable workspace tree enters Eggwork. +### M005a — Declared-artifact capture fail-closed corrective + +Class: invariant + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md` + +Objective: + +Stop a shipped target from silently losing declared outputs. On a non-Unix target the safe artifact-capture open is refused, and the execution still reports `Succeeded` with a zero artifact count and a nested finalization-failure marker. An execution whose declared outputs could not be captured must not present as a successful execution with missing artifacts. + +Exit conditions: + +- a failed capture is visible in the terminal state, the event stream, and to the caller, not only as a nested marker; +- the caller can distinguish "no declared outputs" from "declared outputs that were not captured"; +- the platform claim in the README and in the divergences table matches the code; +- the required-isolation and fail-closed rules are unchanged. + +### M005b — GC preview and store ownership corrective + +Class: invariant + +Status: proposed + +Corrective addendum: + +- `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` + +Implementation plan: + +- `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md` + +Objective: + +Make the operator's GC preview and the apply pass share one implementation, so they cannot disagree, and bring the blob store's path layout and the manifest owner-id format back under the modules that own them. The owner module already states that the dry run and the real run must share the candidate statement; that rule is currently violated in the sibling module, where the preview uses a different predicate from the one the apply pass uses. + +Exit conditions: + +- the dry-run report and the apply pass select candidates through the same store-owned statement; +- the operator's blob inspection goes through the store's path and ownership API rather than re-deriving the shard layout; +- the workspace materializer uses the store's verified-open path; +- the manifest owner-id composite has exactly one producer, and the two inlined call sites use it; +- a test proves that the preview and the apply pass agree; +- no public protocol surface and no stored format changes. + ## 4. Future optimized materializers After M004, optional adapters may add: From 6f419572800f39c15eca5f9a6d630cce848660c5 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 15:01:42 +0000 Subject: [PATCH 02/37] feat(security): M005a degraded isolation observability A best-effort isolation or resource request that could not be enforced now produces a bounded, grammar-conforming diagnostic event in the execution's event stream, emitted by the runner before the target spawns and therefore delivered before any target output and before the terminal event. The diagnostic grammar is owned by eggwork-core so the runner (producer) and the server (forwarder) share one definition. The runner's public OutputChunk becomes an enum carrying a Diagnostic variant. No wire representation, authorization, lease, generation, fencing, or digest bound changed. The Required path is untouched and still fails closed before the target starts. --- architecture/protocol.md | 61 +++ architecture/runner-execution.md | 67 ++- architecture/sandbox-helper.md | 5 + architecture/server-node.md | 33 ++ crates/eggwork-core/src/lib.rs | 339 +++++++++++++ crates/eggwork-runner/src/lib.rs | 321 ++++++++++-- .../tests/diagnostic_degradation.rs | 325 +++++++++++++ crates/eggwork-server/src/lib.rs | 385 ++++++++++++++- .../005a-status.md | 455 ++++++++++++++++++ .../security-isolation-resource-roadmap.md | 9 +- 10 files changed, 1950 insertions(+), 50 deletions(-) create mode 100644 crates/eggwork-runner/tests/diagnostic_degradation.rs create mode 100644 plans/closure/security-isolation-resource/005a-status.md diff --git a/architecture/protocol.md b/architecture/protocol.md index eff401d..8c782fc 100644 --- a/architecture/protocol.md +++ b/architecture/protocol.md @@ -93,3 +93,64 @@ own `NodeStatus` and `NodeCapabilities` are unchanged: they answer "is this node accepting work", and this document answers "what did this host look like". The two are never merged, and nothing in this contract qualifies an execution. + +## The execution diagnostic payload (schema version 1) + +`ExecutionEventKind::Diagnostic(String)` carries one diagnostic payload. The +payload is a single bounded string, not an object, because it rides inside an +event whose envelope is already bounded. + +### Grammar + +```text +eggwork.diagnostic..v1 key=value key=value … +``` + +* The prefix is `eggwork_core::DIAGNOSTIC_PREFIX` (`eggwork.diagnostic.`) and + the schema suffix is `eggwork_core::DIAGNOSTIC_SCHEMA_SUFFIX` (`.v1`). +* The class is one of the closed set in `eggwork_core::DIAGNOSTIC_CLASSES`: + `isolation.degraded` (`DIAGNOSTIC_CLASS_ISOLATION_DEGRADED`) and + `resources.degraded` (`DIAGNOSTIC_CLASS_RESOURCES_DEGRADED`). A class + outside the set is refused, not guessed at, because the class is what a + consumer dispatches on. +* Fields are `key=value` pairs separated by single spaces. The key set is a + lowercase ASCII token of at most `MAX_DIAGNOSTIC_KEY_BYTES` bytes; `class` is + reserved and is derived from the payload's own class. +* Values are printable ASCII. Every character outside `!`..=`~` — a space + included — becomes `_`, so a value can never contain the separator and the + tokenisation stays unambiguous without an escaping scheme. + +### Required keys + +| Key | Meaning | +| --- | --- | +| `class` | The class, repeated as a field so a consumer that only reads the key/value pairs does not have to parse the prefix. | +| `requirement` | Always `best_effort`. A degradation is by definition a best-effort request that was not honoured; a required request is refused instead. | +| `reason` | The bounded, human-readable cause of the degradation. | +| `profile` | `isolation.degraded` only: the requested filesystem profile. | +| `dimension` | `resources.degraded` only: the affected dimension (`memory`, `cpu`, `pids`). | + +`eggwork_core::DiagnosticPayload::parse` enforces the grammar, the closed +class set, the bound, and the presence of `class`, `requirement` and `reason`. + +### Bound and truncation + +The assembled payload never exceeds +`eggwork_core::MAX_DIAGNOSTIC_PAYLOAD_BYTES` (`MAX_METADATA_VALUE_BYTES`, +2048 bytes). When the fields do not fit, values are shortened in insertion +order: the first value that does not fit is cut on a UTF-8 character boundary +and gains the literal marker `eggwork_core::DIAGNOSTIC_TRUNCATION_MARKER` +(`...[truncated]`), and the fields after it are omitted. The marker is what +makes truncation observable — a bounded payload never silently reads as a +complete statement. The free-form `reason` is inserted last so that it +absorbs the overage and the structured keys survive intact. + +### What the payload deliberately does not carry + +No secret, no credential, no path outside the execution's own workspace +naming, no stack trace, and no per-dimension measurement. A diagnostic says +*what was not enforced and why*, in the smallest form that lets a caller act +on it. The terminal snapshot (`ExecutionResult.sandbox`, +`ExecutionResult.resources`) remains the authoritative evidence; the +diagnostic makes the same fact observable while the execution is still +running. diff --git a/architecture/runner-execution.md b/architecture/runner-execution.md index 39f76ac..9204c37 100644 --- a/architecture/runner-execution.md +++ b/architecture/runner-execution.md @@ -218,9 +218,11 @@ The non-Linux variant is unconditional refusal: `Err("trusted Landlock is unsupp **4. Setup.** `self.setup.prepare(&request.sandbox, &request.resources, &request.root).await?`. The `?` means a required-sandbox or required-resource refusal is an `Err`, never a silent downgrade to direct execution. +**4a. Degradation diagnostics.** `report_setup_degradations` turns the outcomes `prepare` returned into diagnostic payloads and sends them on the output channel. It runs here — after the setup resolved and before any process exists — so the diagnostic reaches the caller *before* the target can produce a single byte of output. See [Reporting a degradation](#reporting-a-degradation) below. + **5. Helper selection (Linux).** `use_helper` is true when (`sandbox != None` **and** `setup.sandbox` is `Applied`) or `setup.resources` is `Applied`, **and** `sandbox_helper_path()` is `Some`. The two conditions are the only way the helper subprocess is created. -**6. Channel construction (Linux, if `use_helper`).** `SandboxChannel::new` may fail. On failure, if the request is not `Required` and has no required resources, both outcomes are downgraded to `NotApplied { reason }` and execution proceeds **without** the helper. Otherwise the error propagates. +**6. Channel construction (Linux, if `use_helper`).** `SandboxChannel::new` may fail. On failure, if the request is not `Required` and has no required resources, both outcomes are downgraded to `NotApplied { reason }`, the degradation is reported on the output channel, and execution proceeds **without** the helper. Otherwise the error propagates. **7. Command assembly.** `channel.command()` or `direct_command(&request, cwd)`, then `wrap_resource_command(command, &request.resources, &setup.resources)` which — only when the outcome is `Applied { backend: "systemd-cgroup-v2" }` — rewrites the command through `SystemdCgroupBackend::wrap` into `systemd-run [--user] --scope --quiet --unit=eggwork--.scope --working-directory --property=… -- `. When both isolation and resources apply, the systemd scope wraps the *helper*, and the helper execs the target inside the scope. The wrapper's own environment is `env_clear()` plus `DBUS_SESSION_BUS_ADDRESS`, `XDG_RUNTIME_DIR`, `HOME` (only if present in the parent), `PATH=/usr/bin:/bin`, and the wrapped command's explicit environment. Non-Linux-unix skips this and calls `direct_command` directly. @@ -229,9 +231,9 @@ The non-Linux variant is unconditional refusal: `Err("trusted Landlock is unsupp **9. Handshake (Linux + channel).** `SandboxChannel::wait(&mut child, cancellation.clone())` has four outcomes: - `Ok(Some(session))` — the target is confirmed confined and started; the session is retained for post-exit limit attribution. -- `Ok(None)` and the request is not required — the helper child is `start_kill`ed and waited, the outcomes are downgraded (`"Landlock helper could not enforce the requested profile"` / `"resource helper could not verify the cgroup limits"`), and the **command is rebuilt and respawned** without the helper. +- `Ok(None)` and the request is not required — the helper child is `start_kill`ed and waited, the outcomes are downgraded (`"Landlock helper could not enforce the requested profile"` / `"resource helper could not verify the cgroup limits"`), the degradation is reported on the output channel, and the **command is rebuilt and respawned** without the helper. The diagnostic is emitted *after* the handshake failure is classified and *before* the respawn: the target is about to run with no Landlock ruleset and no cgroup verification, and the caller has to learn that before the target runs. - `Ok(None)` and the request is required — kill, wait, `Err(RunnerError::RequiredSetupUnavailable)`. -- `Err(_)` — kill, wait, return the error. `BeforeTarget` errors are recoverable (respawn unwrapped) when nothing was required; `AfterTarget` errors are always terminal. +- `Err(_)` — kill, wait, return the error. `BeforeTarget` errors are recoverable (respawn unwrapped) when nothing was required; `AfterTarget` errors are always terminal. A recoverable `BeforeTarget` error reports the degradation before the respawn, exactly as the `Ok(None)` arm does. Note the ordering: `let process_group = child.id();` is taken at line 1290, *after* the handshake, so the group that gets signalled is the group of whichever child actually ended up running. @@ -303,7 +305,7 @@ Consequences worth checking as a reviewer: retention is exactly `limit` bytes fo 1. `capture.push(&buffer[..count], capture_limit)` — always, before anything else. 2. If `overflow == Terminate` and `total_bytes` crossed `capture_limit` on this read (`before <= capture_limit && after > capture_limit`), `overflow_tx.send(true)`. -3. `for bytes in buffer[..count].chunks(chunk_limit)` → `output_tx.try_send(OutputChunk { stderr, bytes })`; on **any** error, `dropped += bytes.len() as u64`. +3. `for bytes in buffer[..count].chunks(chunk_limit)` → `output_tx.try_send(OutputChunk::Stdout(bytes))` or `OutputChunk::Stderr(bytes)` depending on the reader's stream; on **any** error, `dropped += bytes.len() as u64`. Why this is the right trade: the reader's job is to keep the pipe empty, because a child blocked on a full stdout pipe can never reach its own exit, never observe cancellation, and never respond to a timeout. `try_send` therefore never awaits. A full or closed channel costs *event* fidelity, not process progress, and the loss is machine-reported through `stream_chunks_dropped` so the caller can decide whether a missing chunk is acceptable. The alternatives are both worse: blocking on `send` reintroduces the deadlock the drain exists to prevent, and dropping the read (or the child) turns a slow consumer into a correctness failure. The `BoundedCapture` totals remain exact regardless of channel pressure, so the durable record of what the child produced is not a function of consumer speed. @@ -345,7 +347,58 @@ Why this is the right trade: the reader's job is to keep the pipe empty, because `ExecutionProvenance { execution_id: Option, generation: Option }` is the round-trip handle: the caller supplies it, the runner injects it into the child environment, and returns it on the result so a caller can attribute a receipt without re-deriving anything. -`OutputChunk { stderr: bool, bytes: Vec }` is the streaming unit. Its doc says consumers "must treat bytes as arbitrary binary data" — there is no encoding assumption anywhere in the reader. +`OutputChunk` is the streaming unit, and it is an enum: `OutputChunk::Stdout(Vec)`, `OutputChunk::Stderr(Vec)` and `OutputChunk::Diagnostic(String)`. Its doc says consumers "must treat bytes as arbitrary binary data" — there is no encoding assumption anywhere in the reader. The `Diagnostic` variant carries a bounded payload (see [protocol.md](protocol.md#the-execution-diagnostic-payload-schema-version-1)) rather than bytes, and it is the only way a degradation reaches a caller. + +### Reporting a degradation + +A degradation is a *best-effort* request that could not be honoured. It is +reported on the output channel as `OutputChunk::Diagnostic`, and the server +forwards it as `ExecutionEventKind::Diagnostic`. The terminal snapshot +(`ExecutionResult.sandbox`, `ExecutionResult.resources`) carries the same fact; +the diagnostic exists so that a caller watching the stream sees the +degradation *while the execution is running* rather than only in the terminal +result. + +**Why the runner and not the server.** The server learns the outcome from +`RunnerResult`, which arrives after the execution has finished. A diagnostic +the server derived from that result would necessarily arrive after all target +output, which is the gap this reporting exists to close. The runner knows +*why* an enforcement was not applied at the moment it decides not to apply +it, and the output channel is the one carrier that preserves the order +between the runner's knowledge and the target's output. + +**Where the runner emits.** + +| Site | When | Ordering | +| --- | --- | --- | +| `report_setup_degradations` after `prepare` | unsupported profile, untrusted helper, no backend configured, resource-probe failure | before the target process exists | +| the `SandboxChannel::new` failure arm | the helper could not even be launched | before the target process exists | +| the `SandboxChannel::wait` recovery arms (`Ok(None)` and a recoverable `BeforeTarget` error) | the handshake failed and the target is about to be respawned directly | after the failure is classified, before the respawn | +| the post-mortem resource-observation block | the helper could not open a counter it had installed, so the limit cannot be *verified* | after the target exited, before the terminal event | + +The last row is the one exception to "before the target's output", and it is +a property of the fact rather than of the mechanism: the helper reports an +unobservable counter only after the target has exited, so no implementation +could report it earlier. It still precedes the terminal event, because the +server drains the output channel before it publishes the terminal state. + +**The rules.** + +* A `Required` request is *refused*, never degraded. `prepare` returns an + `Err` before any diagnostic could be emitted, and a refusal is not a + degradation: reporting one would dress a fail-closed refusal up as an + advisory. +* One degraded dimension produces exactly one diagnostic. `ReportedDegradations` + keeps the bookkeeping, because a degradation can be discovered twice — a + sandbox `prepare` could not apply may also be the sandbox the handshake + could not enforce — and the second discovery refines the recorded outcome + rather than duplicating the event. +* `resources.degraded` carries the affected `dimension`, and one event is + emitted per affected dimension when more than one is affected. +* An execution with nothing degraded emits no diagnostic at all. +* The runner never emits a diagnostic for a degradation it did not classify + itself: the payload and the terminal snapshot are derived from the same + `SetupOutcome`, so the two cannot disagree. `RunnerResult::execution_result()` (line 977) — also reachable via `impl From for ExecutionResult` (line 1924) — maps to the protocol-neutral result: @@ -427,6 +480,8 @@ Drop-safety is partial by design. Every `Command` sets `.kill_on_drop(true)`, so | Required setup fails closed before the target runs | `TrustedLandlockSetup::prepare`; `NoExecutionSetup::prepare`; `SandboxChannel::wait` decode; `wrap_resource_command` backend match | `unsupported_resource_limits_are_reported_or_rejected_before_spawn` (marker file absent); `helper_trust_checks_reject_missing_wrong_and_symlinked_helpers` and `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` (helper crate) | | Advisory capability == enforcement answer | one `verify_trusted_helper`; `probe_landlock_ruleset` mirrors the helper's rules; delegation in `operations::trusted_helper` | `trusted_helper_advertises_landlock_workspace_rw_capability`; `missing_helper_advertises_no_landlock_capability`; `no_setup_advertises_empty_dynamic_capabilities`; `capability_feature_string_is_frozen_for_workspace_rw_profile` | | Pre-spawn refusals are typed and distinguishable | the two early returns in `run`; `failure_for_runner_error` in the server | `cancellation_before_spawn_and_spawn_failure_are_typed`; `unsupported_resource_limits_are_reported_or_rejected_before_spawn` | +| A degradation is reported in the stream, before the target's output | `report_setup_degradations` after `prepare`, in the `SandboxChannel::new` failure arm, and in the handshake recovery arms; `OutputChunk::Diagnostic` on the same channel as the target's output | `crates/eggwork-runner/tests/diagnostic_degradation.rs` (the diagnostic is the first chunk on the channel); server-side `a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal` (sequence numbers) | +| A required request is never reported as a degradation | `report_setup_degradations` only reports `BestEffort` requests; `prepare` errors on a required request before any diagnostic could be emitted | `a_required_sandbox_is_refused_without_a_degradation_diagnostic`; server-side `a_required_sandbox_never_reaches_the_target_and_is_not_reported_as_a_degradation` | | Cross-platform honesty | `#[cfg(not(unix))]` refusal; non-Linux fail-closed fallbacks | none in this crate (see Test coverage) | ## Platform support matrix @@ -486,6 +541,8 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu `tests/capability_probe.rs` covers the advertisement boundary end to end. It copies the built `eggwork-sandbox-helper` out of `$CARGO_TARGET_DIR/debug` (or `OUT_DIR`) into a fresh `0700` tempdir as `0755`, deliberately leaks the tempdir, and asserts `LocalProcessRunner::new(TrustedLandlockSetup::new(helper)).execution_capabilities()` contains `isolation.landlock.workspace-rw.v1` on an ABI-V4 kernel. It **skips** (prints and returns) when no helper binary is present. The mirror case, `missing_helper_advertises_no_landlock_capability`, points at `/nonexistent/eggwork-sandbox-helper` and asserts the feature is absent. +`crates/eggwork-runner/tests/diagnostic_degradation.rs` is the degradation-reporting suite. It drives the runner through its public API with `LocalProcessRunner::new(NoExecutionSetup)` — chosen explicitly, because `LocalProcessRunner::default()` picks a setup from the environment and a test that wanted "no enforcement available" could silently get an enforcing one. The argv is platform specific (`cmd.exe` on Windows, `/bin/sh` elsewhere) because the `windows-runner` CI job runs this suite and the runner has platform-specific spawn paths the diagnostic sits in front of. The proofs are: a degraded best-effort sandbox emits exactly one diagnostic and it is the *first* chunk on the channel, ahead of the target's output; a degraded best-effort resource request emits one diagnostic naming the affected dimension, and two affected dimensions emit two diagnostics; a required sandbox is refused with `RequiredSetupUnavailable`, the target's marker file does not exist, and no diagnostic is emitted; an execution with nothing degraded emits no diagnostic; a cancellation before the spawn emits no diagnostic; and every emitted payload stays within `MAX_DIAGNOSTIC_PAYLOAD_BYTES` and parses against the documented grammar. + `SandboxChannel` internals are covered from the helper crate's integration test, `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`, which drives the runner's public API: outside read/write denial, helper trust rejections (missing/wrong/symlinked), workspace and cwd symlink escapes, timeout and cancellation reaping the helper's own process group, required memory/PID/CPU enforcement and classification, concurrent cgroup scope isolation, and `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target`. **Thin areas, honestly:** diff --git a/architecture/sandbox-helper.md b/architecture/sandbox-helper.md index 86d041e..26df79d 100644 --- a/architecture/sandbox-helper.md +++ b/architecture/sandbox-helper.md @@ -254,6 +254,10 @@ The step is `std::process::Command::spawn`, not a self-`execve`. That is a delib The runner's reading of those bytes (`SandboxChannel::wait`, `lib.rs:1798`): the first byte `0 | 2 | 3 | 30 | 31` → `Ok(None)` (no resource-reporting session; the run continues), `>= 4` → `Err(SandboxWaitError::BeforeTarget(RunnerError::Setup("sandbox helper rejected its launch specification (status {code})")))`, `1` → read the second byte: `1` → `Ok(Some(SandboxSession))`, `0` → `AfterTarget(Spawn("sandbox target could not start"))`, anything else → `"sandbox status was invalid"`. Every arm is a single byte read, never a length-prefixed or textual protocol. +**The handshake recovery path and what the caller is told.** When the helper cannot confirm confinement — status byte `0`, `2`, `3`, `30` or `31`, or a spec rejection the runner treats as recoverable — the runner kills the helper tree, rewrites `setup.sandbox` and `setup.resources` to `NotApplied { reason }`, and re-spawns the target **directly**, with no Landlock ruleset and no cgroup verification. The target therefore runs unconfined, and the runner reports that as a degradation diagnostic on its output channel (`OutputChunk::Diagnostic` → `ExecutionEventKind::Diagnostic`) before the re-spawn, so the caller learns the execution ran unconfined while it is still running rather than only from the terminal result. The diagnostic's class is `isolation.degraded` for the sandbox and `resources.degraded` for the resource dimension; the grammar and bound are in [protocol.md](protocol.md#the-execution-diagnostic-payload-schema-version-1). The runner's own rules for when this happens live in [runner-execution.md](runner-execution.md#reporting-a-degradation); from the helper's side the only requirement is the one below. + +**The unobservable counter is a post-mortem fact.** The helper opens the cgroup counters it needs *before* it spawns the target, but it can only report that it could not open them after the target has exited — the counters are read under a 2 s timeout once the target is done. When the helper reports that a counter was unobservable, the runner rewrites the affected resource dimension to `NotApplied` and emits the matching `resources.degraded` diagnostic at that point. That diagnostic necessarily follows the target's output, because the fact it reports only exists after the target exited; it still precedes the terminal event. A caller must therefore read the *terminal* resource result as the authoritative evidence and the diagnostic as the running-time notice. + The wire sequence, as a fixed four-message exchange with no framing beyond "one byte": | # | Direction | Byte | Meaning | @@ -341,6 +345,7 @@ In detail: | Limit breaches are attributed per dimension, not guessed | `ResourceEvents` bit flags → `ResourceDimension::{Memory, Pids}` | `required_memory_limit_is_enforced_and_classified`, `required_pid_limit_is_enforced_and_classified` | | Per-run cgroup isolation is real, not shared state | runner-side scope creation; helper only reads its own `/proc/self/cgroup` | `concurrent_resource_scopes_keep_pid_limits_isolated` | | A malformed spec aborts before the target runs | `read_spec` → code 12 + `Err` | `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` | +| A runtime enforcement failure is reported to the caller, not only to the snapshot | the runner's handshake recovery path emits a diagnostic before it re-spawns the target directly | runner-side `crates/eggwork-runner/tests/diagnostic_degradation.rs`; server-side `a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal` | | An unavailable status channel aborts before the spec is read | `UnixStream::connect` first (`main.rs:69`) | same test | | The environment is rebuilt, never inherited | `env_clear()` + pinned `PATH` + validated spec env (`main.rs:100`) | `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` (`PATH=/malicious/path`) | | Loader/interpreter/credential knobs never reach the target | `denied_environment_key` in both crates | none directly (runner-side filter is what test 1 observes) | diff --git a/architecture/server-node.md b/architecture/server-node.md index 9a7314f..9eebd47 100644 --- a/architecture/server-node.md +++ b/architecture/server-node.md @@ -550,6 +550,28 @@ and the page comes from `store.load_page`. No correctness rests on the broadcast `slow_event_consumer_is_bounded_and_gets_a_stream_error` (`lib.rs:3102`) pins the failure mode explicitly rather than allowing an unbounded per-subscriber queue. +**Where a degradation diagnostic is published.** The forwarding loop maps the runner's +`OutputChunk::Diagnostic(payload)` to `ExecutionEventKind::Diagnostic(payload)` and publishes it +through the same `publish` funnel as any other event, with `ExecutionState::Running` as the proposed +state. The payload is forwarded unchanged: the runner is the sole producer and is inside the node's +trust boundary, so the server does not re-derive or second-guess it. + +**The publication point is load-bearing.** `publish` returns early when the recorded base state is +already terminal, and `store::ExecutionStore::commit_event` refuses to append to a terminal +execution. A diagnostic published *after* the terminal event is therefore **silently dropped** — +not rejected, not reported, simply lost. That is why the diagnostic is published from the forwarding +loop while the execution is still running, and why the runner emits it *before* it spawns the target: +the `biased` `select!` drains the runner's output channel first, so a chunk the runner sent before the +spawn is published before any output the target produced, and long before the terminal event. The +ordering is asserted on event sequence numbers, not by inspection — see +`a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal`. + +A consequence worth stating plainly: a diagnostic the server derived from the `RunnerResult` could +not satisfy this. The result arrives after the execution finished, so such a diagnostic would land +after the terminal event and be dropped by the rule above. The runner is the only party that knows +*why* an enforcement was not applied, and it knows it at the moment it decides not to apply it. The +grammar and bound of the payload are in [protocol.md](protocol.md#the-execution-diagnostic-payload-schema-version-1). + `publish` is the single write funnel, and it takes **two** locks with different jobs. `ExecutionRecord::commit_lock` (`lib.rs:205-216`) serialises publishers across the durable commit; `snapshot` is a plain `RwLock` held only for the cheap read and the short assign. The order is: @@ -936,6 +958,17 @@ file). Fixtures first: `init_tls`, `issue_identity`, `tls_material`, `untrusted_ - 5906 / 6180 — terminal records survive drain, and concurrent drain outcomes are closed. - 6104 `secret_sentinels_stay_out_of_error_and_debug_surfaces` — sentinels searched across error and `Debug` renderings. +- The M005a degradation-diagnostic set: `a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal` + (the diagnostic's sequence number is strictly below the first stdout event's and below the terminal + event's), `the_diagnostic_is_replayed_from_the_journal_after_the_execution_ended` (the diagnostic is + committed, not merely broadcast), `a_required_sandbox_never_reaches_the_target_and_is_not_reported_as_a_degradation` + (the marker file is absent, the terminal classification is `Failed`/`Internal`, and no diagnostic is + published), `an_execution_with_nothing_degraded_publishes_no_diagnostic`, and + `a_degraded_best_effort_resource_request_publishes_a_dimension_scoped_diagnostic`. They use the + `node_with_runner` fixture, which injects the runner explicitly; the required-refusal case uses the + `AdvertisesLandlockButCannotEnforce` fixture, because the admission gate otherwise refuses a + `Required` request before the runner is reached and the runner's own fail-closed path would be + unreachable. **Honest gaps**, identified from the test names without reading every body: diff --git a/crates/eggwork-core/src/lib.rs b/crates/eggwork-core/src/lib.rs index d65c8f8..6e1c8a9 100644 --- a/crates/eggwork-core/src/lib.rs +++ b/crates/eggwork-core/src/lib.rs @@ -37,6 +37,267 @@ pub const MAX_WORKSPACE_PATH_BYTES: usize = 1024 * 1024; pub const MAX_WORKSPACE_DEPTH: usize = 128; pub const MAX_WORKSPACE_LOGICAL_BYTES: u64 = 2 * 1024 * 1024 * 1024; +/// Prefix of every diagnostic payload. +/// +/// A diagnostic is carried by [`ExecutionEventKind::Diagnostic`] as a single +/// bounded string. The grammar is +/// `eggwork.diagnostic..v1 key=value key=value …`, so the prefix and +/// the schema suffix bracket the class name and make the payload +/// self-describing: a reader can tell what kind of fact it is holding without +/// out-of-band knowledge. +pub const DIAGNOSTIC_PREFIX: &str = "eggwork.diagnostic."; + +/// Schema version suffix of every diagnostic payload. +pub const DIAGNOSTIC_SCHEMA_SUFFIX: &str = ".v1"; + +/// The class of a diagnostic that reports a requested best-effort filesystem +/// isolation that was not applied. +pub const DIAGNOSTIC_CLASS_ISOLATION_DEGRADED: &str = "isolation.degraded"; + +/// The class of a diagnostic that reports a requested best-effort resource +/// enforcement that was not applied. +pub const DIAGNOSTIC_CLASS_RESOURCES_DEGRADED: &str = "resources.degraded"; + +/// The closed set of diagnostic classes. A payload naming anything else is +/// refused rather than guessed at, because a class is what a consumer +/// dispatches on. +pub const DIAGNOSTIC_CLASSES: [&str; 2] = [ + DIAGNOSTIC_CLASS_ISOLATION_DEGRADED, + DIAGNOSTIC_CLASS_RESOURCES_DEGRADED, +]; + +/// Ceiling on a whole diagnostic payload. +/// +/// The bound is deliberately the same as one event-metadata value: a +/// diagnostic is operator-facing text carried inside an event, so it must not +/// be able to dominate the event it rides in. +pub const MAX_DIAGNOSTIC_PAYLOAD_BYTES: usize = MAX_METADATA_VALUE_BYTES; + +/// Ceiling on one diagnostic key. +pub const MAX_DIAGNOSTIC_KEY_BYTES: usize = 32; + +/// The literal marker appended to a diagnostic value that had to be shortened. +/// +/// The marker is what makes truncation *observable*: a reader can tell a +/// shortened reason from a complete one, so a bounded payload never silently +/// reads as a complete statement. +pub const DIAGNOSTIC_TRUNCATION_MARKER: &str = "...[truncated]"; + +/// Errors from building or parsing a diagnostic payload. +#[derive(Debug, Clone, PartialEq, Eq, Error)] +pub enum DiagnosticError { + #[error("diagnostic class {0} is not in the closed class set")] + UnknownClass(String), + #[error("diagnostic key {0} is not a valid diagnostic key")] + InvalidKey(String), + #[error("diagnostic key {0} is reserved")] + ReservedKey(String), + #[error("diagnostic payload does not match the documented grammar")] + InvalidGrammar, + #[error("diagnostic payload exceeds its {max}-byte limit")] + TooLong { max: usize }, +} + +/// A bounded, machine-readable diagnostic payload. +/// +/// The payload is built from a class drawn from [`DIAGNOSTIC_CLASSES`] and an +/// ordered list of key/value pairs, and is rendered by [`DiagnosticPayload::build`] +/// as `eggwork.diagnostic..v1 key=value key=value …`. +/// +/// Two bounds are enforced here rather than at the call site, because a +/// diagnostic rides inside an event and a caller that forgets to bound it would +/// otherwise be able to overflow the event envelope: +/// +/// * the assembled payload never exceeds [`MAX_DIAGNOSTIC_PAYLOAD_BYTES`]; +/// * a value that does not fit is shortened on a UTF-8 character boundary and +/// gains [`DIAGNOSTIC_TRUNCATION_MARKER`], so the loss is visible in the +/// payload instead of being silent. +/// +/// Values are normalised to printable ASCII (everything outside `!`..=`~` +/// becomes `_`) so that the space-separated `key=value` grammar stays +/// unambiguous: a value can never contain the separator or a newline. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DiagnosticPayload { + class: String, + fields: Vec<(String, String)>, +} + +impl DiagnosticPayload { + /// Creates a payload for a class in the closed set. + /// + /// A class outside [`DIAGNOSTIC_CLASSES`] is refused: the class is what a + /// consumer dispatches on, so an unknown one cannot be honoured. + pub fn new(class: &str) -> Result { + if !DIAGNOSTIC_CLASSES.contains(&class) { + return Err(DiagnosticError::UnknownClass(class.to_owned())); + } + Ok(Self { + class: class.to_owned(), + fields: Vec::new(), + }) + } + + /// The diagnostic class. + pub fn class(&self) -> &str { + &self.class + } + + /// Adds a key/value pair. + /// + /// The key must be a lowercase ASCII token of at most + /// [`MAX_DIAGNOSTIC_KEY_BYTES`] bytes and must not be `class`, which the + /// builder derives from the payload's own class. + pub fn set( + &mut self, + key: &str, + value: impl Into, + ) -> Result<&mut Self, DiagnosticError> { + if key == "class" { + return Err(DiagnosticError::ReservedKey(key.to_owned())); + } + if !valid_diagnostic_key(key) { + return Err(DiagnosticError::InvalidKey(key.to_owned())); + } + let value = normalize_diagnostic_value(&value.into()); + self.fields.push((key.to_owned(), value)); + Ok(self) + } + + /// Renders the bounded payload. + /// + /// The result is never longer than [`MAX_DIAGNOSTIC_PAYLOAD_BYTES`]. When + /// the fields do not fit, values are shortened in insertion order: the + /// first value that does not fit is cut on a UTF-8 character boundary and + /// gains [`DIAGNOSTIC_TRUNCATION_MARKER`], and the fields after it are + /// omitted. Insert the free-form `reason` last so that it absorbs the + /// overage and the structured keys survive intact. + pub fn build(&self) -> String { + let prefix = format!( + "{DIAGNOSTIC_PREFIX}{}{DIAGNOSTIC_SCHEMA_SUFFIX}", + self.class + ); + // The class is part of the prefix and of the key set, and it is drawn + // from a closed set, so it is never shortened. + let fixed = prefix.len() + 1 + "class=".len() + self.class.len(); + let mut budget = MAX_DIAGNOSTIC_PAYLOAD_BYTES.saturating_sub(fixed); + let mut rendered: Vec = Vec::with_capacity(self.fields.len()); + for (key, value) in &self.fields { + let overhead = 1 + key.len() + 1; + let available = budget.saturating_sub(overhead); + if value.len() <= available { + rendered.push(format!("{key}={value}")); + budget -= overhead + value.len(); + continue; + } + let marker = DIAGNOSTIC_TRUNCATION_MARKER; + if overhead + marker.len() > budget { + // Not even the marker fits: the field is omitted rather than + // pushed past the bound. + continue; + } + let keep = available - marker.len(); + rendered.push(format!("{key}={}{marker}", truncate_utf8(value, keep))); + budget -= overhead + keep + marker.len(); + } + let mut payload = prefix; + payload.push_str(" class="); + payload.push_str(&self.class); + for part in rendered { + payload.push(' '); + payload.push_str(&part); + } + payload + } + + /// Parses a payload back into its class and fields. + /// + /// This is the validator a consumer uses to decide whether a diagnostic it + /// received is well formed. It refuses a payload that does not match the + /// documented grammar, names a class outside the closed set, exceeds the + /// bound, or omits one of the required keys. + pub fn parse(payload: &str) -> Result { + if payload.len() > MAX_DIAGNOSTIC_PAYLOAD_BYTES { + return Err(DiagnosticError::TooLong { + max: MAX_DIAGNOSTIC_PAYLOAD_BYTES, + }); + } + let rest = payload + .strip_prefix(DIAGNOSTIC_PREFIX) + .ok_or(DiagnosticError::InvalidGrammar)?; + let (class, rest) = rest + .split_once(DIAGNOSTIC_SCHEMA_SUFFIX) + .ok_or(DiagnosticError::InvalidGrammar)?; + if !DIAGNOSTIC_CLASSES.contains(&class) { + return Err(DiagnosticError::UnknownClass(class.to_owned())); + } + let mut parsed = Self::new(class)?; + for token in rest.split_whitespace() { + let (key, value) = token + .split_once('=') + .ok_or(DiagnosticError::InvalidGrammar)?; + if key == "class" { + if value != class { + return Err(DiagnosticError::InvalidGrammar); + } + continue; + } + if !valid_diagnostic_key(key) { + return Err(DiagnosticError::InvalidKey(key.to_owned())); + } + parsed.fields.push((key.to_owned(), value.to_owned())); + } + // `class` is implied by the prefix; the other two are the minimum key + // set every diagnostic has to carry, so a payload without them is not + // a diagnostic this grammar can describe. + for required in ["requirement", "reason"] { + if !parsed.fields.iter().any(|(key, _)| key == required) { + return Err(DiagnosticError::InvalidGrammar); + } + } + Ok(parsed) + } +} + +/// A diagnostic key is a lowercase ASCII token. +fn valid_diagnostic_key(key: &str) -> bool { + !key.is_empty() + && key.len() <= MAX_DIAGNOSTIC_KEY_BYTES + && key + .bytes() + .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_') +} + +/// Normalises a diagnostic value to printable ASCII. +/// +/// The grammar separates fields with spaces, so a value that could contain a +/// space would make the payload ambiguous. Every character outside `!`..=`~` +/// becomes `_`, which keeps the value a single token without inventing an +/// escaping scheme a reader would have to know about. +fn normalize_diagnostic_value(value: &str) -> String { + value + .chars() + .map(|character| { + if ('!'..='~').contains(&character) { + character + } else { + '_' + } + }) + .collect() +} + +/// Cuts a string to at most `max_bytes`, on a UTF-8 character boundary. +fn truncate_utf8(value: &str, max_bytes: usize) -> &str { + if value.len() <= max_bytes { + return value; + } + let mut end = max_bytes; + while end > 0 && !value.is_char_boundary(end) { + end -= 1; + } + &value[..end] +} + #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum ValidationError { #[error("{field} must not be empty")] @@ -1630,6 +1891,84 @@ fn normalize_execution_spec(spec: &ExecutionSpec) -> ExecutionSpec { #[cfg(test)] mod tests { use super::*; + /// A diagnostic payload matches the documented grammar, carries the class + /// and the required keys, and round-trips through the parser. + #[test] + fn a_diagnostic_payload_matches_the_documented_grammar() { + let mut payload = DiagnosticPayload::new(DIAGNOSTIC_CLASS_ISOLATION_DEGRADED).unwrap(); + payload.set("requirement", "best_effort").unwrap(); + payload.set("profile", "workspace_rw").unwrap(); + payload + .set("reason", "sandbox helper trust check failed") + .unwrap(); + let built = payload.build(); + assert!(built.starts_with("eggwork.diagnostic.isolation.degraded.v1 ")); + assert!(built.contains(" class=isolation.degraded")); + assert!(built.contains(" requirement=best_effort")); + assert!(built.contains(" profile=workspace_rw")); + assert!(built.contains(" reason=sandbox_helper_trust_check_failed")); + assert!(built.len() <= MAX_DIAGNOSTIC_PAYLOAD_BYTES); + let parsed = DiagnosticPayload::parse(&built).unwrap(); + assert_eq!(parsed.class(), DIAGNOSTIC_CLASS_ISOLATION_DEGRADED); + } + /// The bound is enforced, and an over-long reason is truncated in a way a + /// reader can see rather than silently. + #[test] + fn an_over_long_diagnostic_reason_is_truncated_observably() { + let mut payload = DiagnosticPayload::new(DIAGNOSTIC_CLASS_RESOURCES_DEGRADED).unwrap(); + payload.set("requirement", "best_effort").unwrap(); + payload.set("dimension", "memory").unwrap(); + payload + .set("reason", "r".repeat(MAX_DIAGNOSTIC_PAYLOAD_BYTES * 2)) + .unwrap(); + let built = payload.build(); + assert!(built.len() <= MAX_DIAGNOSTIC_PAYLOAD_BYTES); + assert!(built.contains(DIAGNOSTIC_TRUNCATION_MARKER)); + // The structured keys survive the truncation; only the free-form + // reason is shortened. + assert!(built.contains(" requirement=best_effort")); + assert!(built.contains(" dimension=memory")); + let reason = built + .split_whitespace() + .find(|token| token.starts_with("reason=")) + .unwrap(); + assert!(reason.ends_with(DIAGNOSTIC_TRUNCATION_MARKER)); + } + /// A value that cannot be shortened without losing its meaning still + /// yields a bounded payload, and the bound holds for a multi-byte value. + #[test] + fn a_diagnostic_payload_stays_within_its_bound() { + let mut payload = DiagnosticPayload::new(DIAGNOSTIC_CLASS_ISOLATION_DEGRADED).unwrap(); + payload.set("requirement", "best_effort").unwrap(); + payload + .set("reason", "é".repeat(MAX_DIAGNOSTIC_PAYLOAD_BYTES)) + .unwrap(); + let built = payload.build(); + assert!(built.len() <= MAX_DIAGNOSTIC_PAYLOAD_BYTES); + assert!(built.contains(DIAGNOSTIC_TRUNCATION_MARKER)); + assert!(DiagnosticPayload::parse(&built).is_ok()); + } + /// The parser refuses what the grammar does not allow: an unknown class, a + /// malformed token, an over-long payload, and a missing required key. + #[test] + fn a_malformed_diagnostic_payload_is_refused() { + assert!(DiagnosticPayload::parse("eggwork.diagnostic.nope.v1 class=nope").is_err()); + assert!( + DiagnosticPayload::parse( + "eggwork.diagnostic.isolation.degraded.v1 class=isolation.degraded" + ) + .is_err() + ); + assert!(DiagnosticPayload::parse("not a diagnostic").is_err()); + assert!(DiagnosticPayload::parse(&"x".repeat(MAX_DIAGNOSTIC_PAYLOAD_BYTES + 1)).is_err()); + assert!( + DiagnosticPayload::parse( + "eggwork.diagnostic.isolation.degraded.v1 class=isolation.degraded requirement=best_effort" + ) + .is_err() + ); + assert!(DiagnosticPayload::new("isolation.degraded.other").is_err()); + } fn spec() -> ExecutionSpec { ExecutionSpec { schema_version: 1, diff --git a/crates/eggwork-runner/src/lib.rs b/crates/eggwork-runner/src/lib.rs index ac87ebb..4ecd365 100644 --- a/crates/eggwork-runner/src/lib.rs +++ b/crates/eggwork-runner/src/lib.rs @@ -51,19 +51,51 @@ pub struct ExecutionProvenance { pub generation: Option, } -/// A bounded output chunk. Consumers must treat bytes as arbitrary binary data. +/// A bounded output chunk, or a diagnostic about the execution's enforcement. +/// +/// Consumers must treat the bytes of `Stdout`/`Stderr` as arbitrary binary +/// data. +/// +/// `Diagnostic` is the only way a degradation reaches the caller, and it is +/// deliberately carried on the *same* channel as the target's output: the +/// server's forwarding loop drains one channel in order, so a diagnostic the +/// runner sends before it spawns the target is published before any output the +/// target produces. A diagnostic derived from the runner's result instead +/// would necessarily arrive after all target output, which is the gap this +/// carrier exists to close. #[derive(Clone, PartialEq, Eq)] -pub struct OutputChunk { - pub stderr: bool, - pub bytes: Vec, +pub enum OutputChunk { + /// Target standard output. + Stdout(Vec), + /// Target standard error. + Stderr(Vec), + /// A bounded diagnostic payload about the execution's isolation or + /// resource enforcement. See [`eggwork_core::DiagnosticPayload`] for the + /// grammar and the bound. + Diagnostic(String), } impl std::fmt::Debug for OutputChunk { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.debug_struct("OutputChunk") - .field("stderr", &self.stderr) - .field("length", &self.bytes.len()) - .field("bytes", &"[REDACTED]") - .finish() + match self { + Self::Stdout(bytes) => f + .debug_struct("OutputChunk") + .field("stream", &"stdout") + .field("length", &bytes.len()) + .field("bytes", &"[REDACTED]") + .finish(), + Self::Stderr(bytes) => f + .debug_struct("OutputChunk") + .field("stream", &"stderr") + .field("length", &bytes.len()) + .field("bytes", &"[REDACTED]") + .finish(), + Self::Diagnostic(payload) => f + .debug_struct("OutputChunk") + .field("stream", &"diagnostic") + .field("length", &payload.len()) + .field("payload", &"[REDACTED]") + .finish(), + } } } @@ -821,6 +853,161 @@ impl ExecutionSetup for NoExecutionSetup { } } +/// The `requirement` value a degradation diagnostic always carries. +/// +/// A degradation is by definition a *best-effort* request that was not +/// honoured: a required request is refused instead, and a refusal is not a +/// degradation. +const DIAGNOSTIC_REQUIREMENT_BEST_EFFORT: &str = "best_effort"; + +/// The degradations the runner has already reported to the caller. +/// +/// The bookkeeping exists so that one degraded dimension produces exactly one +/// diagnostic event. A degradation can be discovered more than once — a +/// sandbox that `prepare` could not apply may also be the sandbox the helper +/// handshake could not enforce — and the second discovery must refine the +/// recorded outcome, not duplicate the event. +#[derive(Debug, Default)] +struct ReportedDegradations { + isolation: bool, + resources: Vec, +} + +/// The best-effort resource dimensions a request asked for. +/// +/// `Required` dimensions are excluded on purpose. A required dimension that +/// reached a `NotApplied` outcome would be a failure of the fail-closed rule, +/// not a degradation, and reporting it as one would turn a refusal into an +/// advisory. The in-tree setups refuse a required request before they can +/// produce such an outcome, so this filter never drops a real report. +fn best_effort_resource_dimensions( + request: &ResourceSetupRequest, +) -> Vec { + let mut dimensions = Vec::new(); + if matches!(request.memory_bytes, Requirement::BestEffort(_)) { + dimensions.push(eggwork_core::ResourceDimension::Memory); + } + if matches!(request.cpu_millis, Requirement::BestEffort(_)) { + dimensions.push(eggwork_core::ResourceDimension::Cpu); + } + if matches!(request.pids, Requirement::BestEffort(_)) { + dimensions.push(eggwork_core::ResourceDimension::Pids); + } + dimensions +} + +/// The wire name of a resource dimension, as the diagnostic grammar spells it. +fn resource_dimension_name(dimension: eggwork_core::ResourceDimension) -> &'static str { + match dimension { + eggwork_core::ResourceDimension::Memory => "memory", + eggwork_core::ResourceDimension::Cpu => "cpu", + eggwork_core::ResourceDimension::Pids => "pids", + } +} + +/// The requested dimensions whose post-mortem counter the helper could not +/// open. +/// +/// Only the dimensions the helper actually reported as unobservable are named: +/// the diagnostic has to say which limit could not be *verified*, not merely +/// that the resource outcome was downgraded. +#[cfg(target_os = "linux")] +fn unobserved_resource_dimensions( + request: &ResourceSetupRequest, + unobserved: &[eggwork_core::ResourceDimension], +) -> Vec { + let mut dimensions = Vec::new(); + if matches!(request.memory_bytes, Requirement::BestEffort(_)) + && unobserved.contains(&eggwork_core::ResourceDimension::Memory) + { + dimensions.push(eggwork_core::ResourceDimension::Memory); + } + if matches!(request.pids, Requirement::BestEffort(_)) + && unobserved.contains(&eggwork_core::ResourceDimension::Pids) + { + dimensions.push(eggwork_core::ResourceDimension::Pids); + } + dimensions +} + +/// Builds the diagnostic payload for a degraded filesystem isolation. +/// +/// The structured keys come first and the free-form reason last, so a reason +/// that does not fit absorbs the truncation and the structured keys survive +/// intact. +fn isolation_diagnostic(profile: &str, reason: &str) -> Option { + let mut payload = + eggwork_core::DiagnosticPayload::new(eggwork_core::DIAGNOSTIC_CLASS_ISOLATION_DEGRADED) + .ok()?; + let _ = payload.set("requirement", DIAGNOSTIC_REQUIREMENT_BEST_EFFORT); + let _ = payload.set("profile", profile); + let _ = payload.set("reason", reason); + Some(payload.build()) +} + +/// Builds the diagnostic payload for a degraded resource dimension. +fn resources_diagnostic( + dimension: eggwork_core::ResourceDimension, + reason: &str, +) -> Option { + let mut payload = + eggwork_core::DiagnosticPayload::new(eggwork_core::DIAGNOSTIC_CLASS_RESOURCES_DEGRADED) + .ok()?; + let _ = payload.set("requirement", DIAGNOSTIC_REQUIREMENT_BEST_EFFORT); + let _ = payload.set("dimension", resource_dimension_name(dimension)); + let _ = payload.set("reason", reason); + Some(payload.build()) +} + +/// Sends one diagnostic payload on the runner's output channel. +/// +/// The channel is the only path from the runner to the caller that preserves +/// ordering: the server drains it in order, so a payload sent before the +/// target is spawned is published before anything the target writes. +async fn send_diagnostic(output_tx: &mpsc::Sender, payload: Option) { + let Some(payload) = payload else { + // The payload could not be built, which can only mean the class is not + // in the closed set. There is no grammar-conforming payload to send, + // and a malformed one would be worse than none: the degradation stays + // recorded in the terminal snapshot. + return; + }; + // `send` rather than `try_send`: a dropped diagnostic would silently + // reopen the gap this milestone closes, and the channel is bounded, so + // awaiting it costs back-pressure and not correctness. + let _ = output_tx.send(OutputChunk::Diagnostic(payload)).await; +} + +/// Emits the diagnostic events for the degradations `setup` records. +/// +/// Only degradations of *best-effort* requests are reported: a required +/// request that could not be satisfied is refused before the target starts +/// and is never described as a degradation. +async fn report_setup_degradations( + output_tx: &mpsc::Sender, + sandbox_request: &SandboxRequest, + resource_request: &ResourceSetupRequest, + setup: &SetupOutcome, + reported: &mut ReportedDegradations, +) { + if !reported.isolation + && let SandboxOutcome::NotApplied { reason } = &setup.sandbox + && let SandboxRequest::BestEffort { profile } = sandbox_request + { + reported.isolation = true; + send_diagnostic(output_tx, isolation_diagnostic(profile, reason)).await; + } + if let ResourceSetupOutcome::NotApplied { reason } = &setup.resources { + for dimension in best_effort_resource_dimensions(resource_request) { + if reported.resources.contains(&dimension) { + continue; + } + reported.resources.push(dimension); + send_diagnostic(output_tx, resources_diagnostic(dimension, reason)).await; + } + } +} + #[derive(Clone)] pub struct RunnerRequest { argv: Vec, @@ -1304,6 +1491,21 @@ impl LocalProcessRunner { .setup .prepare(&request.sandbox, &request.resources, &request.root) .await?; + // The degradations `prepare` decided are known before any process + // exists, so their diagnostics are emitted here — before the target is + // spawned, and therefore before the target can produce any output. A + // diagnostic the server derived from the runner's result instead would + // necessarily arrive after all target output, which is the gap this + // emission point exists to close. + let mut reported_degradations = ReportedDegradations::default(); + report_setup_degradations( + &output_tx, + &request.sandbox, + &request.resources, + &setup, + &mut reported_degradations, + ) + .await; #[cfg(target_os = "linux")] let use_helper = ((!matches!(request.sandbox, SandboxRequest::None) && matches!(setup.sandbox, SandboxOutcome::Applied { .. })) @@ -1332,6 +1534,17 @@ impl LocalProcessRunner { reason: error.to_string(), }; } + // The helper could not even be launched, so the target is + // about to run without the requested enforcement. The + // diagnostic is emitted here, before the target exists. + report_setup_degradations( + &output_tx, + &request.sandbox, + &request.resources, + &setup, + &mut reported_degradations, + ) + .await; None } Err(error) => return Err(error), @@ -1384,6 +1597,19 @@ impl LocalProcessRunner { reason: "resource helper could not verify the cgroup limits".into(), }; } + // The handshake failure is classified and the outcomes are + // rewritten, and only now is the degradation reported: the + // target is about to be re-spawned directly, with no + // Landlock ruleset and no cgroup verification, so the + // caller has to learn that before the target runs. + report_setup_degradations( + &output_tx, + &request.sandbox, + &request.resources, + &setup, + &mut reported_degradations, + ) + .await; let direct = direct_command(&request, cwd.clone()); let (direct, unit) = wrap_resource_command(direct, &request.resources, &setup.resources)?; @@ -1412,6 +1638,17 @@ impl LocalProcessRunner { reason: error.to_string(), }; } + // Same rule as the `Ok(None)` arm above: the degradation is + // reported after the handshake failure is classified and + // before the target is re-spawned directly. + report_setup_degradations( + &output_tx, + &request.sandbox, + &request.resources, + &setup, + &mut reported_degradations, + ) + .await; let direct = direct_command(&request, cwd.clone()); let (direct, unit) = wrap_resource_command(direct, &request.resources, &setup.resources)?; @@ -1450,6 +1687,13 @@ impl LocalProcessRunner { let stderr = tree .take_stderr() .ok_or_else(|| RunnerError::Io("stderr pipe missing".into()))?; + // A post-mortem resource observation is only knowable after the target + // exited, so the diagnostic that reports it needs a sender of its own: + // `output_tx` is moved into the readers below. The clone is dropped + // again as soon as the observation has been reported, so the output + // channel still closes exactly when the readers finish. + #[cfg(target_os = "linux")] + let diagnostic_tx = output_tx.clone(); let stdout_task = spawn_reader( stdout, false, @@ -1528,22 +1772,40 @@ impl LocalProcessRunner { // post-mortem counter the helper could not open, is not evidence that // the limit held. Record `NotApplied` rather than letting it fall // through as `Applied`. - if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { - let requested = &request.resources; - let unobserved = if matches!(requested.memory_bytes, Requirement::NotRequested) { - false - } else { - resource_unobserved.contains(&eggwork_core::ResourceDimension::Memory) - } || if matches!(requested.pids, Requirement::NotRequested) { - false - } else { - resource_unobserved.contains(&eggwork_core::ResourceDimension::Pids) - }; - if unobserved { - setup.resources = ResourceSetupOutcome::NotApplied { - reason: "installed resource limits could not be observed after exit".into(), + { + if matches!(setup.resources, ResourceSetupOutcome::Applied { .. }) { + let requested = &request.resources; + let unobserved = if matches!(requested.memory_bytes, Requirement::NotRequested) { + false + } else { + resource_unobserved.contains(&eggwork_core::ResourceDimension::Memory) + } || if matches!(requested.pids, Requirement::NotRequested) { + false + } else { + resource_unobserved.contains(&eggwork_core::ResourceDimension::Pids) }; + if unobserved { + let reason = "installed resource limits could not be observed after exit"; + setup.resources = ResourceSetupOutcome::NotApplied { + reason: reason.into(), + }; + // This degradation is a post-mortem fact: the helper + // reports the unobservable counter only after the target + // exited, so the diagnostic cannot precede the target's + // output the way a setup-time degradation does. It still + // precedes the terminal event, because the server drains + // the output channel before it publishes the terminal + // state. + for dimension in unobserved_resource_dimensions(requested, &resource_unobserved) + { + send_diagnostic(&diagnostic_tx, resources_diagnostic(dimension, reason)) + .await; + } + } } + // The sender is released here, so the output channel keeps closing + // exactly when the readers finish. + drop(diagnostic_tx); } #[cfg(target_os = "linux")] let resource_cleanup_warning = if let Some(unit) = resource_unit.as_deref() { @@ -2044,13 +2306,12 @@ fn spawn_reader( let _ = overflow_tx.send(true); } for bytes in buffer[..count].chunks(chunk_limit) { - if output_tx - .try_send(OutputChunk { - stderr, - bytes: bytes.to_vec(), - }) - .is_err() - { + let chunk = if stderr { + OutputChunk::Stderr(bytes.to_vec()) + } else { + OutputChunk::Stdout(bytes.to_vec()) + }; + if output_tx.try_send(chunk).is_err() { dropped += bytes.len() as u64; } } diff --git a/crates/eggwork-runner/tests/diagnostic_degradation.rs b/crates/eggwork-runner/tests/diagnostic_degradation.rs new file mode 100644 index 0000000..89d33a3 --- /dev/null +++ b/crates/eggwork-runner/tests/diagnostic_degradation.rs @@ -0,0 +1,325 @@ +//! A degraded best-effort execution has to say so *while it runs*, not only in +//! the terminal result. +//! +//! The runner is the only party that knows why an enforcement was not applied, +//! and the output channel is the only carrier that preserves ordering between +//! the runner's knowledge and the target's output. These tests pin that +//! ordering at the layer where it is decided: the diagnostic chunk has to be +//! sent before the target produces a single byte, and it has to be sent at all +//! exactly when something was degraded. +//! +//! `NoExecutionSetup` is used explicitly rather than `LocalProcessRunner::default`: +//! the default picks a setup from the environment, so a test that wanted "no +//! enforcement available" could silently get an enforcing one. +//! +//! The argv is platform specific because the runner has platform-specific spawn +//! paths and the diagnostic sits in front of all of them: the Windows CI job +//! runs this suite, and `/bin/sh` does not exist there. + +use eggwork_core::Requirement; +use eggwork_runner::{ + LocalProcessRunner, NoExecutionSetup, OutputChunk, ResourceSetupRequest, RunnerError, + RunnerRequest, SandboxRequest, +}; +use std::path::Path; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +/// A command that writes one line to stdout. +fn echo_argv(text: &str) -> Vec { + if cfg!(windows) { + vec![comspec(), "/C".to_owned(), format!("echo {text}")] + } else { + vec![ + "/bin/sh".to_owned(), + "-c".to_owned(), + format!("echo {text}"), + ] + } +} + +/// A command that creates a marker file and nothing else. +fn touch_argv(marker: &Path) -> Vec { + if cfg!(windows) { + vec![ + comspec(), + "/C".to_owned(), + format!("type nul > \"{}\"", marker.display()), + ] + } else { + vec![ + "/bin/sh".to_owned(), + "-c".to_owned(), + format!("touch {}", marker.display()), + ] + } +} + +/// The command interpreter Windows actually uses. +/// +/// It is resolved from the environment rather than hard-coded, because the +/// Windows path spawns through a Job Object and the target has to be a real +/// Windows program. +fn comspec() -> String { + std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_owned()) +} + +/// Collects every chunk the runner sent, in the order it sent them. +async fn drain(mut rx: mpsc::Receiver) -> Vec { + let mut chunks = Vec::new(); + while let Some(chunk) = rx.recv().await { + chunks.push(chunk); + } + chunks +} + +/// The diagnostics among the collected chunks, in order. +fn diagnostics(chunks: &[OutputChunk]) -> Vec<&str> { + chunks + .iter() + .filter_map(|chunk| match chunk { + OutputChunk::Diagnostic(payload) => Some(payload.as_str()), + _ => None, + }) + .collect() +} + +/// The index of the first target output chunk. +fn first_target_output_index(chunks: &[OutputChunk]) -> Option { + chunks + .iter() + .position(|chunk| matches!(chunk, OutputChunk::Stdout(_) | OutputChunk::Stderr(_))) +} + +/// A best-effort sandbox request that cannot be honoured emits exactly one +/// diagnostic, and it is emitted before the target writes anything. +#[tokio::test] +async fn a_degraded_best_effort_sandbox_is_reported_before_the_target_output() { + let root = tempfile::tempdir().expect("temp dir"); + let runner = LocalProcessRunner::new(NoExecutionSetup); + let mut request = RunnerRequest::new(echo_argv("target-output"), root.path()); + request.set_sandbox_request(SandboxRequest::BestEffort { + profile: "workspace_rw".into(), + }); + + let (tx, rx) = mpsc::channel(32); + let result = runner + .run(request, CancellationToken::new(), tx) + .await + .expect("the target itself runs"); + let chunks = drain(rx).await; + + let reported = diagnostics(&chunks); + assert_eq!( + reported.len(), + 1, + "one degraded dimension produces exactly one diagnostic; got {reported:?}" + ); + let payload = reported[0]; + assert!( + payload.starts_with("eggwork.diagnostic.isolation.degraded.v1 "), + "unexpected diagnostic payload: {payload}" + ); + assert!(payload.contains(" requirement=best_effort")); + assert!(payload.contains(" profile=workspace_rw")); + assert!(payload.contains(" reason=")); + assert!( + eggwork_core::DiagnosticPayload::parse(payload).is_ok(), + "the payload must match the documented grammar: {payload}" + ); + + // The ordering guarantee: the diagnostic precedes every target output. + let first_output = first_target_output_index(&chunks).expect("the target produced output"); + assert_eq!( + first_output, 1, + "the diagnostic has to precede the target's first output; got {chunks:?}" + ); + assert!( + matches!(chunks.first(), Some(OutputChunk::Diagnostic(_))), + "the diagnostic has to be the first chunk on the channel; got {chunks:?}" + ); + + // And the terminal result still records the degradation, so the stream and + // the snapshot cannot disagree. + let execution = result.execution_result(); + assert!(matches!( + execution.sandbox, + Some(eggwork_core::SandboxResult::NotApplied { .. }) + )); +} + +/// A resource degradation names the affected dimension. +#[tokio::test] +async fn a_degraded_best_effort_resource_request_is_reported_per_dimension() { + let root = tempfile::tempdir().expect("temp dir"); + let runner = LocalProcessRunner::new(NoExecutionSetup); + let mut request = RunnerRequest::new(echo_argv("done"), root.path()); + request.set_resource_setup_request(ResourceSetupRequest { + memory_bytes: Requirement::BestEffort(64 * 1024 * 1024), + cpu_millis: Requirement::NotRequested, + pids: Requirement::NotRequested, + }); + + let (tx, rx) = mpsc::channel(32); + runner + .run(request, CancellationToken::new(), tx) + .await + .expect("the target itself runs"); + let chunks = drain(rx).await; + + let reported = diagnostics(&chunks); + assert_eq!( + reported.len(), + 1, + "only the requested dimension is affected; got {reported:?}" + ); + assert!(reported[0].starts_with("eggwork.diagnostic.resources.degraded.v1 ")); + assert!(reported[0].contains(" dimension=memory")); + assert!(reported[0].contains(" requirement=best_effort")); +} + +/// Two affected dimensions produce two diagnostics, one per dimension. +#[tokio::test] +async fn two_affected_resource_dimensions_produce_one_diagnostic_each() { + let root = tempfile::tempdir().expect("temp dir"); + let runner = LocalProcessRunner::new(NoExecutionSetup); + let mut request = RunnerRequest::new(echo_argv("done"), root.path()); + request.set_resource_setup_request(ResourceSetupRequest { + memory_bytes: Requirement::BestEffort(64 * 1024 * 1024), + cpu_millis: Requirement::BestEffort(1000), + pids: Requirement::NotRequested, + }); + + let (tx, rx) = mpsc::channel(32); + runner + .run(request, CancellationToken::new(), tx) + .await + .expect("the target itself runs"); + let chunks = drain(rx).await; + + let reported = diagnostics(&chunks); + assert_eq!(reported.len(), 2, "got {reported:?}"); + assert!( + reported + .iter() + .any(|payload| payload.contains(" dimension=memory")) + ); + assert!( + reported + .iter() + .any(|payload| payload.contains(" dimension=cpu")) + ); + assert!( + reported + .iter() + .all(|payload| !payload.contains(" dimension=pids")), + "a dimension that was not requested is not affected; got {reported:?}" + ); +} + +/// A required request is refused, not degraded: the target never runs and no +/// diagnostic is emitted. +#[tokio::test] +async fn a_required_sandbox_is_refused_without_a_degradation_diagnostic() { + let root = tempfile::tempdir().expect("temp dir"); + let marker = root.path().join("marker"); + let runner = LocalProcessRunner::new(NoExecutionSetup); + let mut request = RunnerRequest::new(touch_argv(&marker), root.path()); + request.set_sandbox_request(SandboxRequest::Required { + profile: "workspace_rw".into(), + }); + + let (tx, rx) = mpsc::channel(32); + let error = runner + .run(request, CancellationToken::new(), tx) + .await + .expect_err("a required sandbox must fail closed"); + assert!( + matches!(error, RunnerError::RequiredSetupUnavailable), + "unexpected error: {error:?}" + ); + assert!( + !marker.exists(), + "the target must not have run for a refused required request" + ); + let chunks = drain(rx).await; + assert!( + diagnostics(&chunks).is_empty(), + "a refusal is not a degradation; got {:?}", + diagnostics(&chunks) + ); +} + +/// Nothing degraded means nothing reported. +#[tokio::test] +async fn an_execution_with_nothing_degraded_emits_no_diagnostic() { + let root = tempfile::tempdir().expect("temp dir"); + let runner = LocalProcessRunner::new(NoExecutionSetup); + let request = RunnerRequest::new(echo_argv("quiet"), root.path()); + + let (tx, rx) = mpsc::channel(32); + runner + .run(request, CancellationToken::new(), tx) + .await + .expect("the target itself runs"); + let chunks = drain(rx).await; + assert!( + diagnostics(&chunks).is_empty(), + "an execution with no degradation must emit no diagnostic; got {:?}", + diagnostics(&chunks) + ); +} + +/// A cancellation before the spawn is not a degradation either. +#[tokio::test] +async fn an_execution_cancelled_before_spawn_emits_no_diagnostic() { + let root = tempfile::tempdir().expect("temp dir"); + let runner = LocalProcessRunner::new(NoExecutionSetup); + let mut request = RunnerRequest::new(echo_argv("never"), root.path()); + request.set_sandbox_request(SandboxRequest::BestEffort { + profile: "workspace_rw".into(), + }); + + let cancellation = CancellationToken::new(); + cancellation.cancel(); + let (tx, rx) = mpsc::channel(32); + let error = runner + .run(request, cancellation, tx) + .await + .expect_err("a cancelled execution does not run"); + assert!( + matches!(error, RunnerError::CancelledBeforeSpawn), + "unexpected error: {error:?}" + ); + let chunks = drain(rx).await; + assert!( + diagnostics(&chunks).is_empty(), + "a cancellation is not a degradation; got {:?}", + diagnostics(&chunks) + ); +} + +/// The diagnostic payload stays inside the bound the grammar documents. +#[tokio::test] +async fn a_diagnostic_payload_is_bounded() { + let root = tempfile::tempdir().expect("temp dir"); + let runner = LocalProcessRunner::new(NoExecutionSetup); + let mut request = RunnerRequest::new(echo_argv("bounded"), root.path()); + request.set_sandbox_request(SandboxRequest::BestEffort { + profile: "workspace_rw".into(), + }); + + let (tx, rx) = mpsc::channel(32); + runner + .run(request, CancellationToken::new(), tx) + .await + .expect("the target itself runs"); + let chunks = drain(rx).await; + for payload in diagnostics(&chunks) { + assert!( + payload.len() <= eggwork_core::MAX_DIAGNOSTIC_PAYLOAD_BYTES, + "the diagnostic payload must stay within its bound; got {} bytes", + payload.len() + ); + } +} diff --git a/crates/eggwork-server/src/lib.rs b/crates/eggwork-server/src/lib.rs index 7f9badd..0e8974f 100644 --- a/crates/eggwork-server/src/lib.rs +++ b/crates/eggwork-server/src/lib.rs @@ -26,8 +26,8 @@ use eggwork_core::{ ProtocolVersionRange, }; use eggwork_runner::{ - ExecutionProvenance, LocalProcessRunner, ResourceSetupRequest, RunnerError, RunnerRequest, - SandboxRequest, + ExecutionProvenance, LocalProcessRunner, OutputChunk, ResourceSetupRequest, RunnerError, + RunnerRequest, SandboxRequest, }; use futures_util::stream; use serde::{Deserialize, Serialize}; @@ -2471,11 +2471,23 @@ async fn run_execution( biased; output = output_rx.recv(), if !output_closed => { if let Some(output) = output { - let kind = if output.stderr { ExecutionEventKind::Stderr(output.bytes) } else { ExecutionEventKind::Stdout(output.bytes) }; + // A diagnostic rides the same channel as the target's + // output and is forwarded in the order it was received, so + // a degradation the runner reported before it spawned the + // target is published before anything the target wrote. + let kind = match output { + OutputChunk::Stdout(bytes) => ExecutionEventKind::Stdout(bytes), + OutputChunk::Stderr(bytes) => ExecutionEventKind::Stderr(bytes), + OutputChunk::Diagnostic(payload) => ExecutionEventKind::Diagnostic(payload), + }; publish(&record, ExecutionState::Running, None, kind).await; } else { output_closed = true; - if result.is_some() { break; } + // The channel is closed and drained, so no further output + // can arrive. The runner's outcome may still be unknown, in + // which case the `joined` branch below is still enabled and + // the loop waits for it. + if result.is_some() || runner_error.is_some() { break; } } } joined = &mut runner_task, if result.is_none() && runner_error.is_none() => { @@ -2489,10 +2501,10 @@ async fn run_execution( } } while let Ok(output) = output_rx.try_recv() { - let kind = if output.stderr { - ExecutionEventKind::Stderr(output.bytes) - } else { - ExecutionEventKind::Stdout(output.bytes) + let kind = match output { + OutputChunk::Stdout(bytes) => ExecutionEventKind::Stdout(bytes), + OutputChunk::Stderr(bytes) => ExecutionEventKind::Stderr(bytes), + OutputChunk::Diagnostic(payload) => ExecutionEventKind::Diagnostic(payload), }; publish(&record, ExecutionState::Running, None, kind).await; } @@ -5286,6 +5298,356 @@ mod tests { server.wait().await.unwrap(); } + /// A setup that advertises the Landlock capability but cannot enforce it. + /// + /// The admission gate refuses a `Required` isolation request on a node that + /// does not advertise the capability, so the runner's own fail-closed + /// refusal would be unreachable from a server test without this fixture. + /// The fixture is deliberately inconsistent — it advertises what it cannot + /// deliver — and exists only to reach that refusal. + struct AdvertisesLandlockButCannotEnforce; + + #[async_trait::async_trait] + impl eggwork_runner::ExecutionSetup for AdvertisesLandlockButCannotEnforce { + async fn prepare( + &self, + sandbox: &SandboxRequest, + resources: &ResourceSetupRequest, + root: &std::path::Path, + ) -> Result { + eggwork_runner::ExecutionSetup::prepare( + &eggwork_runner::NoExecutionSetup, + sandbox, + resources, + root, + ) + .await + } + + async fn execution_capabilities(&self) -> Vec { + vec![eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY.to_owned()] + } + } + + /// Starts a node with the given runner and returns it with a connected + /// client. The runner is injected explicitly so a test can pin what the + /// node is able to enforce. + async fn node_with_runner( + runner: Arc, + node_id: &str, + temp: &TempDir, + ) -> (NodeServer, NodeClient) { + let (root, server_identity, client_identity, _) = tls_material(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let principal = eggwork_core::PrincipalId::new("controller-a").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + principal, + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: None, + node_id: NodeId::new(node_id).unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024, + max_active_executions: 1, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + runner, + resolver, + Arc::new(|_: &NodePrincipal, _| true), + ) + .await + .unwrap(); + let client_temp = TempDir::new().unwrap(); + let client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + (server, client) + } + + /// The sequence number of the terminal state event. + fn terminal_sequence(events: &[eggwork_core::ExecutionEvent]) -> EventSequence { + events + .iter() + .rev() + .find_map(|event| match &event.kind { + ExecutionEventKind::State(state) if *state != ExecutionState::Running => { + Some(event.sequence) + } + _ => None, + }) + .expect("the execution must reach a terminal state") + } + + /// The diagnostic events of a page, in order. + fn diagnostic_payloads(events: &[eggwork_core::ExecutionEvent]) -> Vec<&str> { + events + .iter() + .filter_map(|event| match &event.kind { + ExecutionEventKind::Diagnostic(payload) => Some(payload.as_str()), + _ => None, + }) + .collect() + } + + /// M005a: a degraded best-effort execution says so in the stream, before + /// the target writes anything and before the terminal event. The terminal + /// state alone is not enough — a caller watching the stream has to be able + /// to see that the execution ran without the enforcement it asked for. + #[tokio::test] + async fn a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal() + { + init_tls(); + let temp = TempDir::new().unwrap(); + // `NoExecutionSetup` is chosen explicitly: the default setup depends on + // the environment, and this test needs a node that cannot enforce + // anything. + let runner = Arc::new(LocalProcessRunner::new(eggwork_runner::NoExecutionSetup)); + let (server, client) = node_with_runner(runner, "node-degraded-best-effort", &temp).await; + + let mut spec = execution_spec(vec![ + "/bin/sh".into(), + "-c".into(), + "echo target-output".into(), + ]); + spec.command.isolation = IsolationRequirement::BestEffort; + let handle = execution_handle("degraded-best-effort"); + let stream = client.execute(&spec, &handle).await.unwrap(); + let events = tokio::time::timeout( + ROUND_TRIP_BUDGET, + stream.into_events().try_collect::>(), + ) + .await + .expect("best-effort execution must terminate") + .unwrap(); + + let payloads = diagnostic_payloads(&events); + assert_eq!( + payloads.len(), + 1, + "one degraded dimension produces exactly one diagnostic; got {payloads:?}" + ); + let payload = payloads[0]; + assert!( + payload.starts_with("eggwork.diagnostic.isolation.degraded.v1 "), + "unexpected diagnostic payload: {payload}" + ); + assert!(payload.contains(" requirement=best_effort")); + assert!(payload.contains(" reason=")); + assert!( + eggwork_core::DiagnosticPayload::parse(payload).is_ok(), + "the payload must match the documented grammar: {payload}" + ); + + let diagnostic_sequence = events + .iter() + .find(|event| matches!(event.kind, ExecutionEventKind::Diagnostic(_))) + .expect("a diagnostic event") + .sequence; + let first_output_sequence = events + .iter() + .find(|event| { + matches!( + event.kind, + ExecutionEventKind::Stdout(_) | ExecutionEventKind::Stderr(_) + ) + }) + .expect("the target produced output") + .sequence; + assert!( + diagnostic_sequence < first_output_sequence, + "the diagnostic has to precede the target's first output; got {events:?}" + ); + let terminal = terminal_sequence(&events); + assert!( + diagnostic_sequence < terminal, + "the diagnostic has to precede the terminal event; got {events:?}" + ); + + // The terminal evidence still records the degradation, so the stream + // and the snapshot cannot disagree. + let snapshot = client + .observe_generation(&handle.execution_id, handle.generation.get()) + .await + .unwrap(); + assert!(matches!( + snapshot.result.unwrap().sandbox, + Some(eggwork_core::SandboxResult::NotApplied { .. }) + )); + server.shutdown().await; + server.wait().await.unwrap(); + } + + /// M005a: the diagnostic is durable. It is committed to the journal, so a + /// later read of the event page replays it — it was not merely broadcast to + /// a live subscriber. + #[tokio::test] + async fn the_diagnostic_is_replayed_from_the_journal_after_the_execution_ended() { + init_tls(); + let temp = TempDir::new().unwrap(); + let runner = Arc::new(LocalProcessRunner::new(eggwork_runner::NoExecutionSetup)); + let (server, client) = node_with_runner(runner, "node-diagnostic-replay", &temp).await; + + let mut spec = execution_spec(vec!["/bin/true".into()]); + spec.command.isolation = IsolationRequirement::BestEffort; + let handle = execution_handle("diagnostic-replay"); + let stream = client.execute(&spec, &handle).await.unwrap(); + let events = tokio::time::timeout( + ROUND_TRIP_BUDGET, + stream.into_events().try_collect::>(), + ) + .await + .expect("best-effort execution must terminate") + .unwrap(); + let payloads = diagnostic_payloads(&events); + assert_eq!(payloads.len(), 1, "got {payloads:?}"); + + // The execution is over; a fresh read of the event page has to carry + // the diagnostic. + let page = client.events(&handle, 0).await.unwrap(); + let bytes = tokio::time::timeout(ROUND_TRIP_BUDGET, page.try_collect::>()) + .await + .expect("the event page must terminate") + .unwrap(); + let page = bytes + .iter() + .flat_map(|chunk| chunk.to_vec()) + .collect::>(); + let page = String::from_utf8_lossy(&page); + assert!( + page.contains(payloads[0]), + "the replayed page must carry the committed diagnostic; got {page}" + ); + server.shutdown().await; + server.wait().await.unwrap(); + } + + /// M005a: a required request is refused, not degraded. The target never + /// runs, and the refusal is never dressed up as a degradation. + #[tokio::test] + async fn a_required_sandbox_never_reaches_the_target_and_is_not_reported_as_a_degradation() { + init_tls(); + let temp = TempDir::new().unwrap(); + let marker = temp.path().join("marker"); + let runner = Arc::new(LocalProcessRunner::new(AdvertisesLandlockButCannotEnforce)); + let (server, client) = node_with_runner(runner, "node-required-refusal", &temp).await; + + let mut spec = execution_spec(vec![ + "/bin/sh".into(), + "-c".into(), + format!("touch {}", marker.display()), + ]); + spec.command.isolation = IsolationRequirement::Required; + let handle = execution_handle("required-refusal"); + let stream = client.execute(&spec, &handle).await.unwrap(); + let events = tokio::time::timeout( + ROUND_TRIP_BUDGET, + stream.into_events().try_collect::>(), + ) + .await + .expect("the refused execution must terminate") + .unwrap(); + + // The observable side effect: the child never ran. + assert!( + !marker.exists(), + "the target must not have run for a refused required request" + ); + // The terminal classification is unchanged: a refusal is a failure with + // an internal cause, and the sandbox result says the requirement could + // not be met. + let snapshot = client + .observe_generation(&handle.execution_id, handle.generation.get()) + .await + .unwrap(); + assert_eq!(snapshot.state, ExecutionState::Failed); + let result = snapshot.result.unwrap(); + assert_eq!(result.failure, Some(ExecutionFailure::Internal)); + assert!(matches!( + result.sandbox, + Some(eggwork_core::SandboxResult::Failed { .. }) + )); + // And it is never reported as a degradation. + assert!( + diagnostic_payloads(&events).is_empty(), + "a refusal is not a degradation; got {:?}", + diagnostic_payloads(&events) + ); + server.shutdown().await; + server.wait().await.unwrap(); + } + + /// M005a: an execution with nothing degraded publishes no diagnostic. + #[tokio::test] + async fn an_execution_with_nothing_degraded_publishes_no_diagnostic() { + init_tls(); + let temp = TempDir::new().unwrap(); + let runner = Arc::new(LocalProcessRunner::new(eggwork_runner::NoExecutionSetup)); + let (server, client) = node_with_runner(runner, "node-nothing-degraded", &temp).await; + + let spec = execution_spec(vec!["/bin/true".into()]); + let handle = execution_handle("nothing-degraded"); + let stream = client.execute(&spec, &handle).await.unwrap(); + let events = tokio::time::timeout( + ROUND_TRIP_BUDGET, + stream.into_events().try_collect::>(), + ) + .await + .expect("the execution must terminate") + .unwrap(); + assert!( + diagnostic_payloads(&events).is_empty(), + "an execution with no degradation must publish no diagnostic; got {:?}", + diagnostic_payloads(&events) + ); + server.shutdown().await; + server.wait().await.unwrap(); + } + + /// M005a: a degraded best-effort resource request publishes a diagnostic + /// that names the affected dimension. + #[tokio::test] + async fn a_degraded_best_effort_resource_request_publishes_a_dimension_scoped_diagnostic() { + init_tls(); + let temp = TempDir::new().unwrap(); + let runner = Arc::new(LocalProcessRunner::new(eggwork_runner::NoExecutionSetup)); + let (server, client) = node_with_runner(runner, "node-degraded-resources", &temp).await; + + let mut spec = execution_spec(vec!["/bin/true".into()]); + spec.command.resources.memory_bytes = Requirement::BestEffort(64 * 1024 * 1024); + let handle = execution_handle("degraded-resources"); + let stream = client.execute(&spec, &handle).await.unwrap(); + let events = tokio::time::timeout( + ROUND_TRIP_BUDGET, + stream.into_events().try_collect::>(), + ) + .await + .expect("the execution must terminate") + .unwrap(); + + let payloads = diagnostic_payloads(&events); + assert_eq!(payloads.len(), 1, "got {payloads:?}"); + assert!( + payloads[0].starts_with("eggwork.diagnostic.resources.degraded.v1 "), + "unexpected diagnostic payload: {}", + payloads[0] + ); + assert!(payloads[0].contains(" dimension=memory")); + assert!(payloads[0].contains(" requirement=best_effort")); + server.shutdown().await; + server.wait().await.unwrap(); + } + #[tokio::test] async fn required_resource_admission_rejects_with_capability_mismatch_when_dimension_unavailable() { @@ -6315,11 +6677,10 @@ mod tests { Ok(_) => panic!("required isolation without a helper must be rejected"), } // Debug rendering of output and environment types redacts content. - let chunk = eggwork_runner::OutputChunk { - stderr: false, - bytes: sentinel.as_bytes().to_vec(), - }; + let chunk = eggwork_runner::OutputChunk::Stdout(sentinel.as_bytes().to_vec()); assert!(!format!("{chunk:?}").contains(sentinel)); + let diagnostic = eggwork_runner::OutputChunk::Diagnostic(sentinel.to_owned()); + assert!(!format!("{diagnostic:?}").contains(sentinel)); let entry = eggwork_core::EnvironmentEntry::new("DEPLOY_TOKEN", sentinel).unwrap(); assert!(!format!("{entry:?}").contains(sentinel)); server.shutdown().await; diff --git a/plans/closure/security-isolation-resource/005a-status.md b/plans/closure/security-isolation-resource/005a-status.md new file mode 100644 index 0000000..1036901 --- /dev/null +++ b/plans/closure/security-isolation-resource/005a-status.md @@ -0,0 +1,455 @@ +# Security M005a — Degraded-isolation observability corrective + +Status: implemented — closure record written, implementation commit pending + +Source implementation plan: +`plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md` + +Source corrective addendum (authoritative where it disagrees with the plan): +`plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` +(finding SI-1) + +Source roadmap: +`plans/subsystems/security-isolation-resource-roadmap.md` (M005a now +"implemented") + +Reviewed repository head before implementation: `778d83c` +Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` + +Branch: `corrective/interrogation-batch-2026-10`. The working tree was left +dirty for the coordinator to review and commit; no commit was made by the +implementing agent. + +## 1. Executive finding + +A degraded best-effort execution is now visible in the event stream *while it +is running*. The runner classifies the degradation at the moment it decides +not to enforce a request, and it publishes that classification on the output +channel it already owns — before the target process exists, and therefore +before the target can produce any output. The server forwards the chunk in +receipt order, so the diagnostic's event sequence number is strictly below the +first stdout/stderr event's and strictly below the terminal event's. + +The mechanism is the runner-side one the plan expected, and it is the only +mechanism that satisfies the ordering requirement in full: the server's +`run_execution` learns the outcome from `RunnerResult`, which arrives after +the execution has finished, so a server-side diagnostic derived from that +result would necessarily arrive after all target output — and, because +`publish` returns early on a terminal base state, would be *silently dropped* +if it were published after the terminal event. + +The `Required` path is untouched. A required request still fails closed before +the target starts, keeps its terminal classification, and is never described +as a degradation. + +## 2. The emission mechanism, and why + +**Chosen: the runner emits on its output channel; the server forwards.** + +`crates/eggwork-runner/src/lib.rs`'s public `OutputChunk` gained a +`Diagnostic(String)` variant and became an enum: + +```rust +pub enum OutputChunk { + Stdout(Vec), + Stderr(Vec), + Diagnostic(String), +} +``` + +`crates/eggwork-server/src/lib.rs`'s forwarding loop in `run_execution` maps +the chunk to `ExecutionEventKind::Diagnostic(payload)` and publishes it through +the existing `publish` funnel, with `ExecutionState::Running` as the proposed +state. + +**Why this and not the server-side alternative.** Three reasons, in order of +weight: + +1. **Ordering.** The server's `run_execution` learns the outcome only from + `RunnerResult`, which arrives after the execution has finished. A + diagnostic derived from it would land after every stdout/stderr event, and + the milestone's ordering property would be unsatisfiable. The plan's + §5.2 permits a server-side publication immediately before + `publish_terminal` only as a fallback. +2. **The post-terminal drop.** `publish` returns early when the recorded base + state is already terminal (`crates/eggwork-server/src/lib.rs`, `publish`), + and `store::ExecutionStore::commit_event` refuses to append to a terminal + execution. A diagnostic published after the terminal event is therefore + *silently dropped* — not rejected, not reported. Any mechanism whose + publication point can drift past the terminal event is unsafe by + construction. +3. **Knowledge.** The runner is the only party that knows *why* an + enforcement was not applied, and it knows it at the moment it decides not + to apply it. The runner does not reconstruct the diagnostic from the + terminal snapshot after the fact; the payload and the snapshot are derived + from the same `SetupOutcome`, so the two cannot disagree. + +**Compatibility consequence of the public API change.** `OutputChunk` is +public in a published crate (`eggwork-runner` 0.1.5). The struct +`OutputChunk { stderr: bool, bytes: Vec }` became the enum above, so +this is a **breaking source change** for any downstream code that constructs +or destructures `OutputChunk`. The in-tree blast radius was small: the only +two construction sites were the runner's own `spawn_reader` and one server +test helper, and both are in files this milestone owns. The release version +and release notes still have to carry this change; **the version bump is not +part of this milestone** (no `Cargo.toml` is in this milestone's ownership), +so the coordinator/release owner must fold the `OutputChunk` change into a +version-visible release rather than shipping it inside a +qualification-only candidate. See §9 finding S-03. + +**Client behaviour.** The repository's own client tolerates the new traffic: +`ExecutionStream::into_events` in `crates/eggwork-client/src/lib.rs` +deserializes every line into an `ExecutionEvent` and yields every event kind +unchanged, and `ExecutionEvent::validate` bounds the diagnostic payload by +`MAX_EVENT_CHUNK_BYTES` (64 KiB), which the 2048-byte payload is well inside. +This is confirmed by execution, not only by inspection: the server tests in +§4 observe the `Diagnostic` events through that exact client path. The +**external**-client consequence must be flagged: a client that treats an +unknown event kind as fatal would break on the newly-trafficked `Diagnostic` +variant. That is the intended correction — the variant already existed in the +wire contract — but it is a client-visible behaviour change. + +## 3. The diagnostic payload grammar as implemented + +Defined once in `crates/eggwork-core/src/lib.rs` (`eggwork-core` is the only +crate both the runner and the server depend on, so the grammar cannot drift +between producer and consumer). + +```text +eggwork.diagnostic..v1 key=value key=value … +``` + +| Element | Constant | Value | +| --- | --- | --- | +| prefix | `DIAGNOSTIC_PREFIX` | `eggwork.diagnostic.` | +| schema suffix | `DIAGNOSTIC_SCHEMA_SUFFIX` | `.v1` | +| class (isolation) | `DIAGNOSTIC_CLASS_ISOLATION_DEGRADED` | `isolation.degraded` | +| class (resources) | `DIAGNOSTIC_CLASS_RESOURCES_DEGRADED` | `resources.degraded` | +| closed class set | `DIAGNOSTIC_CLASSES` | the two classes above | +| bound | `MAX_DIAGNOSTIC_PAYLOAD_BYTES` | `MAX_METADATA_VALUE_BYTES` = 2048 | +| key bound | `MAX_DIAGNOSTIC_KEY_BYTES` | 32 | +| truncation marker | `DIAGNOSTIC_TRUNCATION_MARKER` | `...[truncated]` | + +**Key set.** `class` (always; it repeats the class so a consumer that only +reads key/value pairs does not have to parse the prefix), `requirement` +(always `best_effort`), `reason` (the bounded cause), `profile` +(`isolation.degraded` only), `dimension` (`resources.degraded` only: +`memory`, `cpu`, `pids`). + +**Value charset.** Values are normalised to printable ASCII: every character +outside `!`..=`~` — a space included — becomes `_`. The grammar separates +fields with spaces, so this keeps the tokenisation unambiguous without +inventing an escaping scheme a reader would have to know about. The reason +text is therefore mangled (spaces become underscores) in the diagnostic while +the terminal snapshot keeps the original sentence; the snapshot stays the +authoritative evidence. + +**Bound and truncation rule.** `DiagnosticPayload::build` never returns more +than `MAX_DIAGNOSTIC_PAYLOAD_BYTES`. When the fields do not fit, values are +shortened *in insertion order*: the first value that does not fit is cut on a +UTF-8 character boundary and gains the literal `...[truncated]` marker, and +the fields after it are omitted. The marker is what makes truncation +observable — a bounded payload never silently reads as a complete statement. +The runner inserts the structured keys first and the free-form `reason` last, +so the reason absorbs the overage and the structured keys survive intact. + +**Validator.** `DiagnosticPayload::parse` refuses a payload that does not +match the grammar, names a class outside the closed set, exceeds the bound, or +omits `requirement`/`reason`. + +No class constant beyond the two named by the coordinator was added. + +## 4. Requirement-to-evidence matrix + +Acceptance criteria are numbered as in the plan's §11. "Executed" means the +command was run in this working tree and produced the stated result; "inspected" +means the property was established by reading code and is not backed by a +command run here. + +| # | Criterion | Implementation site | Evidence | Status | +| --- | --- | --- | --- | --- | +| 1 | A best-effort request that could not be enforced produces a diagnostic event | `report_setup_degradations` in `crates/eggwork-runner/src/lib.rs`; forwarding in `run_execution` in `crates/eggwork-server/src/lib.rs` | Executed: `cargo test -p eggwork-server --lib a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal` — passed; `cargo test -p eggwork-runner --test diagnostic_degradation` — 7 passed | Pass | +| 2 | The diagnostic's sequence number is strictly less than the terminal event's | same | Executed: the same server test asserts `diagnostic_sequence < terminal_sequence` | Pass | +| 3 | The diagnostic's sequence number is strictly less than the first stdout/stderr event's | same | Executed: the same server test asserts `diagnostic_sequence < first_output_sequence` against a target that writes to stdout; runner-side `a_degraded_best_effort_sandbox_is_reported_before_the_target_output` asserts the diagnostic is the first chunk on the channel | Pass | +| 4 | The payload matches the grammar, names the class, is at most `MAX_METADATA_VALUE_BYTES` | `eggwork_core::DiagnosticPayload` in `crates/eggwork-core/src/lib.rs` | Executed: `cargo test -p eggwork-core --lib` — 32 passed, including `a_diagnostic_payload_matches_the_documented_grammar`, `an_over_long_diagnostic_reason_is_truncated_observably`, `a_diagnostic_payload_stays_within_its_bound`, `a_malformed_diagnostic_payload_is_refused`; runner-side `a_diagnostic_payload_is_bounded` | Pass | +| 5 | A `Required` request still fails closed before the target starts, proven on the target's side effect | unchanged `Required` branches in `NoExecutionSetup::prepare`, `TrustedLandlockSetup::prepare`, `SandboxChannel::wait` | Executed: runner-side `a_required_sandbox_is_refused_without_a_degradation_diagnostic` asserts the marker file does not exist; server-side `a_required_sandbox_never_reaches_the_target_and_is_not_reported_as_a_degradation` asserts the marker file does not exist | Pass | +| 6 | A `Required` request's terminal classification is unchanged | `failure_for_runner_error` and `failed_result` in `crates/eggwork-server/src/lib.rs` (not modified) | Executed: server-side `a_required_sandbox_never_reaches_the_target_and_is_not_reported_as_a_degradation` asserts `ExecutionState::Failed`, `ExecutionFailure::Internal`, and `SandboxResult::Failed { .. }` — the baseline classification | Pass | +| 7 | An execution with nothing degraded emits no diagnostic | `report_setup_degradations` only reports `BestEffort` requests and only for outcomes it classified | Executed: runner-side `an_execution_with_nothing_degraded_emits_no_diagnostic` and `an_execution_cancelled_before_spawn_emits_no_diagnostic`; server-side `an_execution_with_nothing_degraded_publishes_no_diagnostic` | Pass | +| 8 | The diagnostic is durable and appears in a replayed event page | `publish` → `store.commit_event` in `crates/eggwork-server/src/lib.rs` (the existing path, unchanged) | Executed: server-side `the_diagnostic_is_replayed_from_the_journal_after_the_execution_ended` reads `GET /v1/executions/{id}/events` after the execution finished and finds the payload | Pass | +| 9 | No wire representation changed; `ExecutionEventKind` keeps its shape | `crates/eggwork-core/src/lib.rs` — `ExecutionEventKind` untouched | Executed: `git diff` shows no change to `ExecutionEventKind`, `ExecutionResult`, `SandboxResult` or `ResourceResult`; `cargo check --workspace --all-targets` passes | Pass | +| 10 | The server creates no child process on any path added by this milestone | `crates/eggwork-server/src/lib.rs` — the added path only maps a chunk to an event kind | Executed: `python3 scripts/check_execution_ownership.py` — passed ("approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)") | Pass | +| 11 | The runner's public API change is enumerated and reflected in the release version and notes | §2 above enumerates it | **Partially open.** The change is enumerated here and in the architecture docs. The *version bump* is not done: no `Cargo.toml` is in this milestone's ownership. The coordinator/release owner must make it version-visible. See §9 finding S-03 | Open (coordinator action) | +| 12 | The four deep dives match the code | `architecture/protocol.md`, `architecture/runner-execution.md`, `architecture/server-node.md`, `architecture/sandbox-helper.md` | Inspected: each edit was written against the code as it now stands, using symbol references rather than line numbers | Pass (inspection) | +| 13 | The full pre-submit gate is green on the reviewed head | — | **Not executed here.** The scoped gate was run (§5); the full workspace gate is the coordinator's, and this milestone deliberately did not run `cargo fmt --all` or `cargo clippy --workspace` while other agents work in the same tree | Open (coordinator action) | + +## 5. Verification actually executed + +Host: Linux x86_64, kernel `6.8.0-147-generic`; rustc `1.89.0` (pinned by +`rust-toolchain.toml`). Everything below was run in this working tree; the +outcomes are quoted, not summarised from memory. + +| Command | Outcome | +| --- | --- | +| `cargo test -p eggwork-core --lib` | **32 passed, 0 failed** | +| `cargo test -p eggwork-runner --lib` | **18 passed, 0 failed, 1 ignored** | +| `cargo test -p eggwork-runner --test diagnostic_degradation` | **7 passed, 0 failed** | +| `cargo test -p eggwork-runner --test capability_probe` | **2 passed, 0 failed** | +| `cargo test -p eggwork-server --lib` | **133 passed, 0 failed** (128 pre-existing + 5 new) | +| `cargo fmt -p eggwork-core -p eggwork-runner -p eggwork-server` | applied; `git diff --check` clean afterwards | +| `cargo clippy -p eggwork-core -p eggwork-runner -p eggwork-server --all-targets -- -D warnings` | **no issues** | +| `cargo check --workspace --all-targets` | **passed** (compiles every crate and test target, including `eggwork-client` and the release-contract suites) | +| `cargo check -p eggwork-core -p eggwork-runner --target x86_64-pc-windows-msvc --all-targets` | **passed** | +| `cargo clippy --locked -p eggwork-runner --target x86_64-pc-windows-msvc --all-targets --all-features -- -D warnings` | **passed** — this is the same command the `windows-runner` CI job runs for the runner's test targets | +| `cargo clippy --locked -p eggwork-runner --target x86_64-apple-darwin --all-targets --all-features -- -D warnings` | **failed on a pre-existing defect, not on this change** — `method 'start_kill' is never used` at `crates/eggwork-runner/src/process_tree.rs:142`. `ProcessTree::start_kill` is called only from the Linux-only helper-handshake paths (the `#[cfg(target_os = "linux")]` block in `LocalProcessRunner::run`), so it is dead code on macOS. `process_tree.rs` is not in this milestone's ownership and was not modified; the same dead-code error is present at the reviewed head `778d83c` (the call sites are inside the same `cfg`-gated block there). See §9 finding S-07. | +| `cargo check -p eggwork-server --lib --bins --target x86_64-pc-windows-msvc` | **blocked by the environment, not by the change** — the `aws-lc-sys` build script needs a Windows C toolchain (`cl.exe`), which is not installed on this Linux host. The failure happens in a third-party dependency's build script, before any Eggwork code is compiled. The server's Windows compilation is covered by the `windows-runner` CI job. | +| `python3 scripts/check_execution_ownership.py` | **passed** — "approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)" | +| `python3 scripts/check_execution_ownership.py --prove-negative-exit` | **passed** — "synthetic forbidden spawn detected" | +| `git diff --check` | **clean** | + +**Not executed in this milestone** (coordinator's full gate, and deliberately +not run here because other agents are working in the same tree): +`cargo fmt --all -- --check`, `cargo clippy --locked --workspace --all-targets +--all-features -- -D warnings`, `cargo test --locked --workspace --all-targets`, +`cargo check --workspace`, and +`python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release`. + +## 6. Negative and adversarial evidence + +### 6.1 The ordering assertions fail against a deliberately reordered implementation + +The implementation was temporarily modified so that the degradation diagnostic +was emitted at the **end** of the run instead of at setup time — i.e. after +the target had produced its output, which is the shape a +`RunnerResult`-derived diagnostic would have. The change was reverted +immediately afterwards and the tree re-verified. + +Runner suite against the reordered implementation: + +```text +test a_degraded_best_effort_sandbox_is_reported_before_the_target_output ... FAILED +---- a_degraded_best_effort_sandbox_is_reported_before_the_target_output stdout ---- +panicked at crates/eggwork-runner/tests/diagnostic_degradation.rs:96:5: +assertion `left == right` failed: the diagnostic has to precede the target's first output; +got [OutputChunk { stream: "stdout", length: 14, bytes: "[REDACTED]" }, + OutputChunk { stream: "diagnostic", length: 150, payload: "[REDACTED]" }] + left: 0 + right: 1 +test result: FAILED. 6 passed; 1 failed +``` + +Server suite against the reordered implementation: + +```text +test tests::a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal ... FAILED +---- stdout ---- +panicked at crates/eggwork-server/src/lib.rs:5467:9: +the diagnostic has to precede the target's first output; got [ + ExecutionEvent { sequence: EventSequence(1), kind: State(Accepted), … }, + ExecutionEvent { sequence: EventSequence(2), kind: State(Running), … }, + ExecutionEvent { sequence: EventSequence(3), kind: Stdout { length: 14, … }, … }, + ExecutionEvent { sequence: EventSequence(4), kind: Diagnostic { length: 150, … }, … }, + ExecutionEvent { sequence: EventSequence(5), kind: State(Succeeded), … } ] +test result: FAILED. 0 passed; 1 failed; 132 filtered out +``` + +Both assertions pass again after the reorder was reverted (7 passed / 133 +passed, §5). + +**What this proves, and what it does not.** The reordered run still placed the +diagnostic *before* the terminal event (sequence 4 < sequence 5), so the +"before the terminal event" assertion alone does **not** discriminate. The +discriminating assertion is the one against the *first target output*. That +is the assertion this milestone had to get right, and it is the one the +negative run shows failing when the emission point moves. + +### 6.2 The `Required` side-effect assertion + +`a_required_sandbox_is_refused_without_a_degradation_diagnostic` (runner) and +`a_required_sandbox_never_reaches_the_target_and_is_not_reported_as_a_degradation` +(server) assert that the target's marker file **does not exist** — the +observable side effect, not merely the terminal state — and that no diagnostic +was published. Both pass (§5). + +### 6.3 Non-vacuity controls + +- The server tests inject the runner explicitly + (`LocalProcessRunner::new(NoExecutionSetup)` and, for the required case, + the `AdvertisesLandlockButCannotEnforce` fixture). `LocalProcessRunner::default()` + is never used, because on Linux it discovers a sibling helper and the + behaviour would be environment-dependent. +- The "nothing degraded" and "cancelled before spawn" tests exist precisely so + that a diagnostic emitted on *every* execution would fail them. +- The core tests pin the truncation marker and the bound, so a payload that + silently dropped an over-long reason would fail. + +### 6.4 Cancellation, restart, contention, and the security review + +| Case | Expected (plan §6) | Status | +| --- | --- | --- | +| Cancellation **before** spawn | no diagnostic — a cancellation is not a degradation | Executed: runner-side `an_execution_cancelled_before_spawn_emits_no_diagnostic` — the runner returns `CancelledBeforeSpawn` before `prepare` is reached, so no degradation was ever classified | +| Cancellation **after** spawn | the diagnostic still stands and precedes the terminal `Cancelled`/`Interrupted` event | Inspected: the diagnostic is emitted at setup time, before the spawn, so it is already in the journal when the cancellation is classified. No dedicated test was added for this case; the mechanism is the same one the ordering tests exercise | +| Lease expiry | the diagnostic is not retracted; the server's rewrite to `Interrupted`/`LeaseExpired` is untouched | Inspected: the rewrite happens in `run_execution` on the *result*, after the diagnostic was published, and it changes the snapshot's state only. No dedicated test | +| Timeout / output-limit termination | the diagnostic is emitted at setup time and is unaffected | Inspected: same mechanism as the cancellation-after-spawn case | +| Runner error | no degradation is reported from a result that does not exist; a setup-time diagnostic that was already emitted stands | Inspected: `failure_for_runner_error`/`failed_result` were not modified | +| Event-publication failure | the existing behaviour (drain and cancel) is unchanged | Inspected: the diagnostic goes through the same `publish` → `store.commit_event` path as every other event | +| Restart and recovery | the diagnostic is in the durable journal, so a client that reconnects after a node restart sees it | Executed (same durability path): `the_diagnostic_is_replayed_from_the_journal_after_the_execution_ended` reads the event page after the execution finished | +| Contention | one sequence number and one journal row; no change to the state machine or the trimming | Inspected: the diagnostic is an ordinary event with no special-casing in `commit_event` | + +**Security review of the change.** + +- *Process ownership*: the server's added path only maps a chunk to an event + kind; it creates no process. `python3 scripts/check_execution_ownership.py` + passed, and no `Cargo.toml` was touched, so no dependency edge changed. +- *Wire contract*: `ExecutionEventKind`, `ExecutionResult`, `SandboxResult` + and `ResourceResult` are byte-for-byte unchanged. The `Diagnostic` variant + already existed and was already decodable; this milestone makes it appear in + production traffic. +- *Authentication, authorization, lease, generation, fencing, digest bounds*: + none of those code paths was touched. The diagnostic is published by the + existing `publish` funnel, under the same lease and generation as every + other event of that execution. +- *Secrets*: the diagnostic carries an operator-facing reason, a profile name + and a dimension name. It carries no credential, no path and no target + output. `OutputChunk`'s hand-written `Debug` still redacts the payload, and + the pre-existing `secret_sentinels_stay_out_of_error_and_debug_surfaces` + test now also covers the `Diagnostic` variant. +- *Fail-closed*: unchanged. A required request is refused before the target + starts; the refusal is never described as a degradation. + +## 7. Platform matrix actually exercised + +| Platform | Evidence | Claim | +| --- | --- | --- | +| Linux x86_64 (`6.8.0-147-generic`, rustc 1.89.0) | The suites in §5 were executed on this host. The degradation paths exercised are the *setup* paths (`NoExecutionSetup`: no sandbox backend, no resource backend) and the server's refusal path. | The diagnostic mechanism, its ordering, its bound and its durability are qualified on this host class. The **Landlock and cgroup enforcement paths themselves were not exercised here** — no trusted helper was installed in this environment, so the *handshake-recovery* emission point and the *post-mortem unobservable-counter* emission point are **code-inspected only**. | +| macOS | No hosted runner and no macOS host in this environment. Code inspection only: `verify_trusted_helper` → `Err`, Landlock probe → `false`, cgroup probe → `Err`, so every best-effort request degrades and takes the setup-time emission path, which is platform-neutral. The runner's test targets were *compiled* for `x86_64-apple-darwin` (clippy reached the crate's own code) but the crate does not build warning-free on macOS at the reviewed head — see §5 and §9 finding S-07. | **Not qualified.** No claim is made beyond "the setup-time emission path is platform-neutral code". | +| Windows | The runner (including its test targets) compiles and lints clean for `x86_64-pc-windows-msvc` with `-D warnings`, which is what the `windows-runner` CI job checks. The *server* crate could not be cross-checked here (§5, `aws-lc-sys` needs a Windows C toolchain). The new runner suite is written platform-aware (`cmd.exe` on Windows, `/bin/sh` elsewhere) so the `windows-runner` job's `cargo test -p eggwork-runner --all-targets` exercises it there — but that run has **not** happened in this milestone. | **Not qualified.** Compilation is not qualification. The Windows row stays open until the Windows CI job runs the new suite green — see §9 finding S-02. | + +Only the Linux toolchain is installed here, so no cross-compilation was +attempted. **No platform is claimed as qualified merely because its code +compiles.** + +## 8. Documentation status + +| Document | Change | +| --- | --- | +| `architecture/protocol.md` | New section "The execution diagnostic payload (schema version 1)": the grammar, the closed class set, the key set, the bound, the truncation rule, and what the payload deliberately does not carry. | +| `architecture/runner-execution.md` | New section "Reporting a degradation": where the runner emits and when, the emission-site table, and the rules (required is never degraded, one event per degraded dimension, silence when nothing degraded). The `OutputChunk` description was replaced with the enum, the `spawn_reader` step and the process-lifecycle steps 4/4a/6/9 were updated, and two invariant rows were added. | +| `architecture/server-node.md` | New paragraph "Where a degradation diagnostic is published": the publication point, the ordering guarantee, and the fact that a post-terminal publication would be dropped (because `publish` short-circuits on a terminal base state and `commit_event` refuses a terminal execution). The test-coverage list names the new cases. | +| `architecture/sandbox-helper.md` | The handshake-recovery paragraph now states that the runner reports the degradation before it re-spawns the target directly, and a new paragraph states that the unobservable counter is a post-mortem fact whose diagnostic necessarily follows the target's output. One invariant row was added. | +| `architecture/overview.md` | **Not edited — the coordinator owns it.** See §9 finding S-01 for the recommended disposition. | +| `AGENTS.md` | Not edited. The hard-invariant list needed no new entry; the "Isolation claims are earned" line is unchanged and remains true. | +| `plans/subsystems/security-isolation-resource-roadmap.md` | M005a entry updated (status, closure-evidence pointer, exit conditions rewritten to the implemented mechanism) and the roadmap's status line updated. | +| `plans/registry.md` | **Not edited — the coordinator owns it.** See §9 finding S-01. | + +New text in the deep dives uses symbol references rather than line numbers, +so it does not add to the repository's stale-line-number defect. + +## 9. Unresolved findings, ranked by severity + +**Critical: none. High: none.** + +- **S-01 — Medium — owner: the coordinator (registry/overview owner).** The + registry (`plans/registry.md`) and `architecture/overview.md` are outside this + milestone's file ownership and were not edited. The recommendation is in + §10. +- **S-02 — Medium — owner: the release owner / CI owner.** The runner's + public `OutputChunk` type changed shape (struct → enum). The plan's §8 + requires the change to be "exercised on the Windows and macOS targets the + release matrix builds", and this milestone could only execute Linux. The + new suite `crates/eggwork-runner/tests/diagnostic_degradation.rs` uses + `/bin/sh` and therefore does not run on Windows as written; the Windows + tree suite (`crates/eggwork-runner/tests/windows_process_tree.rs`) already + proves that best-effort is reported `NotApplied` there, but it does not yet + assert the diagnostic. Until a Windows run covers it, the Windows row of + §7 stays "not qualified". +- **S-03 — Medium — owner: the coordinator / release owner.** The + `OutputChunk` change is release-visible and must be folded into a + version-visible release with release notes, not into a qualification-only + candidate. No `Cargo.toml` is in this milestone's ownership, so the version + bump was not made. +- **S-04 — Low — owner: the security-isolation subsystem owner.** The + post-mortem resource observation (the helper's `STATUS_UNOBSERVED` counter) + is a fact that only exists *after* the target exited, so its diagnostic + necessarily follows the target's output. It still precedes the terminal + event, and the terminal snapshot remains the authoritative evidence. This + is the one documented exception to "the diagnostic precedes any target + output"; it is a property of the fact, not of the mechanism. The terminal + snapshot is also coarse here: the whole resource outcome is rewritten to + `NotApplied` when *one* counter was unobservable, so the snapshot reads + `NotApplied` for dimensions whose limits were in fact applied and observed. + The diagnostic is more precise than the snapshot in that case (it names only + the dimension the helper actually reported). The snapshot's behaviour was + **not** changed by this milestone, per the plan's §5.7. +- **S-05 — Low — owner: the security-isolation subsystem owner.** The + diagnostic's `reason` value is normalised to printable ASCII, so a space + becomes `_`. The reason text in the diagnostic is therefore less readable + than the same sentence in the terminal snapshot. This is the price of a + space-separated grammar without an escaping scheme; the snapshot keeps the + original sentence and remains the authoritative evidence. +- **S-06 — Low — owner: the control-plane owner.** An external client that + treats an unknown `ExecutionEventKind` as fatal would break on the newly + trafficked `Diagnostic` variant. The repository's own client tolerates it + (executed evidence in §4, criterion 8's path). The wire contract itself is + unchanged — the variant already existed — so this is a client-side + behaviour note for the release notes rather than a protocol change. +- **S-07 — Low — owner: the foundation/runner owner (NOT this milestone).** + `crates/eggwork-runner/src/process_tree.rs`'s `ProcessTree::start_kill` is + called only from the Linux-only helper-handshake paths, so on macOS it is + dead code and `cargo clippy --target x86_64-apple-darwin -- -D warnings` + fails with "method `start_kill` is never used". This is **pre-existing at + the reviewed head `778d83c`** (the same call sites are inside the same + `cfg`-gated block there) and `process_tree.rs` is not in this milestone's + ownership, so it was not touched. It is recorded here because it blocks the + macOS cross-target clippy check that §8's platform matrix would otherwise + use. The one-line fix is a `#[cfg(target_os = "linux")]` on the method. + +## 10. `architecture/overview.md` recommendation + +**Conclusion: no divergence row should be added for M005a.** + +The truthfulness gap the milestone set out to close is closed: a degraded +best-effort execution now produces a diagnostic event in the stream, bounded, +grammar-conforming, published before the target's output and before the +terminal event, and durable in the journal. The plan's §10 says to add a row +"only if a residual divergence remains after M005a; if the truthfulness gap is +closed, do not add a row", and it is closed. + +The one documented exception (S-04, the post-mortem unobservable counter) is a +property of the *fact* being reported, not a divergence between the code and +the documentation: the code and the docs both say that this particular +diagnostic follows the target's output, because the helper can only report an +unobservable counter after the target exited. There is nothing for a +divergence row to point at. + +**If the coordinator nonetheless wants a row** — for instance to make the +post-mortem exception visible from the bird's-eye view — the exact text would +be: + +```markdown +| 6 | The helper-reported unobservable-counter degradation is published after the target's output | `crates/eggwork-runner/src/lib.rs` (post-mortem resource observation block) | `architecture/runner-execution.md` § "Reporting a degradation"; the fact only exists after the target exited | +``` + +It should be added **only** with that wording, and it must not touch +divergence #5 (the weaker deployment-path helper-trust check), which is a +separate, still-open item that this milestone neither closes nor worsens. + +## 11. Registry and roadmap disposition + +- `plans/subsystems/security-isolation-resource-roadmap.md`: M005a — + `proposed` → **implemented** (closure record written, implementation commit + pending). The exit condition "the diagnostic is emitted on the same path as + the terminal result, so the two cannot disagree" was **rewritten** to the + implemented mechanism, because the original wording describes the + server-side fallback that the plan explicitly demotes. The intent is + preserved and made stronger: the payload and the terminal snapshot are + derived from the same `SetupOutcome`, and the diagnostic is published + *before* the terminal event rather than next to it. +- The roadmap's status line was updated to match. +- `plans/registry.md`: **not edited** — the registry is the coordinator's + file. The coordinator's action is to register M005a as implemented (closure + record `plans/closure/security-isolation-resource/005a-status.md`) and to + fill `IMPLEMENTATION-COMMIT-PENDING` in this record and in the roadmap + entry with the real commit SHA. +- `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`: + **not edited** — the plan is not in this milestone's ownership and is left + as the authoritative statement of what was asked. diff --git a/plans/subsystems/security-isolation-resource-roadmap.md b/plans/subsystems/security-isolation-resource-roadmap.md index 46976bd..4b9388d 100644 --- a/plans/subsystems/security-isolation-resource-roadmap.md +++ b/plans/subsystems/security-isolation-resource-roadmap.md @@ -1,6 +1,6 @@ # Security, Isolation, and Resource Enforcement Roadmap -Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a and M005b correctives proposed; M005c blocked on ADR-0007 +Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a implemented (closure record written, implementation commit pending); M005b corrective proposed; M005c blocked on ADR-0007 Canonical authority: @@ -154,7 +154,10 @@ Run hostile input/process/workspace/transport fixtures, audit dependencies and u Class: invariant -Status: proposed +Status: implemented — closure record written, implementation commit pending + +Closure evidence: `plans/closure/security-isolation-resource/005a-status.md` +(implementation `IMPLEMENTATION-COMMIT-PENDING`) Corrective addendum: @@ -171,7 +174,7 @@ Make degradation visible where a caller will actually see it. `SandboxResult::No Exit conditions: - a degraded best-effort execution emits a diagnostic into the event stream, with a payload that identifies what degraded and why; -- the diagnostic is emitted on the same path as the terminal result, so the two cannot disagree; +- the diagnostic is published **before the target's first output and before the terminal event**, so a caller sees the degradation while the execution is still running. The runner emits it on the output channel it already owns, and the payload and the terminal snapshot are derived from the same `SetupOutcome`, so the two cannot disagree. A diagnostic derived from the runner's result instead would necessarily arrive after all target output — and after the terminal event, where the store would refuse to append it; - no `Required` execution reaches the target without the requested control; - the required-isolation and required-resource fail-closed rules are unchanged. From a8abfcb2d0d656f5b79f308cd2fb01d9f94541aa Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 15:06:51 +0000 Subject: [PATCH 03/37] docs(plans): record the core protocol-contract ownership change as ADR-0008 plans/003-planning-process.md section 8 requires an ADR or canonical amendment before an ownership-boundary change lands. Control-plane M004 section 12.3 names that condition as a stop condition. ADR-0008 records that eggwork-core owns the control-plane API schema version, the exec.argv.v1 capability name, and the terminal/non-terminal classification of ExecutionState, while the runner keeps producer ownership of the capability names it produces and of the sandbox profile name. No wire value, wire field, or capability byte changes. This clears M004's section 12.3 stop condition. The plan, the corrective addendum, and the registry are updated to point at the record. --- ...R-0008-core-protocol-contract-ownership.md | 177 ++++++++++++++++++ ...004-shared-protocol-contract-corrective.md | 4 +- plans/registry.md | 2 + ...col-shared-contract-corrective-addendum.md | 2 +- 4 files changed, 183 insertions(+), 2 deletions(-) create mode 100644 plans/adrs/ADR-0008-core-protocol-contract-ownership.md diff --git a/plans/adrs/ADR-0008-core-protocol-contract-ownership.md b/plans/adrs/ADR-0008-core-protocol-contract-ownership.md new file mode 100644 index 0000000..d487423 --- /dev/null +++ b/plans/adrs/ADR-0008-core-protocol-contract-ownership.md @@ -0,0 +1,177 @@ +# ADR-0008: Core Ownership of the Protocol Contract Facts + +Status: accepted + +Date: 2026-10-23 + +Decision: `eggwork-core` owns the control-plane API schema version, the +`exec.argv.v1` capability feature name, and the terminal/non-terminal +classification of `ExecutionState`. The runner keeps producer ownership of the +capability feature names it produces and of the sandbox profile name. No wire +value, wire field, or capability byte changes. + +Related authority: + +- `plans/adrs/ADR-0001-fixed-target-scheduler-free-execution.md` +- `plans/adrs/ADR-0002-eggstack-transport-and-mtls.md` +- `plans/adrs/ADR-0004-content-addressed-workspaces-and-artifacts.md` +- `plans/000-long-term-specification.md` +- `plans/001-terminology-and-domain-model.md` +- `architecture/core-domain.md` — the **States** section, which currently records + that `eggwork-core` owns no terminal concept +- `architecture/overview.md` — divergence #12 +- `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` — + the corrective that owns the findings and the ownership decision +- `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md` — + the implementation plan, whose §12.3 stop condition requires this record +- `plans/003-planning-process.md` §8 (architecture changes) + +## Context + +Three protocol contract facts were each stated by more than one owner, and the +copies had no mechanical relationship. Both sides of every pair currently agree +by value, so none of this is a live bug. The defect is structural: a future +rename or bump on the producing side desynchronises the consuming side +silently, and neither the compiler nor the test suite objects. + +1. **The control-plane API schema version.** The client and the server each + declared a private `API_SCHEMA_VERSION`. The client stamps its value into + the execute, control, workspace-create, and workspace-derive request bodies. + The server compares the received value against its own and rejects a + mismatch with HTTP 426 `protocol_version`. Nothing linked the two + declarations. + +2. **The `exec.argv.v1` capability feature name.** The server produces the + name in its static capability advertisement; the client consumes it when it + checks that a node is protocol-compatible. Each endpoint crate spelled the + literal independently. + +3. **The terminal/non-terminal classification of `ExecutionState`.** + `eggwork-core` defines `ExecutionState` as a flat nine-variant enum and + owned no terminal concept at all: no predicate, no grouping, no canonical + spelling. The server therefore enumerated the classification approximately + nine times — in the store's state-name and terminal-name helpers, in an + inline match in the same store file that did not call its own helper, in a + separate terminal predicate, in an inline artifact-capture eligibility + subset, in a wildcard-terminated terminal-to-metric-name match, in a + non-terminal match in the operations module, in a parallel SQL literal list, + and in a second enum-to-string map for display labels. + +`eggwork-core` already owned the closest precedent: it exports +`NODE_TELEMETRY_SCHEMA_VERSION`, consumed by the client's telemetry reader, the +server's telemetry projection, and core's own `NodeTelemetry::validate`. + +`plans/003-planning-process.md` §8 requires that a durable ownership-boundary +change be recorded as an ADR or a canonical amendment before the implementing +work lands. This ADR is that record. + +## Alternatives + +A. **The server owns the schema version and the feature names; the client + imports them.** Rejected. `crates/eggwork-client` depends on `eggwork-core` + only. The client cannot depend on the server without inverting the + workspace's one-way dependency rule, and the server cannot be depended upon + by the client. + +B. **A new workspace crate owning the protocol contract.** Rejected. It would + add a dependency edge to a five-crate workspace whose dependency graph is + deliberately flat and one-way, and it would move wire types away from the + crate that already models them. The facts have exactly one consumer set + that spans endpoints, and the crate both endpoints already share is that + set's natural home. + +C. **Leave the literals in place and pin them with tests only.** Rejected. A + test pins a value at the moment it is written; it does not make a future + one-sided edit a compile error, and the terminal-state case has nine + enumeration sites rather than two. The classification in particular cannot + be pinned by value, because the defect is that the set is written nine + times. + +D. **`eggwork-core` owns the contract facts that both endpoints consume; the + producing crate owns the names it alone produces.** **Selected.** + +## Decision and constraints + +1. **`eggwork-core` owns the control-plane API schema version.** It is + declared exactly once, publicly, in `crates/eggwork-core/src/lib.rs`. The + client and the server import it; neither keeps a private copy. The server's + check sites, and when it checks, are unchanged. + +2. **`eggwork-core` owns the `exec.argv.v1` capability feature name.** The + server produces the name and the client consumes it, and the client cannot + depend on the server. `eggwork-core` is the crate both already depend on, + and it already owns the `NodeCapabilities` type whose `features` field + carries the name. + +3. **`eggwork-core` owns the terminal/non-terminal classification of + `ExecutionState`**, together with the canonical wire spelling of a state + and a way to enumerate every variant. The classification is an exhaustive + match over all nine variants with no wildcard arm, and the wire-spelling + function is likewise exhaustive. Adding a tenth variant is therefore a + compile error in `eggwork-core` rather than a silent behaviour change in a + downstream crate. + +4. **The artifact-capture eligibility subset stays a distinct policy.** The + subset that admits artifacts for capture is exactly `Succeeded` and + `Failed`. It is not the terminal set and must not be folded into it, nor the + terminal set folded into it. + +5. **Producer ownership is preferred where it is available.** The runner keeps + ownership of the capability feature names it produces — the Landlock + workspace-rw name and the three `resources.cgroups-v2.*` names — and of the + sandbox profile name. The server imports the runner's constants rather than + restating them. + +6. **The sandbox helper keeps no workspace-crate dependency.** The helper is + the trusted artifact and its dependency surface is part of its trust story, + so the helper's copy of the profile name is pinned by a test rather than by + a shared crate. The same rule applies to the protocol limit constants the + helper restates. + +7. **No wire value changes.** The schema version stays `1`. Every capability + feature name keeps its exact bytes. `ExecutionState` keeps its derived + `Serialize`/`Deserialize` with no rename attribute and stays externally + tagged PascalCase. The server's stored `state` column keeps the same + PascalCase strings, and the operator-facing state labels keep the same + snake_case output. + +8. **`eggwork-core` keeps no internal dependency.** The crate hierarchy stays + one-way: core and the sandbox helper depend on nothing internal; the client + depends on core; the server depends on core and the runner; the runner + depends on core; the client is a dev-dependency of the server only. + +9. **No authentication, authorization, lease, generation, fencing, digest, or + idempotency semantics change.** This ADR moves where a fact is written, not + what it is. + +10. **Sharing a constant prevents creating skew inside one build.** It cannot + remove skew between two already-deployed binaries. A future schema-version + bump needs its own compatibility story; this ADR does not pre-authorize + one. + +## Consequences + +- A change to the API schema version, to the `exec.argv.v1` feature name, or + to the terminal-state classification becomes a compile-time or + test-detectable event rather than a silent divergence. +- The server's nine terminal-state enumeration sites collapse to derivations + from one owner. The metric-name mapping becomes total by construction, so a + newly added terminal variant cannot silently lose its metric name. +- The active-execution count query derives its SQL literal list from the + shared spelling. That list becomes runtime-assembled, so the query must stay + parameterised; string-concatenated SQL is not acceptable on that path. +- `architecture/core-domain.md` currently states that `eggwork-core` has no + `is_terminal()` helper and no terminal-state grouping. That statement becomes + false when this decision is implemented and must be rewritten in the same + pass. It is an update to a recorded observation, not a deletion. +- Sharing a constant within one build is not a migration story: no stored + format moves, no rollout step is needed, and no coordination with deployed + clients or nodes is required, because no observable value changes. + +## Scope boundary + +This ADR records an ownership decision. It does not specify the implementation +of that ownership, the tests that prove it, or the milestone that delivers it; +those belong to +`plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md` +and its closure record. diff --git a/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md b/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md index bd7eccf..3f593bd 100644 --- a/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md +++ b/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md @@ -19,6 +19,8 @@ Canonical/ADR references: - `plans/adrs/ADR-0001-fixed-target-scheduler-free-execution.md` - `plans/adrs/ADR-0002-eggstack-transport-and-mtls.md` - `plans/adrs/ADR-0003-execution-idempotency-leases-and-fencing.md` +- `plans/adrs/ADR-0008-core-protocol-contract-ownership.md` — records the `eggwork-core` + ownership change this milestone makes, satisfying §12.3's architecture-review condition - `plans/003-planning-process.md` Historical predecessor closures (immutable; this plan does not rewrite them): @@ -298,7 +300,7 @@ Stop, do not improvise, and escalate to the plan's owner if any of these occur. 1. **A feature-string value would have to change.** If sharing a capability constant appears to require changing any feature name's bytes — including `exec.argv.v1`, the three `resources.cgroups-v2.*` names, `isolation.landlock.workspace-rw.v1`, or `network.unrestricted.v1` — stop. A value change is a compatibility break that needs an ADR, and `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md` §3 already froze these semantics. Preserve the values; change only the ownership. 2. **A dependency edge the crate rules forbid.** The rules are: `eggwork-core` and `eggwork-sandbox-helper` depend on nothing internal; `eggwork-client` depends on `eggwork-core`; `eggwork-server` depends on `eggwork-core` and `eggwork-runner`; `eggwork-client` is a dev-dependency of `eggwork-server` only. If a shared constant would require violating one of these — in particular, giving `eggwork-sandbox-helper` a workspace dependency, or giving `eggwork-client` a dependency on `eggwork-server` or `eggwork-runner` — stop and re-plan. The correct answer to a blocked owner is a different owner or a test-pinned literal, not a new edge. -3. **The core ownership change needs architecture review.** Giving `eggwork-core` a terminal-state classification and a schema-version constant is an intentional ownership change to a crate that currently owns neither. Per `plans/003-planning-process.md` §8, stop before implementing if that change has not been recorded as an ADR or canonical amendment, and report the blocker. +3. **The core ownership change needs architecture review.** Giving `eggwork-core` a terminal-state classification and a schema-version constant is an intentional ownership change to a crate that currently owns neither. Per `plans/003-planning-process.md` §8, this change must be recorded as an ADR or canonical amendment before the implementation lands. **Satisfied:** `plans/adrs/ADR-0008-core-protocol-contract-ownership.md` (accepted, 2026-10-23) records it, including the alternatives rejected and the constraint that no wire value, wire field, or capability byte changes. If the implementation finds the ownership change must extend beyond what ADR-0008 records, stop and report the blocker rather than widening it silently. 4. **The artifact-capture eligibility rule would have to widen.** If consolidating the enumerations appears to require capturing artifacts for `Cancelled`, `TimedOut`, or `Interrupted`, stop. That rule is a distinct policy subset and this plan must not touch it. 5. **The store's stored format would have to move.** If deriving the SQL literal list or the `state` spelling would change the stored bytes, the column schema, or the JSON in the `executions` table, stop and re-plan. This plan changes where the spelling comes from, not what it is. 6. **A test would become vacuous.** If any required test in §6 cannot be made non-vacuous — for example if the cross-crate agreement test cannot observe the client's real request body — stop and report. A test that passes for the wrong reason is worse than no test. diff --git a/plans/registry.md b/plans/registry.md index e5e8b08..4fbe072 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -19,6 +19,8 @@ Founding ADRs: Follow-up accepted ADR: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` (Eggwork reads local Gregg optionally; Gregg unchanged). +Follow-up accepted ADR: `plans/adrs/ADR-0008-core-protocol-contract-ownership.md` (2026-10-23) — `eggwork-core` owns the control-plane API schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification of `ExecutionState`; the runner keeps producer ownership of the capability names it produces and of the sandbox profile name. No wire value, wire field, or capability byte changes. This is the `plans/003-planning-process.md` §8 record that Control-plane M004's §12.3 stop condition requires. + Proposed ADR, **not yet accepted**: `plans/adrs/ADR-0007-resource-scoped-authorization.md` (decides whether resource-scoped grants are implemented or the inert hook and its plumbing are removed). Security M005c is blocked on it. ## Status vocabulary diff --git a/plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md b/plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md index 4cefffe..ec3fc9b 100644 --- a/plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md +++ b/plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md @@ -110,7 +110,7 @@ Give each of the three duplicated contract facts a single owner, so that client, Status is **proposed**, not **ready**, for three reasons recorded here rather than left to the implementing agent: -1. M004 requires an intentional, reviewed ownership change to `eggwork-core`: the crate must take ownership of a terminal-state classification it does not currently have. `plans/003-planning-process.md` §8 requires that an ownership-boundary change be recorded as an ADR or canonical amendment before the implementation lands. That record does not exist yet. +1. M004 requires an intentional, reviewed ownership change to `eggwork-core`: the crate must take ownership of a terminal-state classification it does not currently have. `plans/003-planning-process.md` §8 requires that an ownership-boundary change be recorded as an ADR or canonical amendment before the implementation lands. **That record now exists**: `plans/adrs/ADR-0008-core-protocol-contract-ownership.md` (accepted, 2026-10-23) records the ownership change, the alternatives rejected, and the constraint that no wire value changes. The plan's §12.3 stop condition is satisfied by that ADR. 2. Two dispositions are still open and are not implementation detail: where the operator-facing `state_label` map lives, and whether the artifact-capture eligibility predicate stays server-local or moves to core. §3.4.4 states the constraint on each; the plan must record the decision it makes. 3. This corrective is not registered in `plans/registry.md`. Registry ownership is not this document's, so a handoff before registration would present a plan as ready when the control surface does not say so. From 63699df919632ee9ecfddaa60bcf7157db83bf9a Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 15:48:43 +0000 Subject: [PATCH 04/37] feat(security,data-plane): M005b helper environment parity + M005b GC preview and store ownership MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two independent milestones, corrected from the repository interrogation batch. Security M005b — the sandbox helper environment parity. The runner's launch specification started from a fixed baseline and appended every non-denied caller key, so a caller-supplied LANG produced a specification with two LANG entries; the helper refused it with status 12; and for a best-effort request the runner re-spawned the target with no Landlock ruleset at all. The environment policy now has one checked-in source of truth, a deterministic generator, and generated copies in each crate. The runner drops denied keys and lets the node's value win for node-owned keys; the helper refuses a policy violation with its own status byte, 13. One builder serves both the direct and the helper launch path. Workspace M005b — the operator's GC dry-run preview and the apply pass used different candidate predicates, in a module whose own doc comment states the two must be shared. The candidate predicate, the metadata filenames, and the blob path layout now each have one owner; the preview reaches owner code through a read-only, non-reconciling seam; the materializer verifies the bytes it writes against the manifest digest while copying; and the manifest owner-id composite has one producer. No wire value, stored format, SQLite schema, bound, or authorization, lease, generation, or fencing semantics changed. --- .gitignore | 1 + architecture/data-plane.md | 219 +++++- architecture/operations-cli.md | 81 ++- architecture/runner-execution.md | 36 +- architecture/sandbox-helper.md | 158 +++-- .../policy/environment-policy.toml | 153 ++++ .../eggwork-runner/src/environment_policy.rs | 154 ++++ crates/eggwork-runner/src/lib.rs | 569 ++++++++++++--- .../tests/environment_policy.rs | 206 ++++++ .../tests/windows_process_tree.rs | 29 +- .../src/environment_policy.rs | 170 +++++ crates/eggwork-sandbox-helper/src/main.rs | 109 ++- .../tests/environment_policy_parity.rs | 670 ++++++++++++++++++ crates/eggwork-server/src/artifact.rs | 109 ++- crates/eggwork-server/src/blob.rs | 189 ++++- crates/eggwork-server/src/lib.rs | 2 +- crates/eggwork-server/src/operations.rs | 578 ++++++++++++--- crates/eggwork-server/src/workspace.rs | 387 ++++++++-- .../eggwork-server/tests/gc_preview_parity.rs | 111 +++ docs/operations.md | 10 + .../005b-status.md | 588 +++++++++++++++ .../005b-status.md | 266 +++++++ plans/registry.md | 9 +- .../security-isolation-resource-roadmap.md | 7 +- .../workspace-artifact-transport-roadmap.md | 16 +- scripts/generate_environment_policy.py | 598 ++++++++++++++++ tests/release/test_environment_policy.py | 172 +++++ 27 files changed, 5130 insertions(+), 467 deletions(-) create mode 100644 crates/eggwork-runner/policy/environment-policy.toml create mode 100644 crates/eggwork-runner/src/environment_policy.rs create mode 100644 crates/eggwork-runner/tests/environment_policy.rs create mode 100644 crates/eggwork-sandbox-helper/src/environment_policy.rs create mode 100644 crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs create mode 100644 crates/eggwork-server/tests/gc_preview_parity.rs create mode 100644 plans/closure/security-isolation-resource/005b-status.md create mode 100644 plans/closure/workspace-artifact-transport/005b-status.md create mode 100644 scripts/generate_environment_policy.py create mode 100644 tests/release/test_environment_policy.py diff --git a/.gitignore b/.gitignore index ce6d234..857bff6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ /target/ +/target-*/ __pycache__/ *.sqlite *.sqlite-shm diff --git a/architecture/data-plane.md b/architecture/data-plane.md index 81c7f89..8280353 100644 --- a/architecture/data-plane.md +++ b/architecture/data-plane.md @@ -93,11 +93,23 @@ whole capture instead of producing a partial record set. /... one shard directory per first-hex-byte pair ``` -`path_for` is `root.join(&digest.as_str()[..2]).join(digest.as_str())` (`blob.rs:123-128`): a -single level of sharding on the first two hex characters - 256 shard directories, no deeper -nesting, no extension, full digest as the file name. Two-digit sharding keeps any one directory -from accumulating the whole store while leaving `read_dir` cheap at open time (`remove_stale_parts` -walks exactly the shards). +`path_for` delegates to the store-owned pure function `blob::object_path(root, digest)`: +`root.join(&digest.as_str()[..2]).join(digest.as_str())` - a single level of sharding on the first +two hex characters - 256 shard directories, no deeper nesting, no extension, full digest as the file +name. Two-digit sharding keeps any one directory from accumulating the whole store while leaving +`read_dir` cheap at open time (`remove_stale_parts` walks exactly the shards). `blob::shard_path` +resolves the shard directory alone, and `blob::object_path` resolves the object. Both are pure +functions of `(root, digest)`, so a caller that only needs to resolve a path does not need a store +instance - and therefore does not need `BlobStore::open`, which creates the root, creates the +metadata database when absent, and calls `remove_stale_parts` (which deletes stale part files and +reconciles index rows). The operator's `inspect blob` verb resolves the object through +`blob::object_path` and never opens the store. + +**One owner for the store's metadata file name.** `blob::metadata_path(root)`, +`workspace::metadata_path(root)` and `artifact::metadata_path(database_path)` are the only places +the three metadata file names (`metadata.sqlite`, `metadata.sqlite`, `artifacts.sqlite`) are +written. The operator module resolves them through those functions instead of spelling them, so +renaming a store's database is a one-line change in its owner. The metadata database, not the filesystem, is the authority for existence. `blobs` is `(digest TEXT PRIMARY KEY, size_bytes INTEGER NOT NULL CHECK(size_bytes >= 0), @@ -106,12 +118,19 @@ reference_count INTEGER NOT NULL DEFAULT 0, last_used_unix_ms INTEGER NOT NULL)` `(owner_kind, owner_id, digest)` with `FOREIGN KEY(digest) REFERENCES blobs(digest) ON DELETE CASCADE`. `reference_count` is never written by Rust - two triggers (`blob_reference_insert` / `blob_reference_delete`, `blob.rs:101-110`) maintain it. Reclamation queries deliberately use -`NOT EXISTS (SELECT 1 FROM blob_references ...)` rather than the counter. +`NOT EXISTS (SELECT 1 FROM blob_references ...)` rather than the counter: the counter is a +denormalization maintained only by those triggers, so it can drift from the rows that actually pin +bytes, and the rows are the truth. `blob_references.owner_kind` is a small closed set in practice: `"workspace"`, `"manifest"`, `"artifact"`, and `"reader"` (in-flight download, `lib.rs:1413`). `owner_id` is the `WorkspaceId`, -the `"{principal}:{manifest_digest}"` composite (`workspace.rs:883`), the `ArtifactId`, or a fresh -UUID. +the `"{principal}:{manifest_digest}"` composite, the `ArtifactId`, or a fresh UUID. The composite +has one producer: `manifest_owner_id_for_key(principal_key, manifest_digest)` in `workspace.rs`, +with `manifest_owner_id(principal_id, manifest_digest)` as the validated-principal entry point +that delegates to it. The two retained-manifest call sites - the GC pass and the orphan sweep - +both go through it, so the format is written in exactly one place. A manifest digest is hex and +contains no colon, so the pair is recovered by splitting at the *last* colon even when the +principal itself contains one. ### Public surface @@ -123,9 +142,21 @@ UUID. - `BlobError` (`blob.rs:33-55`), walked in [Error model](#error-model). - `BlobStore::{open, path_for, find_missing, prepare_upload, stored_size, retain, set_reference_expiry, clear_reference_expiry, release_references, reference_owners, - garbage_collect, put_stream, verify_existing, open_verified}`. `BlobStore` is `Clone` and - internally `Arc`-shared, so one instance is reachable from every handler and from the workspace - and artifact modules. + garbage_collect, put_stream, verify_existing, open_verified, copy_verified}`. `BlobStore` is + `Clone` and internally `Arc`-shared, so one instance is reachable from every handler and from the + workspace and artifact modules. +- **Owner-module free functions.** These are the seams the operator uses, and they are deliberately + *not* methods on an open store, because every `open` in this subsystem creates and reconciles: + - `blob::metadata_path(root) -> PathBuf`, `blob::shard_path(root, digest) -> PathBuf`, + `blob::object_path(root, digest) -> PathBuf` - the store's file names and layout, pure. + - `blob::preview_gc(metadata_path, now_unix_ms, limit) -> Result` - + the blob candidates the collector would act on, evaluated against a read-only connection. + - `workspace::metadata_path(root) -> PathBuf`, + `workspace::preview_gc(metadata_path, now_unix_ms, limit) -> Result` - the same for workspaces and retained manifests. + - `artifact::metadata_path(database_path) -> PathBuf`, + `artifact::preview_gc(metadata_path, now_unix_ms, limit) -> Result` - the same for artifacts. ### Ingest @@ -209,9 +240,45 @@ Two phases. First, an unbounded `COUNT(*)` of expired references (`expires_unix_ms IS NOT NULL AND expires_unix_ms <= now`) - the number a dry run reports. Then, when not a dry run, delete up to `limit` of them, **re-select** blob candidates, and delete them. Selection is `WHERE NOT EXISTS (SELECT 1 FROM blob_references r WHERE r.digest = blobs.digest) -ORDER BY last_used_unix_ms ASC LIMIT ?1` (`blob.rs:318-324`): unreferenced-only, cold -(least-recently-verified) first. Selection is repeated after the expired references are dropped so -a blob that just became unreferenced is eligible in the same pass. +ORDER BY last_used_unix_ms ASC LIMIT ?1` - unreferenced-only, cold (least-recently-verified) first. +Selection is repeated after the expired references are dropped so a blob that just became +unreferenced is eligible in the same pass. + +**One predicate, three readers.** The candidate statement is the module constant +`UNREFERENCED_CANDIDATES_SQL` in `blob.rs`, and it is the only place the blob candidate predicate +is written. It has three readers: the collector's dry run, the collector's real pass, and the +operator's preview. The first two are the same function - `BlobStore::garbage_collect` selects +through `BlobStore::unreferenced_candidates` - evaluated at two different points in the +transaction. The third is `blob::preview_gc`, which evaluates the *same* statement against a +read-only connection to the same database file. + +This matters because the operator's preview used to carry its own hand-copied copy of the +predicate, and the copy had drifted: it selected on `blobs.reference_count = 0` while the collector +selected on the reference rows. The counter is a denormalization maintained only by the +`blob_reference_insert` / `blob_reference_delete` triggers, so it can drift from the rows that +actually pin bytes. The preview therefore reported a *different* set from the pass it was +previewing - both in membership and, once the drift was asymmetric, in count. + +**The preview seam is non-mutating by construction.** `BlobStore::open`, `WorkspaceManager::open` +and `ArtifactStore::open` all create and reconcile: they create the root and the metadata database +when absent, and `BlobStore::open` calls `remove_stale_parts` (deleting stale part files and +reconciling index rows) while `WorkspaceManager::open` calls `reconcile` (deleting rows and +directories that do not match the store). A preview that opened a store would therefore mutate the +store it reports on - and, against a store that does not exist yet, would bring it into being. So +the preview does not open the store: `blob::preview_gc`, `workspace::preview_gc` and +`artifact::preview_gc` open the metadata database with `SQLITE_OPEN_READ_ONLY` and evaluate the +owner's canonical statement. A preview that cannot evaluate the canonical statement fails with a +typed error; it never degrades to zero candidates. The one exception is deliberate and historical: +a store that predates the retained-manifest cache has no `retained_manifests` table, and +`workspace::preview_gc` reports zero manifest candidates for it instead of failing the whole +preview. + +**Preview versus apply.** The preview evaluates the candidate statement *before* the expired +reference rows are deleted; the apply pass evaluates it *after*. The preview's set is therefore a +**subset** of what the apply pass removes, and the difference is exactly the blobs that became +unreferenced because their expired reference was swept in the same pass. When the store holds no +expired references, the two select at the same point and the sets are **equal**. That relation is +enforced by tests, not by a comment. Per candidate: `fs::remove_file`, then `DELETE FROM blobs WHERE digest = ?1 AND NOT EXISTS (SELECT 1 FROM blob_references WHERE digest = @@ -351,11 +418,38 @@ loop fails without touching the filesystem at all. before creation, so parents precede children with no dependency analysis, and parent existence is already guaranteed by the second pass of `manifest.validate()`. `Directory` -> `create_dir` + 0700. `File` -> `OpenOptions::new().write(true).create_new(true)` with `mode(0o700)` when `executable` else -`0o600`, copying from `blobs.path_for(digest)` opened with `File::open`; `io::copy` must yield -exactly `size_bytes` else `BlobSizeMismatch` (`workspace.rs:919-921`), then `sync_all()` and -`set_file_permissions`. `Symlink` -> `InvalidManifest` (`workspace.rs:926`) - defense in depth, -since core already rejected it. Afterwards every created directory is `sync_all`ed deepest-first -(reverse component count). +`0o600`, copying from `blobs.path_for(digest)` through `BlobStore::copy_verified`; the copy must +yield exactly `size_bytes` else `BlobSizeMismatch`, then `sync_all()` and `set_file_permissions`. +`Symlink` -> `InvalidManifest` (`workspace.rs:926`) - defense in depth, since core already rejected +it. Afterwards every created directory is `sync_all`ed deepest-first (reverse component count). + +**The materializer verifies the bytes it writes.** `BlobStore::copy_verified` hashes the byte +stream it forwards into the staging file and compares the result with the manifest's digest; a +mismatch is `InvalidBlob`, and the staged file is removed so unverified bytes never survive into +the tree. The hash is computed **over the bytes that are actually copied**, not over a separate +read of the same path. A pre-flight check and a later copy are two reads of a mutable file, and +only hashing the bytes that reach the destination proves the destination holds the manifest's +content: an object that changes between the two reads cannot be smuggled past a check that +happened before it. A size-only check accepted any file of the right length, which is not a +weaker version of the same guarantee - it is a different and weaker one. + +The choice was **verify-while-copying**, not verify-then-copy. The performance consequence is +worth stating precisely, because this path already pays a full re-hash of every input: + +- Before: the pre-flight `blobs.verify_existing(digest)` re-hashes every referenced blob (one + read, one SHA-256 pass), and `materialize_tree` then re-reads the object to copy it (one read, no + hash). +- After: the pre-flight is unchanged, and the copy computes a SHA-256 pass over the bytes it + forwards. The number of reads of the object file and the bytes moved are **unchanged**; what is + added is one SHA-256 computation over the copied bytes. +- A verify-then-copy implementation would have added a *third* read of every object file: hash the + file, close it, open it again, copy it. + +So the recorded property - "blob download and workspace materialization both pay a full re-hash of +every input" - remains true, and is now bound to the bytes actually written rather than to a +separate earlier read. The cost is CPU, not I/O. The bounds are unchanged: no quota, size, or entry +count moved, and the staging/rename protocol, the `0600`/`0700` permissions, the symlink refusal +and the staging cleanup behaviour are all as they were. **Symlink policy: materialization never creates a symlink.** No code path in `materialize_tree` calls `symlink`, and a symlinked *parent* cannot exist because the staging root is fresh, 0700, and @@ -535,9 +629,12 @@ startup, so a crash mid-execution cannot leave a permanently live reference. ### Bounded cleanup -`ArtifactStore::garbage_collect(now_unix_ms, limit, dry_run)` (`artifact.rs:186-223`) runs three -bounded statements: count all expired, count the bounded candidate window (`ORDER BY -expires_unix_ms LIMIT limit`), and - when not a dry run - delete that window. +`ArtifactStore::garbage_collect(now_unix_ms, limit, dry_run)` (`artifact.rs:186-223`) selects the +bounded candidate window through the module constant `ARTIFACT_CANDIDATES_SQL` +(`SELECT artifact_id FROM artifacts WHERE expires_unix_ms <= ?1 ORDER BY expires_unix_ms LIMIT ?2`) +and - when not a dry run - deletes exactly the rows that window named. The constant is the only +place the artifact candidate predicate is written; `artifact::preview_gc` evaluates the same +statement against a read-only connection. `ArtifactGcReport { candidate_artifacts, deleted_artifacts }` (`artifact.rs:54-57`), where `deleted_artifacts` is the bounded candidate count, not a measured row count. @@ -566,6 +663,21 @@ reference rows expirable; blob GC runs last and picks up everything that became blob pass is the only one that takes `BlobStore::write_lock`, so it is the one that can block behind an in-flight upload. +**The operator's path and the in-process path.** `eggworkd gc` runs outside the node: it takes the +exclusive maintenance lock (so it refuses to race a running node), opens the three stores, and +either previews or applies. `NodeServer::collect_garbage` runs *inside* the node against the +already-open store instances. They are separate entry points and are **not** unified, for a reason +that is not about the predicate: the operator path's defining property is that it takes an +exclusive lock and therefore refuses to run against a live node, while the in-process path's +defining property is that it runs against the live store. Merging them would give up one of those +two properties. + +What *is* unified is the candidate predicate. Both paths call the owner collectors, and the owner +collectors and the operator's preview all evaluate the same module constants +(`UNREFERENCED_CANDIDATES_SQL`, `WORKSPACE_CANDIDATES_SQL`, `MANIFEST_CANDIDATES_SQL`, +`ARTIFACT_CANDIDATES_SQL`), so there is no second place where the answer could differ. The +in-process path is not exposed as a remote route. + ## Bounds and quotas | Constant | Value | Location | What it bounds | @@ -727,6 +839,12 @@ How a caller distinguishes the three cases: | Expired artifacts are invisible, then deleted | `artifact.rs:132`, `artifact.rs:168`, `artifact.rs:186-223` | `artifact.rs:804`; `lib.rs:3399` | | Capture is all-or-nothing w.r.t. records | retain before insert (`artifact.rs:311-322`) | `artifact.rs:753` | | Retention cannot stay pinned after a crash | `workspace.rs:667-696`, `workspace.rs:518-533` | `workspace.rs:1430`; `workspace.rs:1497` | +| The GC preview and the GC apply select the same candidates | `UNREFERENCED_CANDIDATES_SQL` / `WORKSPACE_CANDIDATES_SQL` / `MANIFEST_CANDIDATES_SQL` / `ARTIFACT_CANDIDATES_SQL` in the owner modules; the operator holds no candidate predicate | `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` (`operations.rs`); `gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes`; `gc_preview_and_apply_agree_when_the_store_has_no_expired_references`; `the_operator_module_contains_no_candidate_predicate_of_its_own` (`tests/gc_preview_parity.rs`) | +| A candidate is selected on the reference rows, not on the counter | `UNREFERENCED_CANDIDATES_SQL` (`NOT EXISTS (SELECT 1 FROM blob_references ...)`) | `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` (`operations.rs`) | +| The GC preview does not create or reconcile a store | `blob::preview_gc` / `workspace::preview_gc` / `artifact::preview_gc` open the metadata database `SQLITE_OPEN_READ_ONLY`; the owner `open` functions create and reconcile | `gc_preview_does_not_create_a_store_that_does_not_exist` (`operations.rs`) | +| The store's metadata file name and the blob layout are written once | `blob::metadata_path`, `workspace::metadata_path`, `artifact::metadata_path`, `blob::shard_path`, `blob::object_path` | `the_operator_module_contains_no_candidate_predicate_of_its_own` (`tests/gc_preview_parity.rs`); `inspect_blob_resolves_the_object_through_the_store_path_ownership` (`operations.rs`) | +| The manifest owner id has one producer | `manifest_owner_id_for_key` / `manifest_owner_id` (`workspace.rs`) | `manifest_owner_id_has_one_producer_for_validated_and_string_principals` (`workspace.rs`); `manifest_gc_releases_the_reference_for_an_unparseable_stored_principal` (`workspace.rs`) | +| Materialized bytes match the manifest digest, not just its length | `BlobStore::copy_verified` (hash over the copied stream) | `materialize_tree_refuses_blob_bytes_that_do_not_match_the_manifest_digest` (`workspace.rs`) | ## Test coverage @@ -742,7 +860,7 @@ and its row deleted, `.part-` files swept at reopen, and `find_missing` reportin as missing afterwards. That one test covers digest mismatch, quota exhaustion, corruption/quarantine, and startup cleanup. -**`workspace.rs` (10 tests).** Exact tree materialization with 0600/0700 permissions and fenced +**`workspace.rs` (13 tests).** Exact tree materialization with 0600/0700 permissions and fenced resolution (1002); missing blobs and symlink manifests never producing a ready workspace (1088); concurrent same-identity materialization plus recovery of unready state (1145); quota checked *before* materialization (1194); retention GC preserving a live workspace and later reclaiming its @@ -752,6 +870,50 @@ expired base behaving as missing and GC releasing the blobs it pinned (1430); a is missing being reaped with crash/reopen reconciliation (1497); and 12-way concurrent derived materialization with conflict fencing and invalid patches (1543). +Three more cover the store-ownership and byte-verification properties: +`materialize_tree_refuses_blob_bytes_that_do_not_match_the_manifest_digest` corrupts a stored +object **in place, keeping its length**, and asserts the materializer refuses it (`InvalidBlob`) +and that the unverified bytes do not survive into the tree - a size-only check would have copied +them; the same test also asserts that correct bytes still materialize. +`manifest_owner_id_has_one_producer_for_validated_and_string_principals` asserts that the +validated-principal and string-keyed entry points produce the same composite, including for a +principal that itself contains a colon. `manifest_gc_releases_the_reference_for_an_unparseable_stored_principal` +seeds a retained-manifest row whose stored principal cannot be parsed and asserts the GC still +deletes the row and releases the blob pin. + +**`operations.rs` (GC preview).** The preview fixture builds the three stores through their owner +modules, so it is a real store and not a hand-built database shaped to a predicate. +`garbage_collection_preview_reads_only_and_reports_bounds` asserts the preview honours its bound +(one candidate at `limit = 1`, the full census at `limit = 8`), reports nothing as deleted, and +leaves an in-flight `.part-` upload untouched. +`gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` seeds a store +whose `reference_count` counter has drifted from its reference rows - two blobs with a live +reference row and a counter of zero, one blob with no reference rows and a counter of one - and +asserts the operator's preview reports exactly the owner's canonical candidate set. The fixture is +asymmetric on purpose: the two predicates would otherwise produce the same *count* and differ only +in membership. +`gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes` asserts the preview's set is +a subset of what the apply pass removes, and that the difference is exactly the blob that became +unreferenced because its expired reference was swept in the same pass. +`gc_preview_and_apply_agree_when_the_store_has_no_expired_references` asserts the two sets are +*equal* when the store holds no expired references. +`gc_preview_does_not_create_a_store_that_does_not_exist` points the preview at a store that does +not exist, asserts it fails with a typed error, and asserts that the blob root, the workspace root +and the database - and the database's parent directory - are still absent afterwards; the same +test then performs the creating open the preview must not use, to show the assertion has teeth. +`inspect_blob_resolves_the_object_through_the_store_path_ownership` resolves an object in a real +store and asserts a recorded size that disagrees with the file's actual length is a data error; +`inspect_blob_refuses_a_symlinked_shard_or_object` (unix) asserts a symlinked shard directory and a +symlinked object file are both refused. + +**`tests/gc_preview_parity.rs` (3 tests).** A structural guard that keeps the two paths from +drifting apart again: the operator module's production code must not spell a reclamation predicate, +the candidate ordering, a store metadata file name or the shard layout, and the operator's preview +function must contain no SQL and open no store. The guard is precise - it does not forbid SQL in +general, because the inspection verbs legitimately read a single record by id - and it does not +scan the test module, because a fixture has to reach the store's tables to seed the drifted states +the behavioural tests need. + **`artifact.rs` (6 tests).** Only declared files captured with content streaming back verified (577); missing required and symlinked outputs failing with no records published (663); a disappearing output and a zero-quota store both failing without publishing records (753); retention references @@ -786,8 +948,15 @@ runner's confinement to the materialized root. `manifest_orphan_sweep_reaches_owners_past_the_first_page`, which pins the resume cursor and the wrap-back-at-end behaviour. Unbounded `retained_manifests` growth and a hardlink-based quota bypass remain uncovered. -- Nothing in `crates/eggwork-server/tests/` touches the data plane: `installed_qualification.rs` and - `release_contract.rs` are the only integration files. +- Nothing in `crates/eggwork-server/tests/` touches the data plane *behaviourally*: the only + integration file that reaches into it is `gc_preview_parity.rs`, and it is a structural guard + over the operator module's source rather than a behavioural test. +- The materializer's byte verification adds one SHA-256 computation over the copied bytes on top + of the pre-flight re-hash. The number of reads and the bytes moved are unchanged - a + verify-then-copy implementation would have added a third read of every object file - but the + hashing CPU for the materialization step roughly doubles. The recorded property "blob download + and workspace materialization both pay a full re-hash of every input" is unchanged and is now + bound to the bytes actually written. - Recorded evidence: [001](../plans/closure/workspace-artifact-transport/001-status.md) through [004](../plans/closure/workspace-artifact-transport/004-status.md); 004 records `cargo test --workspace --all-targets` as 108 passed, 1 ignored, 8 suites, and enumerates the diff --git a/architecture/operations-cli.md b/architecture/operations-cli.md index ce82f4a..a410290 100644 --- a/architecture/operations-cli.md +++ b/architecture/operations-cli.md @@ -402,8 +402,8 @@ walks `blob_root` and `workspace_root` iteratively with no limit, summing file l skipping symlinks (it checks `file_type().is_symlink()` and `continue`s, so a symlink is neither followed nor counted). Execution and artifact sizes instead use `file_family_bytes`, which sums the main file plus `-wal` and `-shm` siblings — so the reported execution -footprint includes un-checkpointed WAL. The artifact database is -`database_path.with_extension("artifacts.sqlite")`. `filesystem_free_bytes` is `None` when +footprint includes un-checkpointed WAL. The artifact database path is +`artifact::metadata_path(database_path)`. `filesystem_free_bytes` is `None` when the measurement fails, and quotas are echoed so the operator computes utilisation — the CLI does not. @@ -430,12 +430,16 @@ operator verbs. The three `inspect_*` functions each return `ResourceInspection { kind, id, metadata }` where `kind` is a `&'static str` and `metadata` is a free-form `serde_json::Value`: -- `inspect_blob` parses a `BlobDigest`, resolves the two-hex-character shard directory, - rejects a symlinked shard or a symlinked blob file, reads the blob's `size_bytes` and - `reference_count` from the blob store's `metadata.sqlite`, and **cross-checks the - recorded size against the file's actual length**, reporting `OperationsError::Data` on - mismatch. It is therefore a corruption check, not just a lookup. Reveals size, reference - count, and stored-ness. Bounded to one shard entry. +- `inspect_blob` parses a `BlobDigest`, resolves the shard directory and the object path + through the blob store's own path ownership (`blob::shard_path` and `blob::object_path` - + pure functions of `(root, digest)`), rejects a symlinked shard or a symlinked blob file, + reads the blob's `size_bytes` and `reference_count` from the blob store's metadata + database, and **cross-checks the recorded size against the file's actual length**, + reporting `OperationsError::Data` on mismatch. It is therefore a corruption check, not + just a lookup. Reveals size, reference count, and stored-ness. Bounded to one shard + entry. It resolves the object *without opening the store*: `BlobStore::open` would + create the root and the metadata database when absent and sweep stale part files, and + an inspection verb must not bring a store into being or reconcile one that exists. - `inspect_workspace` reads one row: `state`, `logical_bytes`, `manifest_digest`, `expires_unix_ms`. Single indexed query. - `inspect_artifact` reads `record_json` and deserializes the full @@ -444,7 +448,9 @@ where `kind` is a `&'static str` and `metadata` is a free-form `serde_json::Valu All three read only, and all three map a missing or unreadable resource to `OperationsError::NotFound`, which the binary flattens to "resource was not found or could -not be inspected" — indistinguishable from the outside. +not be inspected" — indistinguishable from the outside. The store metadata file names are +not spelled here: they are resolved through `blob::metadata_path`, +`workspace::metadata_path` and `artifact::metadata_path`, which are their owners. ## Garbage collection @@ -452,16 +458,38 @@ not be inspected" — indistinguishable from the outside. `1..=MAX_GC_BATCH` (1024) and then splits. **The default is a read-only preview.** Without `--apply`, `dry_run` is true and -`dry_run_gc` runs a fixed set of read-only aggregate queries: expired workspaces with a -count and summed `logical_bytes`; expired retained manifests; expired artifacts; expired -blob *references*; and unreferenced blobs (`reference_count = 0`, ordered by -`last_used_unix_ms`) with a count and summed `size_bytes`. All except the manifest query -are bounded by `LIMIT ?`; the manifest query is wrapped in `unwrap_or(0)` with an explicit -comment that older stores predate the retained-manifest cache and the preview should -report zero rather than fail. All counts are `.max(0) as u64`, and every `*_deleted` field -is `0`. **What the limit implies:** the preview is a bounded *sample* of the oldest -eligible entries, not an exhaustive census. A nonzero count proves there is garbage; a -zero count does not prove there is none when the eligible set exceeds the limit. +`dry_run_gc` asks each owner module for the candidates the collector would act on: +expired workspaces with a count and summed `logical_bytes`; expired retained manifests; +expired artifacts; expired blob *references*; and unreferenced blobs with a count and +summed `size_bytes`. The operator module holds **no** candidate predicate and **no** SQL of +its own: it calls `blob::preview_gc`, `workspace::preview_gc` and `artifact::preview_gc`, +which evaluate the same canonical statements the collectors evaluate. All candidate +queries are bounded by `LIMIT ?`; the manifest query tolerates a store that predates the +retained-manifest cache and reports zero manifest candidates for it rather than failing the +whole preview. Every `*_deleted` field is `0`. **What the limit implies:** the preview is a +bounded *sample* of the oldest eligible entries, not an exhaustive census. A nonzero count +proves there is garbage; a zero count does not prove there is none when the eligible set +exceeds the limit. + +**The preview does not open the stores.** `BlobStore::open`, `WorkspaceManager::open` and +`ArtifactStore::open` all create and reconcile — they create the root and the metadata +database when absent, and they sweep stale part files and unmatched rows. A preview that +opened a store would therefore mutate the store it reports on, and against a store that does +not exist yet it would bring one into being. So the preview reaches the owner modules +through entry points that open the metadata database `SQLITE_OPEN_READ_ONLY` and evaluate +the canonical statement directly. The consequence for the operator: **`eggworkd gc` against +a store that does not exist fails with a typed error rather than reporting zero +candidates**, and it leaves the filesystem exactly as it found it. + +**Preview and apply answer the same question.** The preview evaluates the candidate +statement *before* the expired blob references are deleted; the apply pass evaluates it +*after*. The preview's set is therefore a **subset** of what the apply pass removes, and +the difference is exactly the blobs that became unreferenced because their expired reference +was swept in the same pass. When the store holds no expired references, the two select at +the same point and the sets are **equal**. This used not to hold: the preview carried its +own hand-copied copy of the blob candidate predicate and selected on the `reference_count` +counter while the collector selected on the reference rows, so the preview could report a +candidate the apply pass would not remove, and miss one it would. **Applying takes an exclusive lock, which is why it cannot run against a live node.** `acquire_maintenance_lock` opens `database_path.with_extension("lock")` (mode `0o600`) @@ -474,16 +502,19 @@ generic "bounded garbage collection failed", which is unfortunate but not wrong. contrast with the live path matters: `NodeServer::collect_garbage` runs inside the node, where the lock is already held and coordination is internal. So there are two GC paths with the same report shape and different preconditions — do not conclude from the shared -`NodeGcReport` that the offline and online paths are interchangeable. +`NodeGcReport` that the offline and online paths are interchangeable. What they *do* share +is the candidate predicate: both call the owner collectors, so the in-process path and the +operator's path cannot disagree about what is collectable. The applied path is also **not exhaustive**: each of the four stores is asked to collect `now, limit, false`, so one invocation removes at most `limit` items per store (up to 1024) and repeated invocations are how a large backlog is drained. **Reference and execution protection** is inherited from the stores themselves: blob -eligibility is `reference_count = 0` (a referenced blob is never a candidate), workspaces -must be past `expires_unix_ms`, and running executions keep their workspaces and blobs -referenced. This file does not add its own active-execution filter to GC — that +eligibility is the *absence of a reference row* (a referenced blob is never a candidate, +and the trigger-maintained `reference_count` counter is deliberately not consulted), +workspaces must be past `expires_unix_ms`, and running executions keep their workspaces +and blobs referenced. This file does not add its own active-execution filter to GC — that protection lives in the store implementations ([data-plane.md](data-plane.md), [storage-journal.md](storage-journal.md)). Note that `gc` is a *separate* verb from `drain`: `eggworkd gc` does not set the drain marker, so the operator must reason about @@ -598,7 +629,9 @@ be able to tell them apart from the JSON alone, since the exit code is 2 in ever | Execution listings are bounded and paginate | `MAX_EXECUTION_PAGE`, `load_snapshots` `LIMIT 2049` + `Bounds` | `execution_listing_is_bounded_and_paginates_over_durable_records` | | Symlinks are never followed when measuring a tree | `tree_bytes` `file_type().is_symlink()` check | `tree_size_never_follows_symlinks` | | The reported metric set is fixed and bounded | `METRIC_NAMES` overlay filter | `metrics_report_uses_a_fixed_bounded_counter_set` | -| GC preview is read-only and reports its bound | `dry_run_gc` aggregate queries; no stores opened | `garbage_collection_preview_reads_only_and_reports_bounds` | +| GC preview is read-only and reports its bound | `dry_run_gc` asks the owner modules for their candidate sets; no store is opened | `garbage_collection_preview_reads_only_and_reports_bounds`; `gc_preview_does_not_create_a_store_that_does_not_exist` | +| GC preview and GC apply select the same candidates | the owner modules' canonical candidate statements; the operator holds no candidate predicate | `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter`; `gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes`; `gc_preview_and_apply_agree_when_the_store_has_no_expired_references`; `the_operator_module_contains_no_candidate_predicate_of_its_own` (`tests/gc_preview_parity.rs`) | +| The operator does not spell a store's file name or the blob layout | `blob::metadata_path`, `workspace::metadata_path`, `artifact::metadata_path`, `blob::shard_path`, `blob::object_path` | `the_operator_module_contains_no_candidate_predicate_of_its_own` (`tests/gc_preview_parity.rs`); `inspect_blob_resolves_the_object_through_the_store_path_ownership` | | `gc --apply` cannot race a running node | `acquire_maintenance_lock` `try_lock_exclusive` | `applying_gc_refuses_to_race_a_running_node` | | The drain marker survives a process restart and `undrain` removes it | `set_persistent_drain` temp+rename+fsync; `NotFound` tolerated on removal | `drain_state_survives_process_restart_and_undrain_removes_marker` | | Quiescence fails closed on unreadable state | `active_execution_count` returning `usize::MAX` | No test in this file; exercised by [release-qualification.md](release-qualification.md) | diff --git a/architecture/runner-execution.md b/architecture/runner-execution.md index 9204c37..aae9040 100644 --- a/architecture/runner-execution.md +++ b/architecture/runner-execution.md @@ -9,7 +9,7 @@ Source of truth: [`crates/eggwork-runner/src/lib.rs`](../crates/eggwork-runner/s **Owns** - OS child creation, process-group isolation, and process-tree termination/reaping. -- The full environment contract: clearing the inherited environment and rebuilding it from a conservative baseline plus a deny-list filter. +- The full environment contract: clearing the inherited environment and rebuilding it from the node's own baseline under the shared environment policy — a deny-list filter, a node-owned-key rule, and one builder shared by both launch paths. - Bounded stdin writes and concurrent stdout/stderr drain with head/tail retention and total/omitted byte accounting. - Timeout, cancellation, and terminate-on-overflow races, and the resulting `TerminationReason`. - Sandbox and OS resource-control *request/outcome* plumbing, plus the runtime capability probe that backs node feature advertisement. @@ -132,11 +132,11 @@ Only `prepare` is required. `execution_capabilities` and `sandbox_helper_path` a - A `tempfile::Builder::new().prefix("eggwork-sandbox-").tempdir()` is created and chmod-ed to `0700` (line 1691). - `spec.json` and `status.sock` are named inside it; a `tokio::net::UnixListener` is bound to `status.sock`. **The runner is the socket server and the helper connects to it** — the target never has the socket. -- The launch environment is rebuilt from scratch: `PATH=/usr/bin:/bin`, `LANG=C.UTF-8`, `LC_ALL=C.UTF-8`, `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`, then the request's environment filtered through `denied_environment_key`, then `EGGWORK_EXECUTION_ID` and `EGGWORK_EXECUTION_GENERATION` when provenance carries them. +- The launch environment is rebuilt from scratch by the same `build_child_environment` the direct path uses: the node's baseline (`PATH=/usr/bin:/bin`, `LANG=C.UTF-8`, `LC_ALL=C.UTF-8`, `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`), then the request's environment with denied keys dropped and node-owned keys replaced by the node's values, then `EGGWORK_EXECUTION_ID` and `EGGWORK_EXECUTION_GENERATION` when provenance carries them. Sharing the builder is what stops the two launch paths from disagreeing. - `SandboxLaunchSpec { schema_version: 1, profile, root, cwd, argv, environment, resource_memory_bytes, resource_cpu_millis, resource_pids }` is serialized with `serde_json` and rejected above 1 MiB. The three resource fields are populated only when `resources_applied`, using `.then_some(...).flatten()` so a `NotRequested` dimension stays `None`. - The spec is written with `OpenOptions::new().write(true).create_new(true).mode(0o600)` — create-new, so a pre-existing file at that path cannot be followed. -`SandboxChannel::command` (line 1779) is then the actual child command: `Command::new(helper_path) --spec --status `, `current_dir` set to the spec's parent, all three stdio handles piped, `kill_on_drop(true)`, `env_clear()` followed by only `PATH`, `LANG`, `LC_ALL`. The environment the *target* will see is not the helper's environment — it is the `environment` array inside the spec, which the helper applies itself after `env_clear()`. +`SandboxChannel::command` is then the actual child command: `Command::new(helper_path) --spec --status `, `current_dir` set to the spec's parent, all three stdio handles piped, `kill_on_drop(true)`, `env_clear()` followed by the node's own baseline. The helper must not inherit the daemon's `LD_*`, `GIT_*` or cloud variables while it is parsing a specification that a deny-list was supposed to keep clean. The environment the *target* will see is not the helper's environment — it is the `environment` array inside the spec, which the helper applies itself after `env_clear()`. `SandboxChannel::wait` (line 1798) is the handshake, and it is the reason required isolation cannot be spoofed by target output. It selects on cancellation or `timeout(5s, listener.accept())`, then reads one status byte with a 5 s timeout: @@ -275,15 +275,27 @@ result = child.wait() => Some((Exited, status?, error?)), ### Environment clearing and the conservative baseline -`direct_command` (line 1494) never inherits the caller's environment. `command.env_clear()` is unconditional, then: +The runner builds a child's environment in exactly one place — `build_child_environment` — and **both** of its launch paths use it: `direct_command` for the unconfined path, and `SandboxChannel::new` for the launch specification the sandbox helper reads. That is the whole point of the function: the two paths cannot disagree about what a child sees. -`baseline_child_environment()` (line 1563) — always: `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`. On non-Windows: `PATH=/usr/bin:/bin`, `LANG=C.UTF-8`, `LC_ALL=C.UTF-8`. On Windows: `SystemRoot` and `windir` (from the parent, defaulting to `C:\Windows`) and `PATH=\System32;`. +`direct_command` never inherits the caller's environment. `command.env_clear()` is unconditional, then the environment is assembled in three steps. -Then the request's environment, each entry filtered through `denied_environment_key` (line 1465), which upper-cases the key and rejects exact matches or prefixes of: `LD_`, `DYLD_`, `PATH`, `IFS`, `SHELLOPTS`, `CDPATH`, `BASH_ENV`, `ENV`, `PYTHONPATH`, `PYTHONHOME`, `NODE_OPTIONS`, `RUBYOPT`, `PERL5OPT`, `GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_CONFIG`, `GIT_CONFIG_`, `AWS_`, `AZURE_`, `GOOGLE_`, `SSH_AUTH_SOCK`. This is a *deny* filter, not an allow list — but combined with `env_clear()` the effective result is allow-shaped: only baseline plus explicitly requested, non-denied keys reach the child. `PATH` is denied from the request precisely because the baseline already fixed it; letting a request override `PATH` would hand it interpreter resolution. +**1. The node's baseline goes in first.** `baseline_child_environment()` returns the node-owned baseline: on Unix `PATH=/usr/bin:/bin`, `LANG=C.UTF-8`, `LC_ALL=C.UTF-8`, `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`; on Windows `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`, plus `SystemRoot` and `windir` (from the parent, defaulting to `C:\Windows`) and `PATH=\System32;`. The Unix baseline is the shared environment policy's, read from the generated `environment_policy` module rather than written out here, so the runner and the sandbox helper cannot disagree about it. The Windows baseline is runner-local, because its values come from the parent process at spawn time and the sandbox helper is Linux-only so it never sees a Windows launch. -Finally provenance: `EGGWORK_EXECUTION_ID` (from `ExecutionId::as_str`) and `EGGWORK_EXECUTION_GENERATION` (from `ExecutionGeneration::get()`) when present. This is the documented "propagate neutral execution provenance through environment only where safe" of plan 002 §3.12 — the IDs are opaque strings with no routing authority. +**2. The request's environment, under the shared policy.** Each entry is classified by the generated `environment_policy` module, whose single owner is `crates/eggwork-runner/policy/environment-policy.toml`: -The `#[cfg(windows)]` branch was originally unreachable: `run` refused on non-Unix before a command was ever built, so the shaping could not and did not fix Windows qualification on its own. Foundation M004 removed that refusal, which makes the branch load-bearing — `SystemRoot` is what the Windows loader needs, and `PATH` is what resolves `cmd.exe`. `windows_process_tree.rs::environment_is_the_documented_baseline_and_leaks_nothing` asserts both the baseline contents and that no ambient daemon variable reaches the target. +- **Denied** — the caller may not set this key at all. The runner **drops** it, silently. This is the *request-normalisation boundary*: a hardened environment has to be a property of the node rather than something the caller has to get right, and the caller is not told. The list is matched case-insensitively by exact name or prefix: `LD_`, `DYLD_`, `PATH`, `IFS`, `SHELLOPTS`, `CDPATH`, `BASH_ENV`, `ENV`, `PYTHONPATH`, `PYTHONHOME`, `NODE_OPTIONS`, `RUBYOPT`, `PERL5OPT`, `GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_CONFIG`, `GIT_CONFIG_`, `AWS_`, `AZURE_`, `GOOGLE_`, `SSH_AUTH_SOCK`. +- **Node-owned (reserved)** — the node sets this key itself, so the caller's value is **discarded in favour of the node's**. The node-owned class is the node's own baseline, and the baseline is platform-shaped: on Unix it is the policy's `RESERVED_KEYS`, and on Windows it is the runner-local baseline's keys. The match is case-insensitive, so a caller's `lang` is the same key as the node's `LANG`. +- **Caller-controlled** — everything else passes through. A repeated key is resolved to its **last** value, so the launch specification can never carry a duplicate key. + +This is a *deny* filter over a baseline, not an allow list — but combined with `env_clear()` the effective result is allow-shaped: only the node's baseline plus explicitly requested, non-denied keys reach the child. + +**3. Provenance last.** `EGGWORK_EXECUTION_ID` (from `ExecutionId::as_str`) and `EGGWORK_EXECUTION_GENERATION` (from `ExecutionGeneration::get()`) when present. This is the documented "propagate neutral execution provenance through environment only where safe" of plan 002 §3.12 — the IDs are opaque strings with no routing authority — and they are appended after the caller's entries so a caller cannot forge them. + +**The reserved-key rule is what closes the collision hole.** Before it, the launch-specification builder started from the fixed baseline and then *appended* every non-denied caller key, and none of the baseline keys except `PATH` was denied. A caller that set `LANG` therefore produced a specification with **two** `LANG` entries; the helper refuses a specification with duplicate keys; the runner read that refusal as a pre-target setup failure and — for a **best-effort** request only — rewrote the sandbox outcome to `NotApplied` and re-spawned the target directly with no Landlock ruleset at all. The observable result was a successful, entirely unconfined execution whose only record of the degradation was a `NotApplied` in the terminal snapshot. The `Required` path was unaffected and still failed closed. + +**The `PATH` contract.** `PATH == /usr/bin:/bin` is an enforced contract on both sides: the runner guarantees the value in the child environment and in the launch specification, and the sandbox helper refuses a specification whose `PATH` differs. It is a **Linux/Unix** contract — the Windows baseline is explicitly outside it, so the Windows `PATH` must not be "fixed" to the Unix value. + +The `#[cfg(windows)]` branch was originally unreachable: `run` refused on non-Unix before a command was ever built, so the shaping could not and did not fix Windows qualification on its own. Foundation M004 removed that refusal, which makes the branch load-bearing — `SystemRoot` is what the Windows loader needs, and `PATH` is what resolves `cmd.exe`. `windows_process_tree.rs::environment_is_the_documented_baseline_and_leaks_nothing` asserts both the baseline contents — taken from the runner's own `baseline_environment_keys()`, not from a second hand-written list — and that no ambient daemon variable reaches the target. ### Bounded capture: head and tail @@ -467,7 +479,7 @@ Drop-safety is partial by design. Every `Command` sets `.kill_on_drop(true)`, so | Only approved crates create OS children | `scripts/check_execution_ownership.py` allowlist; `process_group(0)` + `spawn` in `direct_command`/`SandboxChannel::command` | guard script's own negative self-test; `cancellation_before_spawn_and_spawn_failure_are_typed` (typed `Spawn`) | | A request cannot bypass protocol bounds | private fields; `RunnerRequest::validate` called at the top of `run` (line 1152) | indirect only — see Test coverage | | cwd is confined to the authorized root | `validate`: canonicalize + `starts_with(&root)` | `cwd_is_confined_and_output_limit_terminates` (positive `pwd`); negative symlink case lives in `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` | -| Child environment is cleared and rebuilt | `env_clear()` in `direct_command`; `baseline_child_environment`; `denied_environment_key` | `captures_exit_stdin_and_sanitizes_environment` asserts `LD_PRELOAD` arrives unset | +| Child environment is cleared and rebuilt | `env_clear()` in `direct_command`; `build_child_environment`; `baseline_child_environment`; the shared `environment_policy` module | `captures_exit_stdin_and_sanitizes_environment` asserts `LD_PRELOAD` arrives unset; `crates/eggwork-runner/tests/environment_policy.rs` asserts the node-owned keys and the deny-list | | Stdin is bounded and then closed | `StdinPolicy::validate` + `MAX_STDIN_BYTES`; `write_all` then `drop` | `captures_exit_stdin_and_sanitizes_environment` (bytes path) | | Capture is bounded with accurate totals | `BoundedCapture::push` | `output_capture_retains_head_tail_with_totals`; `bounds_capture_and_streaming_under_slow_receiver` | | Pipes stay drained under a slow consumer | `try_send` + drop counter in `spawn_reader` | `bounds_capture_and_streaming_under_slow_receiver` (asserts `stream_chunks_dropped > 0` with a 1-slot channel) | @@ -545,13 +557,15 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu `SandboxChannel` internals are covered from the helper crate's integration test, `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`, which drives the runner's public API: outside read/write denial, helper trust rejections (missing/wrong/symlinked), workspace and cwd symlink escapes, timeout and cancellation reaping the helper's own process group, required memory/PID/CPU enforcement and classification, concurrent cgroup scope isolation, and `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target`. +`crates/eggwork-runner/tests/environment_policy.rs` is the environment-policy suite on the runner's side: it asserts that the shared policy is reachable from the runner's public API, that the node-owned class and the node-owned baseline are the same list, that the baseline the runner installs is the policy's baseline, and — through a real child — that a caller's value for a node-owned key does not reach the child while a denied key does not either and a caller-controlled key does. The other half of that proof is `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs`, which drives the real helper binary: it compares the two generated copies of the policy element by element, drives the helper with a launch specification for every probe key and compares its accept/refuse decision with what the runner's copy of the policy says, proves that a caller-supplied node-owned key keeps the execution confined, and proves that the direct path and the helper path build the same environment. + **Thin areas, honestly:** - **No unit test rejects a bad `RunnerRequest`.** Every `RunnerError::InvalidRequest` branch — empty/NUL/oversized argv, environment count and size bounds, `=` in an environment name, `capture_limit` over 16 MiB, `event_chunk_bytes` of 0, zero or over-maximum timeout, stdin over 4 MiB — is unexercised. The only escaping test is `cwd` under a valid root. - **No test covers a cwd that escapes root** (`..`, absolute, or a symlink) at the runner level; that assertion lives in the helper crate's test, and only for the symlink form. - **No test covers `RunnerError::UnsupportedPlatform`.** The path is now `cfg(not(any(unix, windows)))`, which is not a release target, so the refusal stays asserted only by code reading. Windows no longer takes this path. - **Pre-run Job Object assignment is a property of the dependency, not of a test.** `process-wrap` adds `CREATE_SUSPENDED`, assigns, and resumes inside `spawn`; the suite can observe the consequences (a descendant created in the target's first moments is owned, a spawn failure leaves nothing running) but cannot observe the assignment itself from outside the process without Win32 tracing. That is stated rather than glossed: the evidence is "no descendant ever escaped", not "the kernel was entered in this state". -- **The baseline environment is only tested negatively.** `captures_exit_stdin_and_sanitizes_environment` proves `LD_PRELOAD` is stripped; nothing pins the exact baseline set, the `denied_environment_key` list, or the `PATH` special case (baseline sets it, the deny list rejects a request-supplied one). +- **The baseline environment is only tested negatively.** `captures_exit_stdin_and_sanitizes_environment` proves `LD_PRELOAD` is stripped. The exact baseline set, the deny-list, and the `PATH` special case are now pinned by `crates/eggwork-runner/tests/environment_policy.rs` and by the sandbox helper's parity suite, but only on Unix: the Windows baseline has no coverage outside the `windows-runner` job. - **`SystemdCgroupBackend::wrap` argv construction is untested** — the `--property` rendering, the `MemoryMax`/`MemorySwapMax=0` pairing, the `CPUQuota` millis-to-percentage conversion, `resource_unit_name` uniqueness, and the `--user` selection are all unasserted. The resource *enforcement* tests live in the helper crate and depend on a systemd-capable host. - **`BoundedCapture` is tested at exactly one limit (6).** Odd limits, `limit == 1`, and `limit == 0` are unverified, as is the head/tail split when a single `push` straddles the boundary. - **`stream_chunks_dropped` semantics are untested** beyond `> 0`; the closed-channel case (dropping the receiver mid-run) is exercised only by `drop(rx)` after the assertion. @@ -562,7 +576,7 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu - **Descendant reaping completeness.** `killpg` only reaches processes that stayed in the child's process group. A grandchild that calls `setsid()` or `setpgid()` escapes both `terminate_group` and `kill_group`, and nothing here detects that. Plan 002 §9 says to stop rather than "pretend direct-child kill is tree cleanup" — that boundary should be re-checked against the current code, which is group-scoped, not tree-scoped. - **The best-effort respawn path re-runs argv outside the wrapper.** On `Ok(None)` or a recoverable `BeforeTarget` error, the helper child is `start_kill`ed and waited, but *its process group is not signalled* and the command is then rebuilt and spawned a second time, unwrapped. Whether a best-effort request should ever be able to produce two process creations for one execution is a policy question the code currently answers implicitly. -- **Env baseline duplication.** The baseline variable set appears twice — `baseline_child_environment()` and the hard-coded `environment` vector in `SandboxChannel::new` — and `denied_environment_key` appears here and again in the helper. Sandbox and non-sandbox children can drift apart silently, and a divergence would be a silent security difference, not a compile error. +- **Env baseline duplication — closed, but the shape of the fix matters.** The baseline variable set used to appear twice — `baseline_child_environment()` and the hard-coded `environment` vector in `SandboxChannel::new` — and the deny-list appeared here and again in the helper, so a sandbox child and a non-sandbox child could drift apart silently. Both now come from one source of truth, `crates/eggwork-runner/policy/environment-policy.toml`, generated into each crate, and one builder (`build_child_environment`) produces both launch paths' environments. What the fix does *not* do is make the deny-list exhaustive: adding a knob is still a policy decision with its own security review, and the generated copies are only as good as the source they are generated from. - **Head/tail capture correctness under concurrent drain.** `BoundedCapture::push` is byte-at-a-time and interleaves head-fill with tail-fill in one pass. Check the `div_ceil` head bias, `limit == 0`/`limit == 1` degeneracy, and that a large single read cannot produce a tail that overlaps the head. - **`stream_chunks_dropped` counts bytes, not chunks.** `dropped += bytes.len() as u64` accumulates a byte count into a field named `stream_chunks_dropped`. The value is correct as a "bytes not delivered" measure and misleading as a chunk count; either the arithmetic or the name should change. - **Trust-check TOCTOU.** `verify_trusted_helper` is a path-based `symlink_metadata` plus an ancestor walk, and the helper is executed later by path. Nothing pins an fd between check and exec, and `SandboxChannel::command()` re-resolves the path. The window is small but real, and it is the window the whole isolation story depends on. diff --git a/architecture/sandbox-helper.md b/architecture/sandbox-helper.md index 26df79d..a4a48e7 100644 --- a/architecture/sandbox-helper.md +++ b/architecture/sandbox-helper.md @@ -16,8 +16,8 @@ Crate facts: one `[[bin]]` (`path = "src/main.rs"`), `version.workspace = true`, **Does not own** -- **No execution admission.** It never decides whether a workload may run. The profile name, the resource values, the argv, the root, and the cwd were all chosen by `eggwork-runner` before the helper was spawned; `TrustedLandlockSetup::prepare` (`crates/eggwork-runner/src/lib.rs:425`) has already refused to hand over a `Required` request whose profile is not `workspace_rw` or whose helper fails `verify_trusted_helper`. -- **No lifecycle.** It does not time out, cancel, reap, or signal anything. Timeout/cancellation/termination of the *target* is the runner's, via the process group and `kill_on_drop` (`SandboxChannel::command`, `lib.rs:1779`). The helper only `wait()`s. +- **No execution admission.** It never decides whether a workload may run. The profile name, the resource values, the argv, the root, and the cwd were all chosen by `eggwork-runner` before the helper was spawned; `TrustedLandlockSetup::prepare` has already refused to hand over a `Required` request whose profile is not `workspace_rw` or whose helper fails `verify_trusted_helper`. +- **No lifecycle.** It does not time out, cancel, reap, or signal anything. Timeout/cancellation/termination of the *target* is the runner's, via the process group and `kill_on_drop` (`SandboxChannel::command`). The helper only `wait()`s. - **No policy decision about whether execution is allowed.** It applies mechanics that were already decided. Every branch that ends in `Err` is an abort, never a downgrade: nothing here can turn "required" into "best effort". - **No trust self-assertion.** The helper never states that it is trusted; the runner verifies the file and the runner alone interprets the status bytes. @@ -33,7 +33,7 @@ Crate facts: one `[[bin]]` (`path = "src/main.rs"`), `version.workspace = true`, ## Trust boundary and installation -The helper is treated as an installation-owned, trusted root (or effective-user) artifact. Trust is verified by the **runner**, in one function, `eggwork_runner::verify_trusted_helper` (`lib.rs:596`, Linux) — deliberately public so operator diagnostics report the same answer the enforcement path will give rather than a second, independently drifting copy of the policy (the doc comment says so explicitly). The Linux checks, in order: +The helper is treated as an installation-owned, trusted root (or effective-user) artifact. Trust is verified by the **runner**, in one function, `eggwork_runner::verify_trusted_helper` (the Linux variant) — deliberately public so operator diagnostics report the same answer the enforcement path will give rather than a second, independently drifting copy of the policy (the doc comment says so explicitly). The Linux checks, in order: | Check | Detail | | --- | --- | @@ -44,15 +44,15 @@ The helper is treated as an installation-owned, trusted root (or effective-user) | Parent dir | `path.parent().canonicalize()`; must be a directory, `uid ∈ {0, geteuid()}`, `mode & 0o022 == 0` | | Every ancestor | must be a directory; `uid ∈ {0, geteuid()}` **or** a root-owned sticky directory (`uid == 0 && mode & 0o1000 != 0`); `mode & 0o022 == 0` unless it is that sticky root directory | -Any failure returns `Err(String)` and the caller reacts by request severity: `Required` → `RunnerError::Setup(reason)` (execution refused), `BestEffort` → `SandboxOutcome::NotApplied { reason }` (surfaced, never described as enforced). The non-Linux variant (`lib.rs:641`) is unconditional: `Err("trusted Landlock is unsupported on this platform")`. So required isolation fails closed rather than degrading. +Any failure returns `Err(String)` and the caller reacts by request severity: `Required` → `RunnerError::Setup(reason)` (execution refused), `BestEffort` → `SandboxOutcome::NotApplied { reason }` (surfaced, never described as enforced). The non-Linux variant is unconditional: `Err("trusted Landlock is unsupported on this platform")`. So required isolation fails closed rather than degrading. `TrustedLandlockSetup::prepare` calls `verify_trusted_helper` **twice** in principle: once when resource setup was applied by `SystemdCgroupBackend` (a required-resource request refuses to continue with an untrusted helper; a best-effort one downgrades to `NotApplied`), and once for the sandbox profile. It never executes the helper during `prepare` — execution happens later, in `SandboxChannel::wait`. -The second, independent gate is the version-coherence probe, and it is not in the runner. `eggworkd deployment status` calls `check_helper_compatibility(helper_path, env!("CARGO_PKG_VERSION"))` (`crates/eggwork-server/src/deployment.rs:330` onward): a lighter duplicate of the ownership/mode/executable checks, then `eggup_core::CommandSpec::new(path).arg("--version").timeout(timeout)` run through `eggup_core::run_bounded` (cleared environment, null stdin, bounded output, timeout, kill/reap). The printed version must be non-empty, ≤ 64 bytes, free of control characters, and an **exact** match for the daemon's own crate version, otherwise `HelperCompatibility::VersionSkew { expected, found }`. `helper_satisfies_required_isolation(compatibility)` (`deployment.rs:300`) is what gates the advertised requirement. This probe is the documented ownership exception in [execution-ownership.md](execution-ownership.md): it "performs no execution admission, owns no lifecycle, and exists only so required-isolation admission can fail closed on version skew." +The second, independent gate is the version-coherence probe, and it is not in the runner. `eggworkd deployment status` calls `check_helper_compatibility(helper_path, env!("CARGO_PKG_VERSION"))` (in `crates/eggwork-server/src/deployment.rs`): a lighter duplicate of the ownership/mode/executable checks, then `eggup_core::CommandSpec::new(path).arg("--version").timeout(timeout)` run through `eggup_core::run_bounded` (cleared environment, null stdin, bounded output, timeout, kill/reap). The printed version must be non-empty, ≤ 64 bytes, free of control characters, and an **exact** match for the daemon's own crate version, otherwise `HelperCompatibility::VersionSkew { expected, found }`. `helper_satisfies_required_isolation(compatibility)` is what gates the advertised requirement. This probe is the documented ownership exception in [execution-ownership.md](execution-ownership.md): it "performs no execution admission, owns no lifecycle, and exists only so required-isolation admission can fail closed on version skew." -**Where the path comes from.** `TrustedLandlockSetup::discover_sibling()` (`lib.rs:412`) canonicalizes `std::env::current_exe()`, takes its parent, and appends `eggwork-sandbox-helper`, falling back to the bare relative name `eggwork-sandbox-helper`. The production daemon does not use that convenience: `start_server` (`operations.rs:1029`) constructs `TrustedLandlockSetup::new(helper)` from `config.sandbox_helper`, the operator-configured absolute path. Both funnel into the same `verify_trusted_helper`. +**Where the path comes from.** `TrustedLandlockSetup::discover_sibling()` canonicalizes `std::env::current_exe()`, takes its parent, and appends `eggwork-sandbox-helper`, falling back to the bare relative name `eggwork-sandbox-helper`. The production daemon does not use that convenience: `start_server` (in `crates/eggwork-server/src/operations.rs`) constructs `TrustedLandlockSetup::new(helper)` from `config.sandbox_helper`, the operator-configured absolute path. Both funnel into the same `verify_trusted_helper`. -**Release-unit consequence.** `README.md`: "Linux releases ship the daemon and its Landlock sandbox helper as one bundle from one source revision, so the pair can never drift. macOS and Windows ship the daemon only." `install_unit_matrix(helper_required)` (`deployment.rs:119`) is the machine-readable form: `MEMBER_DAEMON` → `DEST_DAEMON` is always `required: true`; `MEMBER_HELPER` → `DEST_HELPER` (`bin/eggwork-sandbox-helper`) takes `required: helper_required`, and `eggworkd` sets that to `config.sandbox_helper.is_some()` (`src/bin/eggworkd.rs:193`) — i.e. a node configured with a helper path on Linux. `crates/eggwork-server/tests/release_contract.rs::the_helper_ships_exactly_on_linux_release_targets` pins the helper to the Linux triples only and asserts `install_unit_matrix(false)` marks it not required, which is the macOS/Windows shape. `operations.rs:449` (`doctor`) and `operations.rs:1029` (`start_server`) are the two operational consumers: `doctor` reports `trusted_helper(helper)` then, only if trusted, builds a `TrustedLandlockSetup` and asks for `execution_capabilities()`; `start_server` selects `TrustedLandlockSetup` when `config.sandbox_helper` is set and `NoExecutionSetup` otherwise. +**Release-unit consequence.** `README.md`: "Linux releases ship the daemon and its Landlock sandbox helper as one bundle from one source revision, so the pair can never drift. macOS and Windows ship the daemon only." `install_unit_matrix(helper_required)` (in `crates/eggwork-server/src/deployment.rs`) is the machine-readable form: `MEMBER_DAEMON` → `DEST_DAEMON` is always `required: true`; `MEMBER_HELPER` → `DEST_HELPER` (`bin/eggwork-sandbox-helper`) takes `required: helper_required`, and `eggworkd` sets that to `config.sandbox_helper.is_some()` (in `crates/eggwork-server/src/bin/eggworkd.rs`) — i.e. a node configured with a helper path on Linux. `crates/eggwork-server/tests/release_contract.rs::the_helper_ships_exactly_on_linux_release_targets` pins the helper to the Linux triples only and asserts `install_unit_matrix(false)` marks it not required, which is the macOS/Windows shape. `doctor` and `start_server` (both in `crates/eggwork-server/src/operations.rs`) are the two operational consumers: `doctor` reports `trusted_helper(helper)` then, only if trusted, builds a `TrustedLandlockSetup` and asks for `execution_capabilities()`; `start_server` selects `TrustedLandlockSetup` when `config.sandbox_helper` is set and `NoExecutionSetup` otherwise. ## Command-line contract @@ -63,7 +63,7 @@ Two accepted argv shapes, parsed strictly. Anything else is `Err(())` → exit * | `eggwork-sandbox-helper --version` (and *no* further argument) | prints `env!("CARGO_PKG_VERSION")` to stdout, one line, exit 0. `--version` with a trailing argument is an error, not a version print. | | `eggwork-sandbox-helper --spec SPEC --status SOCK` (in that order, nothing else) | full launch path. Order is fixed: the second token must be `--status`, a fourth token must not exist. | -The runner therefore builds exactly (`SandboxChannel::command`, `lib.rs:1779`): +The runner therefore builds exactly (`SandboxChannel::command`): ``` Command::new() @@ -78,9 +78,9 @@ Command::new() `current_dir` is the `0700` temp directory, so the helper starts with the same working directory the spec file lives in and never depends on the daemon's cwd. `env_clear()` on the helper itself matters: the helper must not inherit the daemon's `LD_*`, `GIT_*`, or cloud variables while it is parsing a spec that a deny-list was supposed to keep clean. -The `--spec` path writes **nothing** to stdout or stderr. All structured output is one-byte codes on the connected `UnixStream`; the helper never logs. The runner gives the helper piped stdio (`SandboxChannel::command`, `lib.rs:1779`) and drains it with the ordinary capture machinery, so the only output an untrusted-looking helper could produce is bounded like any child's. +The `--spec` path writes **nothing** to stdout or stderr. All structured output is one-byte codes on the connected `UnixStream`; the helper never logs. The runner gives the helper piped stdio (`SandboxChannel::command`) and drains it with the ordinary capture machinery, so the only output an untrusted-looking helper could produce is bounded like any child's. -Order of operations inside `run()` (`main.rs:48`): +Order of operations inside `run()` (`linux::run`): 1. `UnixStream::connect(&status_path)` — **before** the spec is read. A missing or unconnectable socket aborts immediately, leaving the spec file untouched and no target started. 2. `read_spec(&spec_path)`; on failure write the numeric code and abort. @@ -93,15 +93,15 @@ Order of operations inside `run()` (`main.rs:48`): 9. Write `1` again (phase marker: target started), flush. 10. `child.wait()`, then write the resource bit-flags byte, then `exit_code(result)`. -**Bounded output and time.** The status protocol is a fixed one-byte-per-phase exchange; the runner wraps each phase read in `tokio::time::timeout(Duration::from_secs(5))` — `accept`, the first status byte, the second status byte — and the final resource byte in a 2 s timeout inside `SandboxSession::resource_limits_exceeded` (`lib.rs:1633`). `--version` is bounded by the deployment layer's `eggup_core::run_bounded` plus the ≤ 64-byte/no-control-character validation. Helper-side size bounds are the `MAX_*` constants in `read_spec`. +**Bounded output and time.** The status protocol is a fixed one-byte-per-phase exchange; the runner wraps each phase read in `tokio::time::timeout(Duration::from_secs(5))` — `accept`, the first status byte, the second status byte — and the final resource byte in a 2 s timeout inside `SandboxSession::resource_limits_exceeded`. `--version` is bounded by the deployment layer's `eggup_core::run_bounded` plus the ≤ 64-byte/no-control-character validation. Helper-side size bounds are the generated `MAX_*` constants; the five protocol limits come from `eggwork-core` via the generator, and `MAX_SPEC_BYTES` is helper-only. **Exit codes.** `entry()` is `std::process::exit(run().unwrap_or(125))`, so 125 means "the helper refused or could not proceed" for every cause, and is intentionally *not* a fine-grained channel: the reason is delivered on the status socket, and 125 is what remains when the socket could not even be connected. A successful run exits with the target's code: `exit_code(status) = status.code().unwrap_or_else(|| 128 + status.signal().unwrap_or(0))` — the conventional 128 + signal form for a signalled child. -**Non-Linux entry point** (`main.rs:393`): accepts `--version` alone (print version, exit 0) and otherwise exits 125. It does not link Landlock or nix and never starts anything. +**Non-Linux entry point** (the `#[cfg(not(target_os = "linux"))]` `main`): accepts `--version` alone (print version, exit 0) and otherwise exits 125. It does not link Landlock or nix and never starts anything. ## LaunchSpec -Read by `read_spec` (`main.rs:123`) from the path given by `--spec`. The runner writes it as `SandboxLaunchSpec` (`lib.rs:1605`) via `serde_json::to_vec` into `spec.json` inside a `0700` temp dir (`tempfile::Builder::new().prefix("eggwork-sandbox-")`), opened with `create_new(true)` and `mode(0o600)`; the encoded length is rejected above 1 MiB before the file is even created. +Read by `read_spec` (`linux::read_spec`) from the path given by `--spec`. The runner writes it as `SandboxLaunchSpec` via `serde_json::to_vec` into `spec.json` inside a `0700` temp dir (`tempfile::Builder::new().prefix("eggwork-sandbox-")`), opened with `create_new(true)` and `mode(0o600)`; the encoded length is rejected above 1 MiB before the file is even created. | Field | Type | Validation | | --- | --- | --- | @@ -133,7 +133,7 @@ As the runner writes it, a fully-populated spec is: } ``` -`root` is canonicalized by the runner before serialization (`lib.rs:1725`) and a failure there is `RunnerError::InvalidRoot`, so the helper's `root != spec.root` equality check (`code 15`) is a re-assertion, not the first line of defense. `resource_*` are populated only when the runner's cgroup backend actually applied them (`resources_applied.then_some(...)`, `lib.rs:1732-1749`): when the backend did not apply them, the fields serialize as `null` and the helper's verification short-circuits, so a `BestEffort` resource request that was not installed cannot make the helper refuse. +`root` is canonicalized by the runner before serialization (`SandboxChannel::new`) and a failure there is `RunnerError::InvalidRoot`, so the helper's `root != spec.root` equality check (`code 15`) is a re-assertion, not the first line of defense. `resource_*` are populated only when the runner's cgroup backend actually applied them (`resources_applied.then_some(...)`, in `SandboxChannel::new`): when the backend did not apply them, the fields serialize as `null` and the helper's verification short-circuits, so a `BestEffort` resource request that was not installed cannot make the helper refuse. **The hand-off, end to end.** @@ -147,7 +147,7 @@ As the runner writes it, a fully-populated spec is: ## Filesystem isolation (Landlock) -`restrict(&spec)` (`main.rs:186`), called only when `spec.profile.is_some()`: +`restrict(&spec)` (`linux::restrict`), called only when `spec.profile.is_some()`: ```rust let abi = ABI::V4; @@ -161,7 +161,7 @@ let mut ruleset = Ruleset::default() - **ABI**: hard-coded `ABI::V4`. There is no fallback and no downgrade: `handle_access`, `create`, every `add_rule`, every `PathFd::new`, and `restrict_self` all map to status code `2` on failure. On a kernel that does not implement V4 the helper refuses to start the target. - **Handled rights**: `AccessFs::from_all(ABI::V4)` — the full handled set for that ABI, which is what makes the model "deny by default": anything not covered by a rule is denied. - **Workspace rule is pinned to a descriptor, not a name.** `read_spec` opens `root` once, immediately after the containment checks, with `O_PATH | O_CLOEXEC` (mirroring what `PathFd::new` would have used) and hands the `File` to `restrict`, which passes it straight to `PathBeneath::new`. The object that was validated is therefore the object that is enforced. This used to re-resolve `spec.root` *by name* inside `restrict`, which left a window in which any process able to write the parent of the workspace root could replace it with a symlink; the ruleset would then grant all rights beneath the link target while still reporting `FullyEnforced`. Exploiting that needs a second process at the node's uid — the confined target cannot do it, because `workspace_rw` grants rights only *beneath* root — but it is exactly the adversary the spec file is already hardened against (reject symlink, then compare `dev`/`ino` on the descriptor actually read), and `root` was getting none of that discipline. `spec.cwd` is still resolved by name at spawn, but that is bounded: the pinned root rule denies everything outside the workspace regardless of where `chdir` lands. -- **Workspace rule**: the single `PathBeneath` rule on that pinned root descriptor with **all** handled rights, i.e. read *and* write *and* create *and* remove. This is the `workspace_rw` profile. The mapping from the public capability name to these concrete rights is: `LANDLOCK_WORKSPACE_RW_CAPABILITY` = `"isolation.landlock.workspace-rw.v1"` (`lib.rs:528`), advertised only when `verify_trusted_helper` succeeds **and** `probe_landlock_ruleset()` is true; the probe builds the identical `ABI::V4` ruleset with the identical four runtime paths and identical rights in-process but never calls `restrict_self` (`lib.rs:538` onward, including the comment that the devnull rule "must mirror the helper's null-device rule exactly"). +- **Workspace rule**: the single `PathBeneath` rule on that pinned root descriptor with **all** handled rights, i.e. read *and* write *and* create *and* remove. This is the `workspace_rw` profile. The mapping from the public capability name to these concrete rights is: `LANDLOCK_WORKSPACE_RW_CAPABILITY` = `"isolation.landlock.workspace-rw.v1"`, advertised only when `verify_trusted_helper` succeeds **and** `probe_landlock_ruleset()` is true; the probe builds the identical `ABI::V4` ruleset with the identical four runtime paths and identical rights in-process but never calls `restrict_self` (in `probe_landlock_ruleset`, including the comment that the devnull rule "must mirror the helper's null-device rule exactly"). - **Runtime read allowlist**: `for path in ["/usr", "/etc/ld.so.cache", "/etc/ssl/certs", "/dev/null"]`, each `canonicalize()`d, and a path that fails to canonicalize is **skipped silently** (no rule, so it stays denied): | Path | Rights granted | @@ -172,7 +172,7 @@ let mut ruleset = Ruleset::default() | `/dev/null` | `ReadFile | WriteFile` | | anything else | denied | - **`/dev/null` handling** (`main.rs:208-214`): granting write is deliberate and the in-source rationale is that the null device "discards all writes and yields EOF on reads: granting write is information-neutral, while denying it breaks ordinary `>/dev/null` redirection and makes escape-trap fixtures vacuous (redirection setup fails before the escape attempt runs). No other `/dev` path is allowed." That is exactly why the test fixture's `cat "$1" >/dev/null 2>&1` escape trap measures a real denial rather than a failed redirection. + **`/dev/null` handling** (the `/dev/null` rule in `linux::restrict`): granting write is deliberate and the in-source rationale is that the null device "discards all writes and yields EOF on reads: granting write is information-neutral, while denying it breaks ordinary `>/dev/null` redirection and makes escape-trap fixtures vacuous (redirection setup fails before the escape attempt runs). No other `/dev` path is allowed." That is exactly why the test fixture's `cat "$1" >/dev/null 2>&1` escape trap measures a real denial rather than a failed redirection. - **Denied paths**: any path outside the ruleset — including the workspace root's parents, the target's own scratch space, `/tmp`, other `/dev` entries, `/proc` beyond the fds already open — is denied by the handled set, and `no_new_privs` blocks the target from acquiring privilege to escape. - **`RestrictionStatus` outcomes**: `ruleset.restrict_self()` returns a `RestrictionStatus`; the helper requires `status.ruleset == RulesetStatus::FullyEnforced`, else status byte `30`, and requires `status.no_new_privs`, else status byte `31`. Both are aborts before the target exists — i.e. a partially enforced ruleset (a ruleset whose enforcement was degraded for a sub-layer) is treated as a refusal, not as best effort. The `RestrictionStatus` is otherwise discarded; it is not forwarded to the runner. @@ -184,7 +184,7 @@ let mut ruleset = Ruleset::default() **No rlimits are set anywhere in this crate.** There is no `setrlimit`/`rlimit` call. The helper's role is verification and observation; the limits themselves are applied by the runner's `SystemdCgroupBackend` (which wraps the helper command in a cgroup, and reports `ResourceSetupOutcome::Applied { backend: "systemd-cgroup-v2" }`), and this test asserts that backend string. -`verify_resource_limits(&spec)` (`main.rs:335`) is a pre-flight check that the cgroup the helper is *already inside* actually enforces the declared values, so the target is never started into a cgroup that silently does not bound what the request asked for. It returns `true` immediately when all three spec fields are `None`. Otherwise it reads `/proc/self/cgroup`, finds the `0::` unified-hierarchy line, and joins the remainder under `/sys/fs/cgroup` (an unreadable cgroup file, a missing `0::` line, or an unparseable value is a **failure**, via `is_none_or` / `return false` — fail closed): +`verify_resource_limits(&spec)` (`linux::verify_resource_limits`) is a pre-flight check that the cgroup the helper is *already inside* actually enforces the declared values, so the target is never started into a cgroup that silently does not bound what the request asked for. It returns `true` immediately when all three spec fields are `None`. Otherwise it reads `/proc/self/cgroup`, finds the `0::` unified-hierarchy line, and joins the remainder under `/sys/fs/cgroup` (an unreadable cgroup file, a missing `0::` line, or an unparseable value is a **failure**, via `is_none_or` / `return false` — fail closed): | Declared | Files read | Acceptance rule | | --- | --- | --- | @@ -192,7 +192,7 @@ let mut ruleset = Ruleset::default() | `resource_pids` | `pids.max` | must parse as `u32` and be **≤** the declared value | | `resource_cpu_millis` | `cpu.max` | both whitespace-separated fields must parse as `u64`; `period != 0`; and `quota.saturating_mul(1000) / period <= cpu_millis` — i.e. the effective millicores-per-second must not exceed what was requested | -**The counter-file mechanism.** `ResourceEvents` (`main.rs:271`) holds up to two `EventCounter`s, one for memory and one for pids, each an open `fs::File` plus a key plus a baseline read at construction. `EventCounter::for_events` resolves `/proc/self/cgroup` → `/memory.events` (key `oom_kill`) or `/pids.events` (key `max`), and `self` is constructed with `track_memory.then(EventCounter::memory).flatten()` — so an unavailable cgroup file or an unparseable baseline simply means no tracking for that dimension, not a failure. `read_counter(&mut file, key)` (`main.rs:325`) seeks to 0, reads the whole file as a string, and returns the first line whose first space-separated token equals `key`, parsed as `u64`. `exceeded()` is `read_counter(...) > baseline` — a strictly-greater comparison, so a target that merely ran near the limit is not reported. +**The counter-file mechanism.** `ResourceEvents` holds up to two `EventCounter`s, one for memory and one for pids, each an open `fs::File` plus a key plus a baseline read at construction. `EventCounter::for_events` resolves `/proc/self/cgroup` → `/memory.events` (key `oom_kill`) or `/pids.events` (key `max`), and `self` is constructed with `track_memory.then(EventCounter::memory).flatten()` — so an unavailable cgroup file or an unparseable baseline simply means no tracking for that dimension, not a failure. `read_counter(&mut file, key)` seeks to 0, reads the whole file as a string, and returns the first line whose first space-separated token equals `key`, parsed as `u64`. `exceeded()` is `read_counter(...) > baseline` — a strictly-greater comparison, so a target that merely ran near the limit is not reported. After the target exits, `ResourceEvents::status_code()` packs the result into one byte: bit 0 = `oom_kill` exceeded, bit 1 = `pids.events: max` exceeded. The runner decodes exactly these two bits in `SandboxSession::resource_limits_exceeded` into `eggwork_core::ResourceDimension::{Memory, Pids}` under a 2 s timeout, and a timeout or short read yields no exceeded dimensions rather than an error. @@ -208,9 +208,29 @@ Note the different units on the two mechanisms: the pre-flight check compares *c ## Environment handling -`denied_environment_key` (`main.rs:242`) uppercases the key and matches it against a fixed list by exact equality **or** prefix: `LD_`, `DYLD_`, `PATH`, `IFS`, `SHELLOPTS`, `CDPATH`, `BASH_ENV`, `ENV`, `PYTHONPATH`, `PYTHONHOME`, `NODE_OPTIONS`, `RUBYOPT`, `PERL5OPT`, `GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_CONFIG`, `GIT_CONFIG_`, `AWS_`, `AZURE_`, `GOOGLE_`, `SSH_AUTH_SOCK`. The intent is to strip every knob that would re-inject code or redirect the loader/interpreter inside a confined target: dynamic-linker search paths, shell startup files, interpreter startup options, and credential/config discovery for the major cloud and Git/SSH clients. +### One owner, two generated copies -It is enforced twice, as two independent layers. The runner filters with its own copy of the same predicate before building the spec (`lib.rs:1465`, used at `lib.rs:1709`) so denied keys are not even written. The helper *validates* the spec: in `read_spec`, `denied_environment_key(key) && key != "PATH"` is a rejection (code `12`), and `PATH` is the single exception, permitted only with the exact value `"/usr/bin:/bin"`. Duplicate keys are also rejected. +The environment policy has exactly one owner: `crates/eggwork-runner/policy/environment-policy.toml`. It holds the denied-key list and its matching rule, the node-owned (reserved) keys, the node-owned baseline, and the `PATH` value contract. Nothing else in the tree states any of them. + +The helper is a standalone binary that may not depend on any workspace crate, so it cannot share the policy as a library. It compiles a *generated copy* instead: `scripts/generate_environment_policy.py` writes `crates/eggwork-runner/src/environment_policy.rs` and `crates/eggwork-sandbox-helper/src/environment_policy.rs` from that one source. Both copies are checked in, so no build needs the generator, no crate reads a file outside its own directory, no `build.rs` is added, and no dependency edge is created. A hand edit of a generated copy is a contract change, not a local fix: change the source of truth and re-run the generator. + +The generated module exposes the same API in both crates — `DENIED_KEYS`, `MATCH_RULE`, `RESERVED_KEYS`, `BASELINE_COMMON`, `BASELINE`, `PATH_VALUE`, and the predicates `denied_environment_key`, `is_reserved_key`, `baseline_entry`, `baseline_value`. The helper's copy additionally carries the five protocol limit constants, because `eggwork-core` owns the wire limits and the helper cannot import them; the generator reads those five values out of `eggwork-core/src/lib.rs` and emits them, so the helper's copy is generated rather than hand-maintained. + +Two copies of one contract is a hole unless something pins them together. What pins them is `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs`, which compares the two copies element by element *and* drives the real helper binary against every probe key to compare its accept/refuse decision with what the runner's copy of the policy says. A one-sided edit to either copy fails that suite. + +### The drop-versus-reject contract + +The policy has three key classes, and the two layers treat them differently on purpose: + +| Class | Meaning | The runner | The helper | +| --- | --- | --- | --- | +| Denied | the caller may not set this key at all | **drops** it, silently | **refuses the launch** | +| Node-owned (reserved) | the node sets this key itself | **replaces** the caller's value with the node's | **refuses** a spec that carries a different value | +| Caller-controlled | everything else | passes it through | accepts it | + +The difference between dropping and refusing is deliberate and is not a contradiction. The runner is the *request-normalisation boundary*: a hardened environment has to be a property of the node rather than something the caller has to get right, so a denied key never reaches the specification and the caller is not told. The helper is the *enforcement point*: a denied key arriving there means the node's own filtering did not happen, which is a defect in the node rather than a caller error, so the whole launch is refused. Only the **list** is shared between them; the **behaviour** is deliberately not. + +`environment_policy::denied_environment_key` uppercases the key and matches it against the fixed list by exact equality **or** prefix: `LD_`, `DYLD_`, `PATH`, `IFS`, `SHELLOPTS`, `CDPATH`, `BASH_ENV`, `ENV`, `PYTHONPATH`, `PYTHONHOME`, `NODE_OPTIONS`, `RUBYOPT`, `PERL5OPT`, `GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_CONFIG`, `GIT_CONFIG_`, `AWS_`, `AZURE_`, `GOOGLE_`, `SSH_AUTH_SOCK`. The intent is to strip every knob that would re-inject code or redirect the loader/interpreter inside a confined target: dynamic-linker search paths, shell startup files, interpreter startup options, and credential/config discovery for the major cloud and Git/SSH clients. `GIT_CONFIG_` is redundant, because the `GIT_CONFIG` prefix already covers `GIT_CONFIG_GLOBAL` and its relatives; it is carried over unchanged from the reviewed baseline. | Group | Denied keys | Why | | --- | --- | --- | @@ -220,9 +240,27 @@ It is enforced twice, as two independent layers. The runner filters with its own | Interpreter options | `PYTHONPATH`, `PYTHONHOME`, `NODE_OPTIONS`, `RUBYOPT`, `PERL5OPT` | the same class of injection, per runtime; `NODE_OPTIONS` alone is a code-execution vector | | VCS / credential discovery | `GIT_ASKPASS`, `SSH_ASKPASS`, `GIT_CONFIG`, `GIT_CONFIG_`, `SSH_AUTH_SOCK` | these point an otherwise-sandboxed process at an agent or a config file outside the workspace | | Cloud credentials | `AWS_`, `AZURE_`, `GOOGLE_` (prefixes) | a confined process must not inherit cloud credential endpoints or tokens from the daemon's environment | -| Path | `PATH` | permitted only as the single hard-coded value `"/usr/bin:/bin"`; see below | +| Path | `PATH` | permitted only as the single contract value `"/usr/bin:/bin"`; see below | + +### The node-owned baseline + +The node-owned baseline is the environment the node installs for a child before any caller-supplied entry: `PATH=/usr/bin:/bin`, `LANG=C.UTF-8`, `LC_ALL=C.UTF-8`, `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`. A caller-supplied value for one of those keys is **discarded in favour of the node's**, on both of the runner's launch paths. -**The surviving environment** is therefore a closed set that the helper reconstructs from scratch: `Command::env_clear()`, then `.env("PATH", "/usr/bin:/bin")`, then `.envs(...)` over the spec's environment with `key != "PATH"` filtered out — the `PATH` filter is redundant with the spec validation and exists so a pinned `PATH` cannot be overridden by a later entry. Nothing is inherited: the runner also launches the helper itself with `env_clear()` plus `PATH`/`LANG`/`LC_ALL` (`lib.rs:1791`). The spec the runner builds starts from the baseline `PATH`, `LANG=C.UTF-8`, `LC_ALL=C.UTF-8`, `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`, then appends non-denied request environment, then `EGGWORK_EXECUTION_ID` and `EGGWORK_EXECUTION_GENERATION` from `ExecutionProvenance` when present (`lib.rs:1698-1721`). +That rule is what closes the collision hole. Before it, the runner's launch-specification builder started from the fixed baseline and then *appended* every non-denied caller key, and none of the baseline keys except `PATH` was denied. A caller that set `LANG` therefore produced a specification with **two** `LANG` entries; the helper refuses a specification with duplicate keys; the runner read that refusal as a pre-target setup failure and — for a **best-effort** request only — rewrote the sandbox outcome to `NotApplied` and re-spawned the target directly with no Landlock ruleset at all. The observable result was a successful, entirely unconfined execution whose only record of the degradation was a `NotApplied` in the terminal snapshot. The `Required` path was unaffected and still failed closed. + +The baseline is the node's, so the helper refuses a specification in which a node-owned key carries anything other than the node's value, or carries it under a different spelling: such a specification is one the runner did not build. + +### The `PATH` contract + +`PATH == /usr/bin:/bin` is an enforced contract on **both** sides. The helper keeps the check, and takes the expected value from the shared policy (`environment_policy::PATH_VALUE`); the runner guarantees the value in the child environment and in the launch specification. + +The contract is a **Linux/Unix** contract. The Windows baseline is explicitly outside it: the Windows `PATH` is `%SystemRoot%\System32;%SystemRoot%`, built from the parent process at spawn time, and a future reader must not "fix" it to the Unix value. The shared policy says so in the same terms, so the Windows branch stays runner-local and the statement cannot drift from it. + +### The surviving environment + +The environment the target receives is a closed set that the helper reconstructs from scratch: `Command::env_clear()`, then `.env("PATH", environment_policy::PATH_VALUE)`, then `.envs(...)` over the spec's environment with `key != "PATH"` filtered out — the `PATH` filter is redundant with the spec validation and exists so a pinned `PATH` cannot be overridden by a later entry. Nothing is inherited: the runner also launches the helper itself with `env_clear()` plus the node's own baseline (`SandboxChannel::command`). + +The specification the runner builds is the node's baseline, then the caller's environment with the denied keys dropped and the node-owned keys replaced by the node's values, then `EGGWORK_EXECUTION_ID` and `EGGWORK_EXECUTION_GENERATION` from `ExecutionProvenance` when present. A repeated caller key is resolved to its last value, so the specification can never carry a duplicate key. ## Hand-off to the target @@ -230,7 +268,7 @@ It is enforced twice, as two independent layers. The runner filters with its own let (program, argv) = spec.argv.split_first().ok_or(())?; let mut command = Command::new(program); command.args(argv).current_dir(&spec.cwd).env_clear() - .env("PATH", "/usr/bin:/bin") + .env("PATH", environment_policy::PATH_VALUE) .envs(spec.environment.iter().filter_map(|(k, v)| (k != "PATH").then_some((k, v)))); let mut child = match command.spawn() { Ok(child) => child, Err(_) => { let _ = status.write_all(&[0]); return Err(()); } }; ``` @@ -244,7 +282,9 @@ The step is `std::process::Command::spawn`, not a self-`execve`. That is a delib | Failure | Status byte | Target started? | | --- | --- | --- | | status socket unconnectable | none written | no (spec not even read) | -| `read_spec` rejection | 4–15 | no | +| `read_spec` rejection — specification shape | 4–12 | no | +| `read_spec` rejection — **environment policy** | **13** | no | +| `read_spec` rejection — root canonicalization | 17 | no | | `verify_resource_limits` false | 2 | no | | `restrict` failure | 2 | no | | ruleset not `FullyEnforced` | 30 | no | @@ -252,7 +292,34 @@ The step is `std::process::Command::spawn`, not a self-`execve`. That is a delib | `argv` empty after validation | none | no | | `spawn` itself fails (e.g. ENOENT on a denied or missing program) | 0 | no — this is the one code the runner treats as `AfterTarget(Spawn)` | -The runner's reading of those bytes (`SandboxChannel::wait`, `lib.rs:1798`): the first byte `0 | 2 | 3 | 30 | 31` → `Ok(None)` (no resource-reporting session; the run continues), `>= 4` → `Err(SandboxWaitError::BeforeTarget(RunnerError::Setup("sandbox helper rejected its launch specification (status {code})")))`, `1` → read the second byte: `1` → `Ok(Some(SandboxSession))`, `0` → `AfterTarget(Spawn("sandbox target could not start"))`, anything else → `"sandbox status was invalid"`. Every arm is a single byte read, never a length-prefixed or textual protocol. +### The status-byte table + +| Byte | Meaning | Written by | +| --- | --- | --- | +| `0` | the target could not be spawned | `run`, after `Command::spawn` fails | +| `1` | mechanics applied; the second byte says whether the target started | `run`, twice — once for "mechanics applied", once for "the target started" | +| `2` | resource verification or Landlock setup failed | `verify_resource_limits`, `restrict` | +| `3` | reserved | — | +| `4` | the spec file could not be `stat`ed | `read_spec` | +| `5` | the spec is not a regular file, is a symlink, is owned by another user, is group/world-accessible, or is too large | `read_spec` | +| `6` | the spec could not be opened | `read_spec` | +| `7` | the opened spec could not be `fstat`ed | `read_spec` | +| `8` | the opened spec is a different inode than the stat'ed one | `read_spec` | +| `9` | the spec could not be read | `read_spec` | +| `10` | the spec is larger than `MAX_SPEC_BYTES` | `read_spec` | +| `11` | the spec is not valid JSON, or does not match `LaunchSpec` | `read_spec` | +| `12` | the specification is invalid: wrong schema version, unsupported profile, empty or oversized argv, or an environment entry that is empty, oversized, or malformed | `read_spec` | +| `13` | **the environment does not satisfy the shared environment policy**: a denied key is present, `PATH` is not the contract value, a node-owned key carries a value or a spelling other than the node's, or an environment key is duplicated | `read_spec` | +| `14` | the working directory could not be canonicalized | `read_spec` | +| `15` | the root is not canonical, is not a directory, or does not contain the working directory | `read_spec` | +| `16` | the validated root could not be pinned open | `read_spec` | +| `17` | the root could not be canonicalized | `read_spec` | +| `30` | the ruleset was not `FullyEnforced` | `restrict` | +| `31` | `no_new_privs` was not set | `restrict` | + +Bytes `13` and `17` are new relative to the pre-corrective table. `13` was the root-canonicalization failure and is now the environment-policy refusal, because an operator reading "status 12" cannot tell which of several specification problems happened — and the environment-policy refusal is the one whose cause is a *contract* rather than a malformed file. The root-canonicalization failure moved to `17`, which was unused. The runner's reading of the bytes is unchanged: every byte `>= 4` is a pre-target refusal, so both `13` and `17` fail closed before the target exists. + +The runner's reading of those bytes (`SandboxChannel::wait`, via `classify_helper_status`): the first byte `0 | 2 | 3 | 30 | 31` → `Ok(None)` (no resource-reporting session; the run continues), `>= 4` → `Err(SandboxWaitError::BeforeTarget(RunnerError::Setup("sandbox helper rejected its launch specification (status {code})")))`, `1` → read the second byte: `1` → `Ok(Some(SandboxSession))`, `0` → `AfterTarget(Spawn("sandbox target could not start"))`, anything else → `"sandbox status was invalid"`. Every arm is a single byte read, never a length-prefixed or textual protocol. **The handshake recovery path and what the caller is told.** When the helper cannot confirm confinement — status byte `0`, `2`, `3`, `30` or `31`, or a spec rejection the runner treats as recoverable — the runner kills the helper tree, rewrites `setup.sandbox` and `setup.resources` to `NotApplied { reason }`, and re-spawns the target **directly**, with no Landlock ruleset and no cgroup verification. The target therefore runs unconfined, and the runner reports that as a degradation diagnostic on its output channel (`OutputChunk::Diagnostic` → `ExecutionEventKind::Diagnostic`) before the re-spawn, so the caller learns the execution ran unconfined while it is still running rather than only from the terminal result. The diagnostic's class is `isolation.degraded` for the sandbox and `resources.degraded` for the resource dimension; the grammar and bound are in [protocol.md](protocol.md#the-execution-diagnostic-payload-schema-version-1). The runner's own rules for when this happens live in [runner-execution.md](runner-execution.md#reporting-a-degradation); from the helper's side the only requirement is the one below. @@ -263,7 +330,7 @@ The wire sequence, as a fixed four-message exchange with no framing beyond "one | # | Direction | Byte | Meaning | | --- | --- | --- | --- | | 1 | helper → runner | accept | the helper reached `connect` and passed argv parsing | -| 2 | helper → runner | `4`–`15` | spec rejected; runner errors before spawn | +| 2 | helper → runner | `4`–`12`, `13`, `14`–`17` | spec rejected; runner errors before spawn | | 3 | helper → runner | `2` / `30` / `31` | mechanics failed; run continues without a resource session | | 4 | helper → runner | `1` | resources verified and Landlock applied (or not requested) | | 5 | helper → runner | `1` | the target `execve` succeeded | @@ -274,7 +341,7 @@ Steps 4 and 5 deliberately reuse the value `1`: the runner distinguishes them by ## Platform support -Linux is the only functional path, and the gate is on the module, not the dependency list: `#[cfg(target_os = "linux")] mod linux` holds `run`, `read_spec`, `restrict`, `exit_code`, `denied_environment_key`, `read_counter`, `verify_resource_limits`, plus `ResourceEvents`/`EventCounter`. Two `main` functions are `#[cfg]`-selected: the Linux one calls `linux::entry()`; the `#[cfg(not(target_os = "linux"))]` one (a) prints the version and exits 0 for a bare `--version`, and (b) exits 125 for everything else. +Linux is the only functional path, and the gate is on the module, not the dependency list: `#[cfg(target_os = "linux")] mod linux` holds `run`, `read_spec`, `restrict`, `exit_code`, `environment_policy_refuses`, `read_counter`, `verify_resource_limits`, plus `ResourceEvents`/`EventCounter`. The generated `environment_policy` module is *not* inside that gate: it is a pure data-and-predicate module with no platform dependency, it is compiled on every host so that the two copies are always compiled, and its items the non-Linux entry point does not use are explicitly allowed to be dead. Two `main` functions are `#[cfg]`-selected: the Linux one calls `linux::entry()`; the `#[cfg(not(target_os = "linux"))]` one (a) prints the version and exits 0 for a bare `--version`, and (b) exits 125 for everything else. The crate still compiles on every other host because the machinery's dependencies are target-scoped (`landlock` under `cfg(target_os = "linux")`, `nix` under `cfg(unix)`), so a macOS or Windows build of the workspace pulls neither into the graph and the non-Linux entry point needs neither. What a non-Linux host actually gets is a binary that answers `--version` and refuses every launch with 125; the `[[bin]]` is unconditional in the manifest, so a host build of the workspace does produce that binary — it simply never becomes part of a release (the release file set for macOS and Windows is the daemon alone; `README.md` "Published targets" and `release_contract.rs` agree on the same split). @@ -296,11 +363,13 @@ The crate still compiles on every other host because the machinery's dependencie The `Cargo.toml` states the intent in a comment: "The helper's Linux-only sandbox machinery (`mod linux`) is the sole user of these crates. Both are Unix/Linux-only and must not enter the build graph on other hosts; the non-Linux entry point uses neither." -Dev-dependencies are `eggwork-runner`, `eggwork-core`, `tempfile`, `tokio` (`features = ["net"]`), and `tokio-util` — used only by `tests/landlock_runner.rs`, which drives the *real* binary (`env!("CARGO_BIN_EXE_eggwork-sandbox-helper")`) through the real `LocalProcessRunner`. None of them enter the shipped binary's graph, which is what keeps the trusted artifact's dependency surface to serde/serde_json plus one sandbox crate. Combined with `#![forbid(unsafe_code)]`, the shipped helper contains no `unsafe` of its own. +Dev-dependencies are `eggwork-runner`, `eggwork-core`, `tempfile`, `tokio` (`features = ["net"]`), and `tokio-util` — used by `tests/landlock_runner.rs` and `tests/environment_policy_parity.rs`, both of which drive the *real* binary (`env!("CARGO_BIN_EXE_eggwork-sandbox-helper")`), the first through the real `LocalProcessRunner` and the second also directly. None of them enter the shipped binary's graph, which is what keeps the trusted artifact's dependency surface to serde/serde_json plus one sandbox crate. Combined with `#![forbid(unsafe_code)]`, the shipped helper contains no `unsafe` of its own. ## Test coverage -`tests/landlock_runner.rs` is 534 lines, 10 tests, **all `#[cfg(target_os = "linux")]`** (9 `#[tokio::test]`, 1 `#[test]`); on any other host the file compiles and runs zero tests. Every test copies `CARGO_BIN_EXE_eggwork-sandbox-helper` into a `0700` temp dir as `0755` so `verify_trusted_helper` accepts it — the trust rules are satisfied by construction, which is itself part of the contract being tested. The suite is an integration suite: it never imports the helper, it drives the real binary either through the real `LocalProcessRunner` or, once, through a raw `Command`. +`tests/landlock_runner.rs` is 534 lines, 10 tests, **all `#[cfg(target_os = "linux")]`** (9 `#[tokio::test]`, 1 `#[test]`); on any other host the file compiles and runs zero tests. + +`tests/environment_policy_parity.rs` is the environment-policy gate: 12 tests, of which the element-wise parity ones and the limit-constant ones run on every host and the behavioural ones are Linux-gated. It is the only suite that compares the two generated copies of the policy with each other and the only one that drives the real helper binary with a hand-written specification carrying a single probe key. Every test copies `CARGO_BIN_EXE_eggwork-sandbox-helper` into a `0700` temp dir as `0755` so `verify_trusted_helper` accepts it — the trust rules are satisfied by construction, which is itself part of the contract being tested. The suite is an integration suite: it never imports the helper, it drives the real binary either through the real `LocalProcessRunner` or, once, through a raw `Command`. | Test | What it pins down | | --- | --- | @@ -328,27 +397,32 @@ In detail: 9. `concurrent_resource_scopes_keep_pid_limits_isolated` — two overlapping runs on the same `LocalProcessRunner`, one with `pids: Required(6)` and one with `Required(32)`, each forking 8 children: the low scope reports `LimitExceeded` while the high scope reports `Applied`. This is the test that keeps the shared-cgroup hazard in `read_counter` honest. 10. `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` — the only **direct** invocation of the binary. A `0700` dir, a `0600` `spec.json` with `profile: "unsupported-profile"` and `argv: ["/usr/bin/touch", marker]`, a bound `status.sock`: the first status byte is exactly `12`, the child exits non-zero, and the marker is absent. Second case: a valid `workspace_rw` spec but a missing status socket — non-zero exit, marker absent, proving the connect happens before the spec is read. -**Thin areas, honestly.** The `restrict` failure codes `30` and `31` have no test, and neither does `2` (resource verification refused) — so the "Landlock not fully enforced" and "`no_new_privs` unset" branches are unexercised. `read_spec` codes `4`, `5` (e.g. a `0644` or euid-mismatched spec), `6`–`11`, `13`–`15` are untested; only `12` is. There is no test for oversized argv/environment or a > 1 MiB spec, none for `denied_environment_key` at the helper level (test 1's `PATH` is neutralized by the runner, not refused by the helper), none for `exit_code`'s 128 + signal mapping, and none that invokes the helper's `--version` path directly. All 9 tests are Linux-gated, so the non-Linux 125 path has no coverage. The memory/PID tests assume `python3` at `/usr/bin/python3` and a cgroup v2 hierarchy the test host can write. +**Thin areas, honestly.** The `restrict` failure codes `30` and `31` have no test, and neither does `2` (resource verification refused) — so the "Landlock not fully enforced" and "`no_new_privs` unset" branches are unexercised. `read_spec` codes `4`, `5` (e.g. a `0644` or euid-mismatched spec), `6`–`11`, `14`–`17` are untested; `12` and `13` are covered — `12` by `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` and `13` by the parity suite. There is no test for oversized argv/environment or a > 1 MiB spec, none for `exit_code`'s 128 + signal mapping, and none that invokes the helper's `--version` path directly. The helper-level `denied_environment_key` refusal that test 1 did not reach is now covered by `the_helper_refuses_exactly_what_the_runner_drops` in the parity suite. All 9 tests are Linux-gated, so the non-Linux 125 path has no coverage. The memory/PID tests assume `python3` at `/usr/bin/python3` and a cgroup v2 hierarchy the test host can write. ## Invariants and enforcement | Invariant | Enforcement site | Test | | --- | --- | --- | -| A required sandbox profile is never served by an untrusted helper | `verify_trusted_helper` → `RunnerError::Setup` (`lib.rs:465-473`) | `helper_trust_checks_reject_missing_wrong_and_symlinked_helpers` | -| Best-effort sandbox is reported as `NotApplied`, never as enforced | `SandboxOutcome::NotApplied { reason }` (`lib.rs:469`) | same test | -| Workspace is read-write, everything else outside the runtime allowlist is denied | `restrict`, `ABI::V4`, `from_all` handled set, root rule at full rights (`main.rs:186`) | `required_landlock_allows_workspace_and_denies_outside_reads_and_writes`, `workspace_symlink_cannot_read_outside_workspace` | -| `/dev/null` stays writable; no other `/dev` path is allowed | explicit `/dev/null` rule + comment (`main.rs:208`) | exercised implicitly by the escape trap's `>/dev/null 2>&1` | -| A partially enforced ruleset is a refusal, not a downgrade | `status.ruleset != FullyEnforced → 30` (`main.rs:227`) | none (uncovered) | -| `no_new_privs` is set | `!status.no_new_privs → 31` (`main.rs:230`) | none (uncovered) | +| A required sandbox profile is never served by an untrusted helper | `verify_trusted_helper` → `RunnerError::Setup` | `helper_trust_checks_reject_missing_wrong_and_symlinked_helpers` | +| Best-effort sandbox is reported as `NotApplied`, never as enforced | `SandboxOutcome::NotApplied { reason }` | same test | +| Workspace is read-write, everything else outside the runtime allowlist is denied | `restrict`, `ABI::V4`, `from_all` handled set, root rule at full rights (`linux::restrict`) | `required_landlock_allows_workspace_and_denies_outside_reads_and_writes`, `workspace_symlink_cannot_read_outside_workspace` | +| `/dev/null` stays writable; no other `/dev` path is allowed | explicit `/dev/null` rule + comment (`linux::restrict`) | exercised implicitly by the escape trap's `>/dev/null 2>&1` | +| A partially enforced ruleset is a refusal, not a downgrade | `status.ruleset != FullyEnforced → 30` (`linux::restrict`) | none (uncovered) | +| `no_new_privs` is set | `!status.no_new_privs → 31` (`linux::restrict`) | none (uncovered) | | No ABI downgrade to an older Landlock version | hard-coded `ABI::V4`, every failure → 2 | indirect: runner's `probe_landlock_ruleset` gates the capability | -| The target never starts with the declared limits unenforced | `verify_resource_limits` (`main.rs:335`), fail-closed on unreadable/unparseable | `required_cpu_quota_is_verified_before_target_start`; memory/pids classification tests | +| The target never starts with the declared limits unenforced | `verify_resource_limits` (`linux::verify_resource_limits`), fail-closed on unreadable/unparseable | `required_cpu_quota_is_verified_before_target_start`; memory/pids classification tests | | Limit breaches are attributed per dimension, not guessed | `ResourceEvents` bit flags → `ResourceDimension::{Memory, Pids}` | `required_memory_limit_is_enforced_and_classified`, `required_pid_limit_is_enforced_and_classified` | | Per-run cgroup isolation is real, not shared state | runner-side scope creation; helper only reads its own `/proc/self/cgroup` | `concurrent_resource_scopes_keep_pid_limits_isolated` | | A malformed spec aborts before the target runs | `read_spec` → code 12 + `Err` | `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target` | | A runtime enforcement failure is reported to the caller, not only to the snapshot | the runner's handshake recovery path emits a diagnostic before it re-spawns the target directly | runner-side `crates/eggwork-runner/tests/diagnostic_degradation.rs`; server-side `a_degraded_best_effort_execution_publishes_its_diagnostic_before_output_and_terminal` | -| An unavailable status channel aborts before the spec is read | `UnixStream::connect` first (`main.rs:69`) | same test | -| The environment is rebuilt, never inherited | `env_clear()` + pinned `PATH` + validated spec env (`main.rs:100`) | `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` (`PATH=/malicious/path`) | -| Loader/interpreter/credential knobs never reach the target | `denied_environment_key` in both crates | none directly (runner-side filter is what test 1 observes) | +| An unavailable status channel aborts before the spec is read | `UnixStream::connect` first (`linux::run`) | same test | +| The environment is rebuilt, never inherited | `env_clear()` + the contract `PATH` + validated spec env (`linux::run`) | `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` (`PATH=/malicious/path`) | +| Loader/interpreter/credential knobs never reach the target | the shared policy's deny-list; the runner drops, the helper refuses | `the_helper_refuses_exactly_what_the_runner_drops` (helper side); runner-side `a_caller_supplied_denied_key_does_not_reach_the_child` | +| The environment policy has exactly one owner | `crates/eggwork-runner/policy/environment-policy.toml`, generated into each crate by `scripts/generate_environment_policy.py` | `test_the_checked_in_copies_are_what_the_generator_produces`; `the_denied_key_list_is_the_same_list_in_the_same_order` | +| The two generated copies cannot drift apart | `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs`, element-wise and behavioural | same suite; a one-sided edit to either copy fails it | +| A node-owned key carries the node's value, in the child and in the specification | the runner's `build_child_environment`; the helper's `linux::environment_policy_refuses` | `a_caller_supplied_node_owned_key_keeps_the_execution_confined`; `the_direct_path_and_the_helper_path_agree_about_the_environment` | +| The `PATH` contract is enforced on both sides and is Linux/Unix-scoped | `environment_policy::PATH_VALUE`; the runner installs it, the helper refuses anything else | `the_matching_rule_and_the_path_contract_are_the_same_in_both_copies`; `the_path_contract_states_that_windows_is_outside_it` | +| The helper's limit constants are the owner's, not a copy | generated into the helper's copy from `eggwork-core/src/lib.rs` | `the_helper_limit_constants_match_eggwork_core` | | Timeout and cancellation reap the whole tree | runner process-group signaling; helper only `wait()`s | `sandbox_timeout_and_cancellation_reap_the_helper_process_group` | | Helper and daemon cannot be version-skewed | exact `--version` match in `check_helper_compatibility` | `crates/eggwork-server`: `helper_version_skew_is_detected`; `release_contract::the_helper_ships_exactly_on_linux_release_targets` | @@ -363,7 +437,7 @@ In detail: - **Spec TOCTOU surface.** `read_spec` uses `symlink_metadata`, then `open`, then compares `dev`/`ino` — but it does not use `O_NOFOLLOW`, so the *opened* file is not proven to be the stat'ed non-symlink. The euid + `mode & 0o077 == 0` + `0700` parent requirements are what actually make the substitution uninteresting; confirm that is the intended layering rather than an oversight. - **Could an untrusted caller invoke the binary directly?** Yes — argv is unvalidated input to any process, so `verify_trusted_helper` protects the *runner*, not the binary. What stops a malicious direct caller is narrow: the spec must be owned by the caller's euid and `0600`, the caller must be able to bind the status socket (self-reporting only, so it can fabricate any code), and the target will be confined to the caller's own `root` with the caller's own environment. A direct caller therefore gets a *correctly confined process with attacker-chosen rules*, i.e. no privilege gain — but it is worth confirming there is no path where a caller-supplied `root` escapes containment, since `read_spec`'s `root != spec.root` equality after canonicalization plus `cwd.starts_with(root)` is the only thing standing between the two. - **Uncleared fd surface.** The helper holds the spec `File`, the `status` `UnixStream`, and up to two cgroup event `File`s across the target's lifetime, plus the `Child`'s inherited pipes. None are `CLOEXEC`-hardened in this crate, and the target inherits whatever the runner's `Command` set. Confirm the runner's stdio wiring is the intended boundary and that the cgroup event fds are harmless to leak (they are pre-restriction opens, which is also exactly why they keep working). -- **The environment denylist is prefix-matched and duplicated.** `denied_environment_key` lives in both crates and is a closed list; a new interpreter or loader knob (e.g. `PERL5LIB`, `RUBYLIB`, `NODE_PATH`, `GLIBC_TUNABLES`, `PROMPT_COMMAND`) is not covered. The duplication is deliberate (runner filters, helper validates) but is two copies to keep in sync, and only the runner's copy has any test coverage. +- **The environment denylist is prefix-matched and closed.** The list is now written once — `crates/eggwork-runner/policy/environment-policy.toml` — and generated into both crates, so the two copies cannot drift. What remains closed is the *coverage*: a new interpreter or loader knob (e.g. `PERL5LIB`, `RUBYLIB`, `NODE_PATH`, `GLIBC_TUNABLES`, `PROMPT_COMMAND`) is not in the list at all. Adding one is a policy decision with its own security review; it is not a mechanical consequence of the duplication being gone. The prefix match also means `PATH` denies *any* key beginning with `PATH`, not only `PATH` itself, which is deliberate but worth remembering when reading the list. - **Exit code fidelity.** `exit_code` maps a signalled target to `128 + signal`, which is conventional but indistinguishable from a target that legitimately exited with that number. Worth confirming the runner's classification does not treat large exit codes as failures by accident. ## Related diff --git a/crates/eggwork-runner/policy/environment-policy.toml b/crates/eggwork-runner/policy/environment-policy.toml new file mode 100644 index 0000000..892fa63 --- /dev/null +++ b/crates/eggwork-runner/policy/environment-policy.toml @@ -0,0 +1,153 @@ +# The node's environment policy — the single owner of the sandbox +# environment contract. +# +# `eggwork-runner` and `eggwork-sandbox-helper` both enforce this policy, and +# the helper is a standalone binary that may not depend on any workspace crate. +# The duplication that forced the helper to keep its own copy is what let a +# one-sided edit change what was enforced without failing anything, and it is +# also what let a caller-supplied `LANG` collide with the node's own baseline +# and cost a best-effort execution its confinement. +# +# So the policy is authored here, once, and +# `scripts/generate_environment_policy.py` writes a generated copy into each +# crate: +# +# crates/eggwork-runner/src/environment_policy.rs +# crates/eggwork-sandbox-helper/src/environment_policy.rs +# +# The generated copies are checked in, so no build needs the generator, no +# crate reads a file outside its own directory, and no dependency edge is +# created. A parity test pins the two copies together, so a one-sided edit +# fails the build instead of silently changing what is enforced. +# +# A hand edit of a generated copy is a contract change, not a local fix. + +schema_version = 1 + +# The rule used to match an environment key against the denied list and against +# the node-owned class: +# +# upper = key.to_ascii_uppercase() +# matches(entry) := upper == entry || upper.starts_with(entry) +# +# It is case-insensitive because the dangerous knobs are dangerous whatever +# their case, and it is prefix-based so one entry covers a whole family +# (`AWS_*`, `GIT_CONFIG_*`). Two properties of the rule are worth recording +# because a parity fix must preserve them: `GIT_CONFIG_` is redundant, because +# the `GIT_CONFIG` prefix already covers `GIT_CONFIG_GLOBAL` and its +# relatives; and because the match is prefix-based, `PATH` denies *any* key +# beginning with `PATH`, not only `PATH` itself. +[match] +rule = "ascii-uppercase-exact-or-prefix" + +# The keys a caller may not set. +# +# The runner *drops* one of these silently: it is the request-normalisation +# boundary, and a hardened environment has to be a property of the node rather +# than something the caller has to get right. The helper *refuses the whole +# launch* when one of these is present: it is the enforcement point, and a +# denied key reaching it means the node's own filtering did not happen, which +# is a defect in the node rather than a caller error. The two behaviours are a +# deliberate two-layer contract; only the list is duplicated, never the +# behaviour. +# +# The entry set is carried over unchanged from the reviewed baseline. Adding or +# removing an entry is a policy decision with its own security review, and it +# is not this milestone's business. +[denied] +keys = [ + "LD_", + "DYLD_", + "PATH", + "IFS", + "SHELLOPTS", + "CDPATH", + "BASH_ENV", + "ENV", + "PYTHONPATH", + "PYTHONHOME", + "NODE_OPTIONS", + "RUBYOPT", + "PERL5OPT", + "GIT_ASKPASS", + "SSH_ASKPASS", + "GIT_CONFIG", + "GIT_CONFIG_", + "AWS_", + "AZURE_", + "GOOGLE_", + "SSH_AUTH_SOCK", +] + +# The node-owned baseline. +# +# `unix` is the Unix/Linux baseline: the keys the node installs for an +# execution child, and the values it installs them with, in the order it +# installs them. This is the baseline the helper enforces and the Linux runner +# installs. +# +# The Windows baseline is deliberately *not* here. Its values are read from the +# parent process at spawn time (`SystemRoot`/`windir`, and a `PATH` built from +# them), and the sandbox helper is Linux-only so it never sees a Windows +# launch. That branch is runner-local; see `baseline_child_environment` in +# `crates/eggwork-runner/src/lib.rs`. `windows_common` names only the keys the +# Windows baseline shares with the Unix one — their values are identical — so +# that the runner's local branch does not have to re-list them. +[baseline.unix] +PATH = "/usr/bin:/bin" +LANG = "C.UTF-8" +LC_ALL = "C.UTF-8" +CI = "1" +NO_COLOR = "1" +TERM = "dumb" +GIT_TERMINAL_PROMPT = "0" +PAGER = "cat" + +[baseline.windows_common] +keys = [ + "CI", + "NO_COLOR", + "TERM", + "GIT_TERMINAL_PROMPT", + "PAGER", +] + +# The node-owned (reserved) keys on the Unix baseline. +# +# A caller-supplied value for one of these is discarded in favour of the +# node's value, so the node's baseline is what reaches the child and the +# launch specification can never carry a duplicate of a baseline key. This is +# the rule that closes the collision hole: before it, a caller that set `LANG` +# produced a specification with two `LANG` entries, the helper refused that +# specification, and a best-effort request answered the refusal by running the +# target with no Landlock ruleset at all. +# +# The class is the node-owned baseline, and the baseline is platform-shaped: on +# the Windows baseline the node owns `SystemRoot`, `windir` and `PATH` instead +# of the Unix locale keys. +[reserved] +keys = [ + "PATH", + "LANG", + "LC_ALL", + "CI", + "NO_COLOR", + "TERM", + "GIT_TERMINAL_PROMPT", + "PAGER", +] + +# The `PATH` value contract. +# +# A `PATH` that points outside `/usr/bin:/bin` widens what a confined target +# can execute, and the helper's Landlock ruleset does not restrict `execve` by +# path. The rule is enforced on both sides: the helper refuses a launch whose +# `PATH` differs, and the runner guarantees the value in the child environment +# and in the launch specification. +# +# The scope is Linux/Unix. The Windows baseline is explicitly outside this +# contract — its `PATH` is `%SystemRoot%\System32;%SystemRoot%` — so a future +# reader must not "fix" the Windows `PATH` to the Unix value. +[path_contract] +value = "/usr/bin:/bin" +scope = "linux-unix" diff --git a/crates/eggwork-runner/src/environment_policy.rs b/crates/eggwork-runner/src/environment_policy.rs new file mode 100644 index 0000000..9a6be2d --- /dev/null +++ b/crates/eggwork-runner/src/environment_policy.rs @@ -0,0 +1,154 @@ +// @generated by scripts/generate_environment_policy.py — do not edit. +// +// Source of truth: crates/eggwork-runner/policy/environment-policy.toml +// Generator: scripts/generate_environment_policy.py +// +// This file is generated. A hand edit is a contract change, not a local +// fix: change the source of truth and re-run the generator. +// +// This is the runner's copy. The other copy is generated from the same +// source of truth, and a parity test pins the two together, so a one-sided +// edit fails the build rather than silently changing what is enforced. + +/// The keys a caller may not set. +/// +/// The runner drops one of these silently: it is the request-normalisation +/// boundary, and a hardened environment has to be a property of the node +/// rather than something the caller has to get right. The helper refuses the +/// whole launch when one of these is present: it is the enforcement point, and +/// a denied key reaching it means the node's own filtering did not happen. +/// The difference is deliberate and is the whole two-layer contract; only the +/// list is shared, never the behaviour. +pub const DENIED_KEYS: &[&str] = &[ + "LD_", + "DYLD_", + "PATH", + "IFS", + "SHELLOPTS", + "CDPATH", + "BASH_ENV", + "ENV", + "PYTHONPATH", + "PYTHONHOME", + "NODE_OPTIONS", + "RUBYOPT", + "PERL5OPT", + "GIT_ASKPASS", + "SSH_ASKPASS", + "GIT_CONFIG", + "GIT_CONFIG_", + "AWS_", + "AZURE_", + "GOOGLE_", + "SSH_AUTH_SOCK", +]; + +/// The rule used to match an environment key against `DENIED_KEYS` and against +/// the node-owned class: ASCII-uppercase the key, then match it as an exact +/// match or as a prefix. +/// +/// The rule is part of the contract, not an implementation detail: the two +/// copies must agree on it, or the runner would drop a key the helper still +/// refuses. +pub const MATCH_RULE: &str = "ascii-uppercase-exact-or-prefix"; + +/// The node-owned (reserved) keys on the Unix baseline. +/// +/// A caller-supplied value for one of these is discarded in favour of the +/// node's value, so the node's baseline is what reaches the child and a +/// launch specification can never carry a duplicate of a baseline key. +/// +/// The class is the node-owned baseline, and the baseline is platform-shaped: +/// on the Windows baseline the node owns `SystemRoot`, `windir` and `PATH` +/// instead of the Unix locale keys, and that branch is runner-local. +pub const RESERVED_KEYS: &[&str] = &[ + "PATH", + "LANG", + "LC_ALL", + "CI", + "NO_COLOR", + "TERM", + "GIT_TERMINAL_PROMPT", + "PAGER", +]; + +/// The node-owned baseline keys every platform carries. +/// +/// The values are the node's own; a caller cannot move them. This is the +/// part of the Unix baseline the runner's Windows branch also installs, so +/// the Windows branch does not have to re-list it. +pub const BASELINE_COMMON: &[(&str, &str)] = &[ + ("CI", "1"), + ("NO_COLOR", "1"), + ("TERM", "dumb"), + ("GIT_TERMINAL_PROMPT", "0"), + ("PAGER", "cat"), +]; + +/// The node-owned Unix baseline, in the order the node installs it. +/// +/// The Windows baseline is deliberately not here: its values are read from the +/// parent process at spawn time, and the sandbox helper is Linux-only so it +/// never sees a Windows launch. That branch is runner-local. +pub const BASELINE: &[(&str, &str)] = &[ + ("PATH", "/usr/bin:/bin"), + ("LANG", "C.UTF-8"), + ("LC_ALL", "C.UTF-8"), + ("CI", "1"), + ("NO_COLOR", "1"), + ("TERM", "dumb"), + ("GIT_TERMINAL_PROMPT", "0"), + ("PAGER", "cat"), +]; + +/// The enforced `PATH` value on the Linux/Unix contract. +/// +/// A `PATH` that points outside this value widens what a confined target can +/// execute, and the helper's Landlock ruleset does not restrict `execve` by +/// path. The helper refuses a launch whose `PATH` differs; the runner +/// guarantees the value in the child environment and in the launch +/// specification. +/// +/// The contract is Linux/Unix. The Windows baseline is explicitly outside it, +/// so the Windows `PATH` must not be "fixed" to this value. +pub const PATH_VALUE: &str = "/usr/bin:/bin"; + +/// True when `key` is denied: the caller may not set it. +/// +/// The key is ASCII-uppercased first, so the match is case-insensitive, and +/// the entry is matched as an exact match or as a prefix. +pub fn denied_environment_key(key: &str) -> bool { + let upper = key.to_ascii_uppercase(); + DENIED_KEYS + .iter() + .any(|denied| upper == *denied || upper.starts_with(denied)) +} + +/// True when `key` is node-owned on the Unix baseline. +/// +/// The key is ASCII-uppercased first, so a caller's differently-cased spelling +/// of a node-owned key is recognised as the same key. +pub fn is_reserved_key(key: &str) -> bool { + let upper = key.to_ascii_uppercase(); + RESERVED_KEYS.iter().any(|reserved| upper == *reserved) +} + +/// The node's baseline entry for `key`, matched case-insensitively. +/// +/// The returned name is the node's own spelling of the key, so a caller that +/// used a different spelling can be told apart from one that used the node's. +pub fn baseline_entry(key: &str) -> Option<(&'static str, &'static str)> { + let upper = key.to_ascii_uppercase(); + BASELINE + .iter() + .find(|(name, _)| *name == upper) + .map(|(name, value)| (*name, *value)) +} + +/// The node's baseline value for `key`, matched case-insensitively. +/// +/// The value is the node's own; a caller's value for a node-owned key is +/// discarded in favour of it. +pub fn baseline_value(key: &str) -> Option<&'static str> { + baseline_entry(key).map(|(_, value)| value) +} diff --git a/crates/eggwork-runner/src/lib.rs b/crates/eggwork-runner/src/lib.rs index 4ecd365..487e1b6 100644 --- a/crates/eggwork-runner/src/lib.rs +++ b/crates/eggwork-runner/src/lib.rs @@ -39,6 +39,20 @@ use tokio_util::sync::CancellationToken; mod process_tree; +/// The node's environment policy. +/// +/// The policy — the denied-key list and its matching rule, the node-owned +/// (reserved) keys, the node-owned baseline, and the `PATH` value contract — +/// has exactly one owner: `crates/eggwork-runner/policy/environment-policy.toml`. +/// This module is the runner's generated copy of it. +/// +/// The standalone sandbox helper enforces the same policy and may not depend +/// on any workspace crate, so it compiles its own generated copy of the same +/// source. The two copies are pinned together by a parity test, which is what +/// makes a one-sided edit fail the build instead of silently changing what is +/// enforced. +pub mod environment_policy; + use process_tree::{ProcessTree, TreeConvergence}; const READ_BUFFER: usize = 8192; @@ -1877,33 +1891,92 @@ impl LocalProcessRunner { } } -fn denied_environment_key(key: &str) -> bool { - let upper = key.to_ascii_uppercase(); - [ - "LD_", - "DYLD_", - "PATH", - "IFS", - "SHELLOPTS", - "CDPATH", - "BASH_ENV", - "ENV", - "PYTHONPATH", - "PYTHONHOME", - "NODE_OPTIONS", - "RUBYOPT", - "PERL5OPT", - "GIT_ASKPASS", - "SSH_ASKPASS", - "GIT_CONFIG", - "GIT_CONFIG_", - "AWS_", - "AZURE_", - "GOOGLE_", - "SSH_AUTH_SOCK", - ] - .iter() - .any(|denied| upper == *denied || upper.starts_with(denied)) +/// True when the node owns `key` on this platform. +/// +/// The node-owned class is the node's own baseline: the node owns exactly the +/// keys its baseline sets. On the Unix baseline that is +/// `environment_policy::RESERVED_KEYS`, which is the shared policy's class. +/// The Windows baseline is runner-local — its values are read from the parent +/// process at spawn time, and the sandbox helper is Linux-only so it never +/// sees a Windows launch — so it is derived from the baseline the runner +/// actually installs rather than from the shared list. +/// +/// The rule is deliberately *not* "is this key on the deny-list". A deny-list +/// entry is a key the caller may not set at all; a node-owned key is one the +/// node sets itself, and the caller's value for it is discarded in favour of +/// the node's. +fn node_owned_key(key: &str, baseline: &[(&'static str, String)]) -> bool { + baseline + .iter() + .any(|(owned, _)| owned.eq_ignore_ascii_case(key)) +} + +/// The environment a child process receives, built from the shared policy. +/// +/// This is the single place the runner builds an environment, and both of the +/// runner's launch paths use it, so the direct path and the sandbox-helper +/// path cannot disagree about what a child sees. +/// +/// Three rules, in the order they are applied: +/// +/// 1. **The node's baseline wins.** The baseline is installed first and a +/// caller-supplied value for a node-owned key is discarded. Before this +/// rule, a caller that set `LANG` produced a launch specification with two +/// `LANG` entries; the helper refuses a specification with duplicate keys, +/// and a best-effort request answered that pre-target refusal by +/// re-spawning the target with no Landlock ruleset at all. The +/// observable result was a successful, entirely unconfined execution. +/// 2. **A denied key is dropped.** Silently, and only here: the runner is the +/// request-normalisation boundary, and a hardened environment has to be a +/// property of the node rather than something the caller has to get right. +/// The helper refuses a launch that contains one; the difference is a +/// deliberate two-layer contract, and only the list is shared. +/// 3. **Everything else is the caller's**, with a repeated key resolved to +/// its last value. Collapsing the repeat is what keeps the launch +/// specification free of duplicate keys, which the helper refuses. +/// +/// The provenance entries are appended last and are node-owned too: they are +/// neutral attribution, and a caller cannot forge them. +fn build_child_environment(request: &RunnerRequest) -> Vec<(String, String)> { + let baseline = baseline_child_environment(); + let mut environment: Vec<(String, String)> = baseline + .iter() + .map(|(key, value)| ((*key).to_owned(), value.clone())) + .collect(); + for (key, value) in &request.environment { + if environment_policy::denied_environment_key(key) { + continue; + } + if node_owned_key(key, &baseline) { + continue; + } + match environment.iter_mut().find(|(existing, _)| existing == key) { + Some(slot) => slot.1 = value.clone(), + None => environment.push((key.clone(), value.clone())), + } + } + if let Some(id) = &request.provenance.execution_id { + environment.push(("EGGWORK_EXECUTION_ID".into(), id.as_str().into())); + } + if let Some(generation) = request.provenance.generation { + environment.push(( + "EGGWORK_EXECUTION_GENERATION".into(), + generation.get().to_string(), + )); + } + environment +} + +/// The keys the node's own baseline installs for an execution child. +/// +/// The list is derived from the baseline the runner actually uses, so it +/// cannot drift from it: it is the shared policy's Unix class on Unix, and the +/// runner-local Windows class on Windows. +pub fn baseline_environment_keys() -> Vec<&'static str> { + baseline_child_environment() + .into_iter() + .map(|(key, _)| key) + .collect() } fn direct_command(request: &RunnerRequest, cwd: PathBuf) -> Command { @@ -1916,39 +1989,12 @@ fn direct_command(request: &RunnerRequest, cwd: PathBuf) -> Command { .stderr(Stdio::piped()) .kill_on_drop(true); command.env_clear(); - for (key, value) in baseline_child_environment() { + for (key, value) in build_child_environment(request) { command.env(key, value); } - for (key, value) in &request.environment { - if !denied_environment_key(key) { - command.env(key, value); - } - } - if let Some(id) = &request.provenance.execution_id { - command.env("EGGWORK_EXECUTION_ID", id.as_str()); - } - if let Some(generation) = request.provenance.generation { - command.env("EGGWORK_EXECUTION_GENERATION", generation.get().to_string()); - } command } -/// The platform-appropriate minimum environment for an execution child. -/// -/// This baseline is deliberately platform-shaped. It used to declare a -/// Unix-only environment unconditionally, including `PATH=/usr/bin:/bin`, so a -/// Windows child would have been handed a `PATH` that does not exist on -/// Windows and no `SystemRoot`. That shaping was written against the M004 -/// qualification symptom of `state: Failed`, `failure: Internal`, -/// `exit_code: null` -- and it could not have fixed Windows qualification, -/// because at that time no Windows child existed at all: `run` refused with -/// `UnsupportedPlatform` before spawn and the server mapped that refusal to -/// `Internal`. Foundation M004 removed the refusal, which makes this shaping -/// load-bearing instead of merely aspirational. -/// -/// Unix keeps the narrow, deterministic baseline the existing Linux and macOS -/// evidence was gathered with. Windows gets the system directories its loader -/// and `cmd.exe` require, without inheriting the caller's full environment. /// What a settled output monitor means for the running child. /// /// `Some` is a termination reason and ends the wait. `None` means the monitor @@ -1975,27 +2021,56 @@ fn monitor_termination(overflowed: bool) -> Option { overflowed.then_some(TerminationReason::OutputLimit) } +/// The platform-appropriate minimum environment for an execution child. +/// +/// The baseline is the node's own: it is installed before any caller-supplied +/// entry, and a caller-supplied value for a baseline key is discarded in +/// favour of the node's. See `build_child_environment` for the rules. +/// +/// The Unix baseline is the shared policy's, and it is read from the generated +/// policy module rather than written out here, so the runner and the sandbox +/// helper cannot disagree about it. +/// +/// The Windows baseline is deliberately runner-local and platform-shaped. It +/// used to declare a Unix-only environment unconditionally, including +/// `PATH=/usr/bin:/bin`, so a Windows child would have been handed a `PATH` +/// that does not exist on Windows and no `SystemRoot`. That shaping was +/// written against the M004 qualification symptom of `state: Failed`, +/// `failure: Internal`, `exit_code: null` -- and it could not have fixed +/// Windows qualification, because at that time no Windows child existed at +/// all: `run` refused with `UnsupportedPlatform` before spawn and the server +/// mapped that refusal to `Internal`. Foundation M004 removed the refusal, +/// which makes this shaping load-bearing instead of merely aspirational. +/// +/// Windows gets the system directories its loader and `cmd.exe` require, +/// without inheriting the caller's full environment. The Windows `PATH` is +/// deliberately *not* the shared policy's `PATH` value: the `PATH` contract is +/// a Linux/Unix contract, and the sandbox helper never sees a Windows launch. fn baseline_child_environment() -> Vec<(&'static str, String)> { - let mut baseline: Vec<(&'static str, String)> = vec![ - ("CI", "1".to_owned()), - ("NO_COLOR", "1".to_owned()), - ("TERM", "dumb".to_owned()), - ("GIT_TERMINAL_PROMPT", "0".to_owned()), - ("PAGER", "cat".to_owned()), - ]; - #[cfg(not(windows))] - baseline.extend([ - ("PATH", "/usr/bin:/bin".to_owned()), - ("LANG", "C.UTF-8".to_owned()), - ("LC_ALL", "C.UTF-8".to_owned()), - ]); - #[cfg(windows)] - { - let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); - baseline.push(("SystemRoot", system_root.clone())); - baseline.push(("windir", system_root.clone())); - baseline.push(("PATH", format!(r"{system_root}\System32;{system_root}"))); - } + platform_baseline() +} + +/// The Unix baseline: the shared policy's, in the policy's order. +#[cfg(not(windows))] +fn platform_baseline() -> Vec<(&'static str, String)> { + environment_policy::BASELINE + .iter() + .map(|(key, value)| (*key, (*value).to_owned())) + .collect() +} + +/// The Windows baseline: the shared policy's platform-independent part, plus +/// the system directories the loader and `cmd.exe` need. +#[cfg(windows)] +fn platform_baseline() -> Vec<(&'static str, String)> { + let mut baseline: Vec<(&'static str, String)> = environment_policy::BASELINE_COMMON + .iter() + .map(|(key, value)| (*key, (*value).to_owned())) + .collect(); + let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); + baseline.push(("SystemRoot", system_root.clone())); + baseline.push(("windir", system_root.clone())); + baseline.push(("PATH", format!(r"{system_root}\System32;{system_root}"))); baseline } @@ -2085,6 +2160,7 @@ impl SandboxSession { } #[cfg(target_os = "linux")] +#[derive(Debug)] enum SandboxWaitError { BeforeTarget(RunnerError), AfterTarget(RunnerError), @@ -2099,6 +2175,34 @@ impl SandboxWaitError { } } +/// The runner's reading of the helper's first status byte. +/// +/// `Ok(false)` means the helper will not report resource counters and the run +/// continues. `Ok(true)` means the helper applied its mechanics and the second +/// byte says whether the target started. `Err` is a refusal that happened +/// before the target existed, and the byte is carried in the message so an +/// operator can tell an environment-policy refusal (13) apart from the general +/// specification-validation refusal (12) — the two are different failures and +/// a single "the helper refused" line cannot distinguish them. +/// +/// Every refusal, whatever the byte, is a *pre-target* failure: the target did +/// not exist yet, so nothing ran unconfined by accident. What a caller does +/// with that refusal is the caller's decision, and the required path fails +/// closed on it. +#[cfg(target_os = "linux")] +fn classify_helper_status(status: u8) -> Result { + match status { + 0 | 2 | 3 | 30 | 31 => Ok(false), + 1 => Ok(true), + code if code >= 4 => Err(SandboxWaitError::BeforeTarget(RunnerError::Setup(format!( + "sandbox helper rejected its launch specification (status {code})" + )))), + _ => Err(SandboxWaitError::BeforeTarget(RunnerError::Setup( + "sandbox status was invalid".into(), + ))), + } +} + #[cfg(target_os = "linux")] impl SandboxChannel { fn new( @@ -2130,30 +2234,13 @@ impl SandboxChannel { let status_path = directory.path().join("status.sock"); let listener = UnixListener::bind(&status_path) .map_err(|_| RunnerError::Setup("sandbox status channel unavailable".into()))?; - let mut environment = vec![ - ("PATH".into(), "/usr/bin:/bin".into()), - ("LANG".into(), "C.UTF-8".into()), - ("LC_ALL".into(), "C.UTF-8".into()), - ("CI".into(), "1".into()), - ("NO_COLOR".into(), "1".into()), - ("TERM".into(), "dumb".into()), - ("GIT_TERMINAL_PROMPT".into(), "0".into()), - ("PAGER".into(), "cat".into()), - ]; - for (key, value) in &request.environment { - if !denied_environment_key(key) { - environment.push((key.clone(), value.clone())); - } - } - if let Some(id) = &request.provenance.execution_id { - environment.push(("EGGWORK_EXECUTION_ID".into(), id.as_str().into())); - } - if let Some(generation) = request.provenance.generation { - environment.push(( - "EGGWORK_EXECUTION_GENERATION".into(), - generation.get().to_string(), - )); - } + // The launch specification's environment is built by the same function + // that builds the direct child's environment, so the two paths cannot + // disagree about a node-owned key's value. Before that was true, the + // direct path applied the caller's `LANG` *after* the node's baseline + // while the specification carried both, and the helper refused the + // resulting duplicate-key specification. + let environment = build_child_environment(request); let spec = SandboxLaunchSpec { schema_version: 1, profile, @@ -2223,10 +2310,15 @@ impl SandboxChannel { .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true) - .env_clear() - .env("PATH", "/usr/bin:/bin") - .env("LANG", "C.UTF-8") - .env("LC_ALL", "C.UTF-8"); + .env_clear(); + // The helper's own environment is the node's baseline, from the same + // shared policy the target's environment is built from. `env_clear()` + // matters here: the helper must not inherit the daemon's `LD_*`, + // `GIT_*`, or cloud variables while it is parsing a specification that + // a deny-list was supposed to keep clean. + for (key, value) in environment_policy::BASELINE { + command.env(key, value); + } command } @@ -2250,10 +2342,9 @@ impl SandboxChannel { result .map_err(|_| SandboxWaitError::BeforeTarget(RunnerError::Setup("sandbox status timed out".into())))? .map_err(|_| SandboxWaitError::BeforeTarget(RunnerError::Setup("sandbox status channel failed".into())))?; - match status[0] { - 0 | 2 | 3 | 30 | 31 => Ok(None), - code if code >= 4 => Err(SandboxWaitError::BeforeTarget(RunnerError::Setup(format!("sandbox helper rejected its launch specification (status {code})")))), - 1 => { + match classify_helper_status(status[0]) { + Ok(false) => Ok(None), + Ok(true) => { let mut target_spawned = [0u8; 1]; tokio::select! { _ = cancellation.cancelled() => return Err(SandboxWaitError::AfterTarget(RunnerError::CancelledBeforeSpawn)), @@ -2269,7 +2360,7 @@ impl SandboxChannel { _ => Err(SandboxWaitError::AfterTarget(RunnerError::Setup("sandbox status was invalid".into()))), } } - _ => Err(SandboxWaitError::BeforeTarget(RunnerError::Setup("sandbox status was invalid".into()))), + Err(error) => Err(error), } } } @@ -2795,4 +2886,266 @@ mod tests { let runtime = setup.execution_capabilities().await; assert!(runtime.is_empty()); } + + /// The node-owned class is the node's own baseline. + /// + /// If the two could drift, the runner would discard a caller's value for a + /// key the helper still expects to carry the node's value, and the helper + /// would refuse the launch — the same collision that used to cost a + /// best-effort execution its confinement. + #[test] + fn the_node_owned_class_is_the_node_owned_baseline() { + let baseline_keys: Vec<&str> = environment_policy::BASELINE + .iter() + .map(|(key, _)| *key) + .collect(); + assert_eq!( + environment_policy::RESERVED_KEYS, + baseline_keys.as_slice(), + "the node-owned class and the node-owned baseline must be the same set" + ); + for (key, value) in environment_policy::BASELINE { + assert_eq!( + environment_policy::baseline_value(key), + Some(*value), + "the baseline value of {key} must be the policy's value" + ); + assert!( + environment_policy::is_reserved_key(key), + "{key} is in the baseline and must be node-owned" + ); + } + } + + /// A caller's value for a node-owned key never reaches the child. + /// + /// The live defect was that the caller's `LANG` was *appended* to the + /// node's baseline, so the child saw the caller's locale and the launch + /// specification carried two `LANG` entries. + #[test] + fn a_caller_supplied_node_owned_key_does_not_replace_the_node_value() { + let root = tempfile::tempdir().expect("temp dir"); + let mut req = request(root.path(), &["/bin/sh", "-c", "true"]); + req.environment = vec![ + ("LANG".into(), "en_US.UTF-8".into()), + ("LC_ALL".into(), "en_US.UTF-8".into()), + ("CI".into(), "false".into()), + ("lang".into(), "de_DE.UTF-8".into()), + ]; + let environment = build_child_environment(&req); + for key in ["LANG", "LC_ALL", "CI"] { + let matching: Vec<&String> = environment + .iter() + .filter(|(name, _)| name == key) + .map(|(_, value)| value) + .collect(); + assert_eq!( + matching.len(), + 1, + "{key} must appear exactly once in the child environment" + ); + assert_eq!( + matching[0], + environment_policy::baseline_value(key).expect("baseline value"), + "{key} must carry the node's value" + ); + } + assert!( + !environment.iter().any(|(name, _)| name == "lang"), + "a differently-cased spelling of a node-owned key is the same key" + ); + } + + /// A denied key is dropped, and only dropped. + /// + /// The runner is the request-normalisation boundary: it drops the key + /// silently and says nothing, because a hardened environment has to be a + /// property of the node rather than something the caller has to get right. + /// The helper's refusal is a different layer and a different behaviour. + #[test] + fn a_caller_supplied_denied_key_does_not_reach_the_child() { + let root = tempfile::tempdir().expect("temp dir"); + let mut req = request(root.path(), &["/bin/sh", "-c", "true"]); + req.environment = vec![ + ("LD_PRELOAD".into(), "/tmp/evil.so".into()), + ("AWS_SECRET_ACCESS_KEY".into(), "secret".into()), + ("PYTHONPATH".into(), "/tmp".into()), + ("KEEP_ME".into(), "kept".into()), + ]; + let environment = build_child_environment(&req); + for denied in ["LD_PRELOAD", "AWS_SECRET_ACCESS_KEY", "PYTHONPATH"] { + assert!( + !environment.iter().any(|(name, _)| name == denied), + "{denied} must not reach the child" + ); + } + assert!( + environment + .iter() + .any(|(name, value)| name == "KEEP_ME" && value == "kept"), + "a caller-controlled key must reach the child" + ); + } + + /// A repeated caller key is resolved to its last value. + /// + /// The launch specification must not carry a duplicate key: the helper + /// refuses a specification that does, and a best-effort request answers + /// that refusal by re-spawning the target with no Landlock ruleset. + #[test] + fn a_repeated_caller_key_is_resolved_to_one_entry() { + let root = tempfile::tempdir().expect("temp dir"); + let mut req = request(root.path(), &["/bin/sh", "-c", "true"]); + req.environment = vec![ + ("REPEATED".into(), "first".into()), + ("REPEATED".into(), "second".into()), + ]; + let environment = build_child_environment(&req); + let matching: Vec<&String> = environment + .iter() + .filter(|(name, _)| name == "REPEATED") + .map(|(_, value)| value) + .collect(); + assert_eq!(matching, vec!["second"]); + } + + /// The launch specification carries exactly one entry per node-owned key, + /// with the node's value. + /// + /// This is the regression for the live defect. The helper refuses a + /// specification with duplicate keys, so a specification that carried the + /// caller's `LANG` *and* the node's `LANG` was refused with status 12, + /// and a best-effort request then ran the target with no Landlock ruleset + /// at all. + #[cfg(target_os = "linux")] + #[tokio::test] + async fn the_launch_specification_carries_one_entry_per_node_owned_key() { + let root = tempfile::tempdir().expect("temp dir"); + let mut req = request(root.path(), &["/bin/sh", "-c", "true"]); + req.sandbox = SandboxRequest::BestEffort { + profile: "workspace_rw".into(), + }; + req.environment = vec![("LANG".into(), "en_US.UTF-8".into())]; + let channel = SandboxChannel::new( + Path::new("/nonexistent/eggwork-sandbox-helper"), + &req, + root.path().to_path_buf(), + false, + ) + .expect("sandbox channel"); + let spec: serde_json::Value = + serde_json::from_slice(&std::fs::read(channel.spec_path).expect("spec")) + .expect("spec json"); + let environment = spec["environment"] + .as_array() + .expect("environment array") + .iter() + .map(|entry| { + ( + entry[0].as_str().expect("key").to_owned(), + entry[1].as_str().expect("value").to_owned(), + ) + }) + .collect::>(); + for key in environment_policy::RESERVED_KEYS { + let matching: Vec<&String> = environment + .iter() + .filter(|(name, _)| name == *key) + .map(|(_, value)| value) + .collect(); + assert_eq!( + matching.len(), + 1, + "the specification must carry exactly one {key}" + ); + assert_eq!( + matching[0], + environment_policy::baseline_value(key).expect("baseline value"), + "the specification's {key} must carry the node's value" + ); + } + assert_eq!( + environment_policy::PATH_VALUE, + "/usr/bin:/bin", + "the `PATH` contract is a Linux/Unix contract" + ); + assert!( + environment + .iter() + .any(|(name, value)| name == "PATH" && value == environment_policy::PATH_VALUE), + "the specification's PATH must carry the contract value" + ); + } + + /// The direct path and the launch specification agree. + /// + /// They used to disagree: the direct path applied the caller's `LANG` + /// after the node's baseline, so the child saw the caller's locale, while + /// the specification carried both entries and was refused. + #[cfg(target_os = "linux")] + #[tokio::test] + async fn the_direct_path_and_the_launch_specification_agree() { + let root = tempfile::tempdir().expect("temp dir"); + let mut req = request(root.path(), &["/bin/sh", "-c", "true"]); + req.sandbox = SandboxRequest::BestEffort { + profile: "workspace_rw".into(), + }; + req.environment = vec![ + ("LANG".into(), "en_US.UTF-8".into()), + ("CI".into(), "false".into()), + ("CALLER_KEY".into(), "caller".into()), + ]; + let direct = build_child_environment(&req); + let channel = SandboxChannel::new( + Path::new("/nonexistent/eggwork-sandbox-helper"), + &req, + root.path().to_path_buf(), + false, + ) + .expect("sandbox channel"); + let spec: serde_json::Value = + serde_json::from_slice(&std::fs::read(channel.spec_path).expect("spec")) + .expect("spec json"); + let specified = spec["environment"] + .as_array() + .expect("environment array") + .iter() + .map(|entry| { + ( + entry[0].as_str().expect("key").to_owned(), + entry[1].as_str().expect("value").to_owned(), + ) + }) + .collect::>(); + assert_eq!(direct, specified); + } + + /// The environment-policy refusal is its own status, and the runner + /// treats it as a failure that happened before the target existed. + #[cfg(target_os = "linux")] + #[test] + fn the_helper_status_bytes_classify_a_refusal_before_the_target() { + for (byte, expected) in [ + (0u8, false), + (2, false), + (3, false), + (30, false), + (31, false), + ] { + assert!( + matches!(classify_helper_status(byte), Ok(value) if value == expected), + "status {byte} must not be a refusal" + ); + } + assert!(matches!(classify_helper_status(1), Ok(true))); + for code in [12u8, 13] { + match classify_helper_status(code) { + Err(SandboxWaitError::BeforeTarget(RunnerError::Setup(message))) => assert!( + message.contains(&format!("status {code}")), + "the refusal must name its status byte: {message}" + ), + _ => panic!("status {code} must be a pre-target refusal"), + } + } + } } diff --git a/crates/eggwork-runner/tests/environment_policy.rs b/crates/eggwork-runner/tests/environment_policy.rs new file mode 100644 index 0000000..82e0614 --- /dev/null +++ b/crates/eggwork-runner/tests/environment_policy.rs @@ -0,0 +1,206 @@ +//! The runner's environment construction, observed through its public API. +//! +//! The runner builds a child's environment in one place, and both of its +//! launch paths — the direct path and the sandbox-helper path — use it. The +//! rules it applies come from the shared environment policy, whose single +//! owner is `crates/eggwork-runner/policy/environment-policy.toml` and whose +//! generated copy this crate compiles. +//! +//! The live defect these tests close was that the caller's `LANG` was +//! *appended* to the node's baseline. The child saw the caller's locale, the +//! launch specification carried two `LANG` entries, the helper refused the +//! specification, and — for a best-effort request only — the runner answered +//! that pre-target refusal by re-spawning the target directly with no +//! Landlock ruleset at all. The observable result was a successful, entirely +//! unconfined execution whose only record of the degradation was a `NotApplied` +//! in the terminal snapshot. +//! +//! The helper-side half of that proof — that the helper *accepts* the +//! resulting specification and that the execution keeps its confinement — is +//! in `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs`, +//! because it needs the real helper executable. + +use eggwork_core::{OverflowPolicy, Requirement}; +use eggwork_runner::{ + LocalProcessRunner, NoExecutionSetup, ResourceSetupRequest, RunnerRequest, SandboxRequest, + StdinPolicy, environment_policy, +}; +use std::path::Path; +use std::time::Duration; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +/// The environment the child actually received, sorted. +async fn observed_environment(root: &Path, environment: Vec<(String, String)>) -> Vec { + let mut request = RunnerRequest::new(vec!["/bin/sh".into(), "-c".into(), "env".into()], root); + request.set_environment(environment); + request.set_stdin_policy(StdinPolicy::Null); + request.set_timeout(Duration::from_secs(20)); + request.set_output_policy(16384, 4096, OverflowPolicy::Truncate); + request.set_sandbox_request(SandboxRequest::BestEffort { + profile: "workspace_rw".into(), + }); + request.set_resource_setup_request(ResourceSetupRequest { + memory_bytes: Requirement::NotRequested, + cpu_millis: Requirement::NotRequested, + pids: Requirement::NotRequested, + }); + let (tx, _rx) = mpsc::channel(8); + let result = LocalProcessRunner::new(NoExecutionSetup) + .run(request, CancellationToken::new(), tx) + .await + .expect("the execution runs"); + let mut lines: Vec = String::from_utf8_lossy(&result.stdout.head) + .lines() + .map(str::to_owned) + .collect(); + lines.sort(); + lines +} + +/// The policy module is the shared contract, and it is reachable from the +/// runner's public API. +/// +/// The standalone sandbox helper enforces the same policy and may not depend +/// on any workspace crate, so it compiles a generated copy of the same source. +/// The two copies are pinned together by a parity test; this test is what +/// makes the runner's copy reachable from outside the crate, which is what +/// that parity test compares against. +#[test] +fn the_policy_is_reachable_from_the_runner_public_api() { + assert!( + !environment_policy::DENIED_KEYS.is_empty(), + "the denied-key list must not be empty" + ); + assert_eq!( + environment_policy::MATCH_RULE, + "ascii-uppercase-exact-or-prefix", + "the matching rule is part of the contract, not an implementation detail" + ); + assert_eq!( + environment_policy::PATH_VALUE, + "/usr/bin:/bin", + "the `PATH` contract is a Linux/Unix contract with one value" + ); + for entry in ["LD_", "PATH", "IFS", "GIT_CONFIG_", "AWS_", "SSH_AUTH_SOCK"] { + assert!( + environment_policy::DENIED_KEYS.contains(&entry), + "{entry} is part of the reviewed deny-list and must not have been dropped" + ); + } +} + +/// The node-owned class and the node's own baseline are the same set. +/// +/// If they could differ, the runner would discard a caller's value for a key +/// the helper still expected to carry the node's value, and the helper would +/// refuse the launch. +#[test] +fn the_node_owned_class_is_the_node_owned_baseline() { + let baseline_keys: Vec<&str> = environment_policy::BASELINE + .iter() + .map(|(key, _)| *key) + .collect(); + assert_eq!( + environment_policy::RESERVED_KEYS, + baseline_keys.as_slice(), + "the node-owned class and the node-owned baseline must be the same list" + ); +} + +/// The baseline the runner installs is the policy's baseline. +/// +/// On Unix the two are the same list; the Windows baseline is runner-local, +/// and this suite runs on Unix. +#[cfg(unix)] +#[test] +fn the_installed_baseline_is_the_policy_baseline() { + let installed = eggwork_runner::baseline_environment_keys(); + let policy: Vec<&str> = environment_policy::BASELINE + .iter() + .map(|(key, _)| *key) + .collect(); + assert_eq!(installed, policy); +} + +/// A caller's value for a node-owned key does not reach the child. +/// +/// This is the regression for the live defect, observed on the direct path. +#[cfg(unix)] +#[tokio::test] +async fn a_caller_supplied_node_owned_key_does_not_reach_the_child() { + let root = tempfile::tempdir().expect("temp dir"); + let observed = observed_environment( + root.path(), + vec![ + ("LANG".into(), "en_US.UTF-8".into()), + ("LC_ALL".into(), "en_US.UTF-8".into()), + ("CI".into(), "false".into()), + ("TERM".into(), "xterm".into()), + ("PAGER".into(), "less".into()), + ], + ) + .await; + for key in environment_policy::RESERVED_KEYS { + let expected = environment_policy::baseline_value(key).expect("baseline value"); + assert!( + observed.contains(&format!("{key}={expected}")), + "the child must carry the node's {key}: {observed:?}" + ); + } + assert!( + !observed.iter().any(|entry| entry.starts_with("LANG=en_US")), + "the caller's LANG must not reach the child: {observed:?}" + ); + assert_eq!( + observed + .iter() + .filter(|entry| entry.starts_with("LANG=")) + .count(), + 1, + "the child must see exactly one LANG: {observed:?}" + ); +} + +/// A denied key does not reach the child. +/// +/// The runner drops it silently: it is the request-normalisation boundary. The +/// helper's refusal of the same key is a different layer and a different +/// behaviour, and only the list is shared between them. +#[cfg(unix)] +#[tokio::test] +async fn a_caller_supplied_denied_key_does_not_reach_the_child() { + let root = tempfile::tempdir().expect("temp dir"); + let observed = observed_environment( + root.path(), + vec![ + ("LD_PRELOAD".into(), "/tmp/evil.so".into()), + ("AWS_SECRET_ACCESS_KEY".into(), "secret".into()), + ("PYTHONPATH".into(), "/tmp".into()), + ("CALLER_KEY".into(), "kept".into()), + ], + ) + .await; + assert!( + !observed + .iter() + .any(|entry| entry.starts_with("LD_PRELOAD=")), + "a denied key must not reach the child: {observed:?}" + ); + assert!( + !observed + .iter() + .any(|entry| entry.starts_with("AWS_SECRET_ACCESS_KEY=")), + "a denied key must not reach the child: {observed:?}" + ); + assert!( + !observed + .iter() + .any(|entry| entry.starts_with("PYTHONPATH=")), + "a denied key must not reach the child: {observed:?}" + ); + assert!( + observed.iter().any(|entry| entry == "CALLER_KEY=kept"), + "a caller-controlled key must reach the child: {observed:?}" + ); +} diff --git a/crates/eggwork-runner/tests/windows_process_tree.rs b/crates/eggwork-runner/tests/windows_process_tree.rs index 2652268..2308eb3 100644 --- a/crates/eggwork-runner/tests/windows_process_tree.rs +++ b/crates/eggwork-runner/tests/windows_process_tree.rs @@ -48,19 +48,15 @@ const INTERRUPT_AFTER: Duration = Duration::from_millis(3000); /// Generous ceiling for fixtures that are supposed to finish on their own. const PATIENCE: Duration = Duration::from_secs(120); -/// The environment every execution child is guaranteed to see. Kept in sync -/// with `baseline_child_environment` in the crate; a mismatch is a contract -/// change, not a test fix. -const BASELINE_KEYS: [&str; 8] = [ - "CI", - "GIT_TERMINAL_PROMPT", - "NO_COLOR", - "PAGER", - "PATH", - "SystemRoot", - "TERM", - "windir", -]; +/// The environment every execution child is guaranteed to see. +/// +/// The list is the runner's own baseline, not a copy of it: the runner +/// derives it from the node-owned baseline it actually installs, so this +/// suite cannot drift from the crate the way a hand-written list can. A +/// mismatch here is a contract change, not a test fix. +fn baseline_keys() -> Vec<&'static str> { + eggwork_runner::baseline_environment_keys() +} fn cmd() -> String { std::env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_owned()) @@ -537,9 +533,10 @@ async fn environment_is_the_documented_baseline_and_leaks_nothing() { let synthesised_by_cmd: [&str; 3] = ["COMSPEC", "PATHEXT", "PROMPT"]; let system_root = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".to_owned()); - for key in BASELINE_KEYS { + let baseline_keys = baseline_keys(); + for key in &baseline_keys { assert!( - child_keys.contains(&key), + child_keys.contains(key), "baseline key {key} missing from the child environment: {child_keys:?}" ); } @@ -556,7 +553,7 @@ async fn environment_is_the_documented_baseline_and_leaks_nothing() { .iter() .copied() .filter(|key| std::env::var_os(key).is_some()) - .filter(|key| !BASELINE_KEYS.contains(key)) + .filter(|key| !baseline_keys.contains(key)) .filter(|key| !synthesised_by_cmd.contains(key)) .collect(); assert!( diff --git a/crates/eggwork-sandbox-helper/src/environment_policy.rs b/crates/eggwork-sandbox-helper/src/environment_policy.rs new file mode 100644 index 0000000..bf0781f --- /dev/null +++ b/crates/eggwork-sandbox-helper/src/environment_policy.rs @@ -0,0 +1,170 @@ +// @generated by scripts/generate_environment_policy.py — do not edit. +// +// Source of truth: crates/eggwork-runner/policy/environment-policy.toml +// Generator: scripts/generate_environment_policy.py +// +// This file is generated. A hand edit is a contract change, not a local +// fix: change the source of truth and re-run the generator. +// +// This is the sandbox helper's copy. The other copy is generated from the same +// source of truth, and a parity test pins the two together, so a one-sided +// edit fails the build rather than silently changing what is enforced. + +/// The keys a caller may not set. +/// +/// The runner drops one of these silently: it is the request-normalisation +/// boundary, and a hardened environment has to be a property of the node +/// rather than something the caller has to get right. The helper refuses the +/// whole launch when one of these is present: it is the enforcement point, and +/// a denied key reaching it means the node's own filtering did not happen. +/// The difference is deliberate and is the whole two-layer contract; only the +/// list is shared, never the behaviour. +pub const DENIED_KEYS: &[&str] = &[ + "LD_", + "DYLD_", + "PATH", + "IFS", + "SHELLOPTS", + "CDPATH", + "BASH_ENV", + "ENV", + "PYTHONPATH", + "PYTHONHOME", + "NODE_OPTIONS", + "RUBYOPT", + "PERL5OPT", + "GIT_ASKPASS", + "SSH_ASKPASS", + "GIT_CONFIG", + "GIT_CONFIG_", + "AWS_", + "AZURE_", + "GOOGLE_", + "SSH_AUTH_SOCK", +]; + +/// The rule used to match an environment key against `DENIED_KEYS` and against +/// the node-owned class: ASCII-uppercase the key, then match it as an exact +/// match or as a prefix. +/// +/// The rule is part of the contract, not an implementation detail: the two +/// copies must agree on it, or the runner would drop a key the helper still +/// refuses. +pub const MATCH_RULE: &str = "ascii-uppercase-exact-or-prefix"; + +/// The node-owned (reserved) keys on the Unix baseline. +/// +/// A caller-supplied value for one of these is discarded in favour of the +/// node's value, so the node's baseline is what reaches the child and a +/// launch specification can never carry a duplicate of a baseline key. +/// +/// The class is the node-owned baseline, and the baseline is platform-shaped: +/// on the Windows baseline the node owns `SystemRoot`, `windir` and `PATH` +/// instead of the Unix locale keys, and that branch is runner-local. +pub const RESERVED_KEYS: &[&str] = &[ + "PATH", + "LANG", + "LC_ALL", + "CI", + "NO_COLOR", + "TERM", + "GIT_TERMINAL_PROMPT", + "PAGER", +]; + +/// The node-owned baseline keys every platform carries. +/// +/// The values are the node's own; a caller cannot move them. This is the +/// part of the Unix baseline the runner's Windows branch also installs, so +/// the Windows branch does not have to re-list it. +pub const BASELINE_COMMON: &[(&str, &str)] = &[ + ("CI", "1"), + ("NO_COLOR", "1"), + ("TERM", "dumb"), + ("GIT_TERMINAL_PROMPT", "0"), + ("PAGER", "cat"), +]; + +/// The node-owned Unix baseline, in the order the node installs it. +/// +/// The Windows baseline is deliberately not here: its values are read from the +/// parent process at spawn time, and the sandbox helper is Linux-only so it +/// never sees a Windows launch. That branch is runner-local. +pub const BASELINE: &[(&str, &str)] = &[ + ("PATH", "/usr/bin:/bin"), + ("LANG", "C.UTF-8"), + ("LC_ALL", "C.UTF-8"), + ("CI", "1"), + ("NO_COLOR", "1"), + ("TERM", "dumb"), + ("GIT_TERMINAL_PROMPT", "0"), + ("PAGER", "cat"), +]; + +/// The enforced `PATH` value on the Linux/Unix contract. +/// +/// A `PATH` that points outside this value widens what a confined target can +/// execute, and the helper's Landlock ruleset does not restrict `execve` by +/// path. The helper refuses a launch whose `PATH` differs; the runner +/// guarantees the value in the child environment and in the launch +/// specification. +/// +/// The contract is Linux/Unix. The Windows baseline is explicitly outside it, +/// so the Windows `PATH` must not be "fixed" to this value. +pub const PATH_VALUE: &str = "/usr/bin:/bin"; + +/// True when `key` is denied: the caller may not set it. +/// +/// The key is ASCII-uppercased first, so the match is case-insensitive, and +/// the entry is matched as an exact match or as a prefix. +pub fn denied_environment_key(key: &str) -> bool { + let upper = key.to_ascii_uppercase(); + DENIED_KEYS + .iter() + .any(|denied| upper == *denied || upper.starts_with(denied)) +} + +/// True when `key` is node-owned on the Unix baseline. +/// +/// The key is ASCII-uppercased first, so a caller's differently-cased spelling +/// of a node-owned key is recognised as the same key. +pub fn is_reserved_key(key: &str) -> bool { + let upper = key.to_ascii_uppercase(); + RESERVED_KEYS.iter().any(|reserved| upper == *reserved) +} + +/// The node's baseline entry for `key`, matched case-insensitively. +/// +/// The returned name is the node's own spelling of the key, so a caller that +/// used a different spelling can be told apart from one that used the node's. +pub fn baseline_entry(key: &str) -> Option<(&'static str, &'static str)> { + let upper = key.to_ascii_uppercase(); + BASELINE + .iter() + .find(|(name, _)| *name == upper) + .map(|(name, value)| (*name, *value)) +} + +/// The node's baseline value for `key`, matched case-insensitively. +/// +/// The value is the node's own; a caller's value for a node-owned key is +/// discarded in favour of it. +pub fn baseline_value(key: &str) -> Option<&'static str> { + baseline_entry(key).map(|(_, value)| value) +} + +/// The protocol limit constants, generated from `eggwork-core`. +/// +/// The helper is a standalone binary with no workspace-crate dependency, so it +/// cannot import `eggwork_core::MAX_ARG_COUNT` and friends. The generator reads +/// these values out of the owner of the wire limits, so the helper's copy is +/// generated rather than hand-maintained, and a parity test compares them +/// against `eggwork-core` at run time. +/// +/// `MAX_SPEC_BYTES` is helper-only, has no core counterpart, and stays in the +/// helper's own source. +pub const MAX_ARG_COUNT: usize = 256; +pub const MAX_ARG_BYTES: usize = 32768; +pub const MAX_ENV_COUNT: usize = 256; +pub const MAX_ENV_NAME_BYTES: usize = 256; +pub const MAX_ENV_VALUE_BYTES: usize = 16384; diff --git a/crates/eggwork-sandbox-helper/src/main.rs b/crates/eggwork-sandbox-helper/src/main.rs index 72acc2d..2b1861f 100644 --- a/crates/eggwork-sandbox-helper/src/main.rs +++ b/crates/eggwork-sandbox-helper/src/main.rs @@ -1,8 +1,25 @@ #![forbid(unsafe_code)] +/// The node's environment policy. +/// +/// The helper is a standalone binary and may not depend on any workspace +/// crate, so it cannot share the policy as a library. It compiles a generated +/// copy of the same source of truth the runner uses, and a parity test pins +/// the two copies together so a one-sided edit fails the build. +/// +/// The copy carries the whole shared contract and this crate uses only part of +/// it — the helper does not build the runner's baseline, and the runner does +/// not enforce the `PATH` value the way the helper does — so the unused items +/// are part of the contract rather than leftovers. +#[allow(dead_code)] +mod environment_policy; + #[cfg(target_os = "linux")] mod linux { + use crate::environment_policy::{ + self, MAX_ARG_BYTES, MAX_ARG_COUNT, MAX_ENV_COUNT, MAX_ENV_NAME_BYTES, MAX_ENV_VALUE_BYTES, + }; use landlock::{ ABI, Access, AccessFs, PathBeneath, PathFd, RestrictionStatus, Ruleset, RulesetAttr, RulesetCreatedAttr, RulesetStatus, @@ -17,12 +34,11 @@ mod linux { process::{Command, ExitStatus}, }; + /// The helper's own bound on the specification file. + /// + /// It is helper-only: `eggwork-core` owns the wire limits and has no + /// counterpart for this one, so it stays here rather than being generated. const MAX_SPEC_BYTES: u64 = 1024 * 1024; - const MAX_ARG_COUNT: usize = 256; - const MAX_ARG_BYTES: usize = 32 * 1024; - const MAX_ENV_COUNT: usize = 256; - const MAX_ENV_NAME_BYTES: usize = 256; - const MAX_ENV_VALUE_BYTES: usize = 16 * 1024; /// Bit 2 of the post-mortem status byte: at least one counter the caller /// asked about could not be opened, so "no limit was exceeded" is unknown @@ -104,7 +120,7 @@ mod linux { .args(argv) .current_dir(&spec.cwd) .env_clear() - .env("PATH", "/usr/bin:/bin") + .env("PATH", environment_policy::PATH_VALUE) .envs( spec.environment .iter() @@ -174,9 +190,23 @@ mod linux { || key.contains('=') || key.contains('\0') || value.contains('\0') - || denied_environment_key(key) && key != "PATH" - || key == "PATH" && value != "/usr/bin:/bin" }) + { + return Err(12); + } + // The environment is judged against the shared environment policy, and + // it gets its own status byte so an operator can tell an + // environment-policy refusal apart from a specification that is + // malformed in some other way. Before the policy was shared, the + // collision of a caller's `LANG` with the node's own `LANG` produced a + // specification with two `LANG` entries, this refusal, and — for a + // best-effort request — a re-spawn of the target with no Landlock + // ruleset at all. The status byte is what makes that class of refusal + // legible; the shared policy is what stops it happening. + if spec + .environment + .iter() + .any(|(key, value)| environment_policy_refuses(key, value)) || spec .environment .iter() @@ -185,9 +215,9 @@ mod linux { .len() != spec.environment.len() { - return Err(12); + return Err(13); } - let root = spec.root.canonicalize().map_err(|_| 13u8)?; + let root = spec.root.canonicalize().map_err(|_| 17u8)?; let cwd = spec.cwd.canonicalize().map_err(|_| 14u8)?; if root != spec.root || !root.is_dir() || !cwd.starts_with(&root) || !cwd.is_dir() { return Err(15); @@ -268,33 +298,38 @@ mod linux { .unwrap_or_else(|| 128 + status.signal().unwrap_or(0)) } - fn denied_environment_key(key: &str) -> bool { - let upper = key.to_ascii_uppercase(); - [ - "LD_", - "DYLD_", - "PATH", - "IFS", - "SHELLOPTS", - "CDPATH", - "BASH_ENV", - "ENV", - "PYTHONPATH", - "PYTHONHOME", - "NODE_OPTIONS", - "RUBYOPT", - "PERL5OPT", - "GIT_ASKPASS", - "SSH_ASKPASS", - "GIT_CONFIG", - "GIT_CONFIG_", - "AWS_", - "AZURE_", - "GOOGLE_", - "SSH_AUTH_SOCK", - ] - .iter() - .any(|denied| upper == *denied || upper.starts_with(denied)) + /// The environment policy's refusal rule, in one place. + /// + /// The runner *drops* a denied key; the helper *refuses the launch*. That + /// difference is deliberate and is the whole two-layer contract: the + /// runner is the request-normalisation boundary, and the helper is the + /// enforcement point, so a denied key arriving here means the node's own + /// filtering did not happen. Only the list is shared, never the behaviour. + /// + /// Three rules, all read out of the shared policy: + /// + /// * a denied key may not be present at all. `PATH` is the single + /// exception, because it is denied as a *caller-controlled* key while + /// the node pins its value; + /// * a `PATH` that is not the contract value widens what a confined target + /// can execute, and the Landlock ruleset does not restrict `execve` by + /// path; + /// * a node-owned key must carry the node's value, and it must carry it + /// under the node's own spelling. A specification that disagreed with + /// the node's baseline is a specification the runner did not build. + fn environment_policy_refuses(key: &str, value: &str) -> bool { + if key != "PATH" && environment_policy::denied_environment_key(key) { + return true; + } + if key == "PATH" && value != environment_policy::PATH_VALUE { + return true; + } + if let Some((name, expected)) = environment_policy::baseline_entry(key) + && (name != key || value != expected) + { + return true; + } + false } struct ResourceEvents { diff --git a/crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs b/crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs new file mode 100644 index 0000000..d3662cd --- /dev/null +++ b/crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs @@ -0,0 +1,670 @@ +//! The environment-policy parity gate. +//! +//! The node's environment policy — the denied-key list and its matching rule, +//! the node-owned (reserved) keys, the node-owned baseline, and the `PATH` +//! value contract — has one owner: `crates/eggwork-runner/policy/environment-policy.toml`. +//! The runner compiles a generated copy of it. The sandbox helper is a +//! standalone binary that may not depend on any workspace crate, so it +//! compiles a generated copy of the *same* source. +//! +//! Two copies of one contract is a hole unless something pins them together. +//! What pins them is this file, and it does so in two independent ways: +//! +//! 1. **Element by element.** The helper's own generated module is compiled +//! into this test, and compared with the runner's public copy, entry by +//! entry, in order. A one-sided edit to either copy fails here. +//! 2. **Behaviourally.** The *real* helper executable is driven with a launch +//! specification for every probe key, and its accept/refuse decision is +//! compared with what the runner's copy of the policy says. A one-sided +//! edit that changed a rule rather than a list fails here, and so does an +//! edit that changed the matching rule itself. +//! +//! The second is the one that matters. A structural comparison of two files +//! proves that two files are alike; it does not prove that the helper enforces +//! the policy the runner applies. The live defect was exactly that gap: the +//! runner appended the caller's `LANG` to the node's baseline, so the launch +//! specification carried two `LANG` entries, the helper refused the +//! specification, and a best-effort request answered that pre-target refusal +//! by re-spawning the target with no Landlock ruleset at all. The observable +//! result was a successful, entirely unconfined execution whose only record of +//! the degradation was a `NotApplied` in the terminal snapshot. +//! +//! The element-wise part of this file is platform-independent on purpose: the +//! lists are platform-independent, and the parity gate must run everywhere. +//! Only the behavioural part needs Linux, because only Linux has a helper that +//! enforces anything. +#![allow(dead_code)] + +/// The helper's own generated copy of the policy, compiled into this test. +/// +/// This is the file the helper binary itself compiles, not a copy of it, so an +/// edit to the helper's generated copy is an edit to what this test compares. +#[path = "../src/environment_policy.rs"] +mod helper_policy; + +use eggwork_runner::environment_policy as runner_policy; + +/// The shared fixture that stages a *trusted* sandbox helper. +/// +/// It is included at the top level rather than inside the Linux module because +/// a `#[path]` inside an inline module resolves against that module's own +/// directory, which does not exist here. +#[cfg(target_os = "linux")] +#[path = "support/helper_fixture.rs"] +mod helper_fixture; + +/// The runner's policy, stated over a launch specification rather than over a +/// request. +/// +/// The runner *drops* a denied key, *replaces* a node-owned key's value with +/// the node's, and passes everything else through. The helper refuses a +/// specification that does not already reflect that, because the helper is the +/// enforcement point and the runner is the request-normalisation boundary. +/// Only the list is shared between them; the behaviour deliberately is not. +/// +/// This is the contract, written against the *runner's* copy of the policy. The +/// helper enforces the same contract with its own copy, and the difference +/// between the two is what this test measures. +fn the_runner_policy_refuses(key: &str, value: &str) -> bool { + if key != "PATH" && runner_policy::denied_environment_key(key) { + return true; + } + if key == "PATH" && value != runner_policy::PATH_VALUE { + return true; + } + if let Some((name, expected)) = runner_policy::baseline_entry(key) + && (name != key || value != expected) + { + return true; + } + false +} + +/// The denied-key list is the same list, in the same order, in both copies. +/// +/// A mismatch is a contract change, not a test to be adjusted: the two copies +/// are the same contract, and a one-sided edit means one side now enforces +/// something the other side does not. +#[test] +fn the_denied_key_list_is_the_same_list_in_the_same_order() { + assert_eq!( + runner_policy::DENIED_KEYS.len(), + helper_policy::DENIED_KEYS.len(), + "the runner and the helper carry different numbers of denied keys; a mismatch is a \ + contract change, not a test to be adjusted" + ); + for (index, (runner, helper)) in runner_policy::DENIED_KEYS + .iter() + .zip(helper_policy::DENIED_KEYS.iter()) + .enumerate() + { + assert_eq!( + runner, helper, + "denied-key entry {index} differs: the runner's copy has {runner:?} and the \ + helper's has {helper:?}. A mismatch is a contract change, not a test to be adjusted" + ); + } +} + +/// The node-owned class is the same class, in the same order, in both copies. +#[test] +fn the_node_owned_class_is_the_same_class_in_the_same_order() { + assert_eq!( + runner_policy::RESERVED_KEYS.len(), + helper_policy::RESERVED_KEYS.len(), + "the runner and the helper carry different numbers of node-owned keys; a mismatch is a \ + contract change, not a test to be adjusted" + ); + for (index, (runner, helper)) in runner_policy::RESERVED_KEYS + .iter() + .zip(helper_policy::RESERVED_KEYS.iter()) + .enumerate() + { + assert_eq!( + runner, helper, + "node-owned-key entry {index} differs: the runner's copy has {runner:?} and the \ + helper's has {helper:?}. A mismatch is a contract change, not a test to be adjusted" + ); + } +} + +/// The node-owned baseline is the same baseline, in the same order, with the +/// same values, in both copies. +#[test] +fn the_node_owned_baseline_is_the_same_baseline_in_both_copies() { + assert_eq!( + runner_policy::BASELINE.len(), + helper_policy::BASELINE.len(), + "the runner and the helper carry different baselines; a mismatch is a contract change, \ + not a test to be adjusted" + ); + for (index, (runner, helper)) in runner_policy::BASELINE + .iter() + .zip(helper_policy::BASELINE.iter()) + .enumerate() + { + assert_eq!( + runner, helper, + "baseline entry {index} differs: the runner's copy has {runner:?} and the helper's \ + has {helper:?}. A mismatch is a contract change, not a test to be adjusted" + ); + } +} + +/// The matching rule and the `PATH` contract are the same in both copies. +/// +/// The matching rule is part of the contract rather than an implementation +/// detail: if the two sides disagreed about it, the runner would drop a key +/// the helper still refuses, or the other way round. +#[test] +fn the_matching_rule_and_the_path_contract_are_the_same_in_both_copies() { + assert_eq!( + runner_policy::MATCH_RULE, + helper_policy::MATCH_RULE, + "the matching rule differs between the copies; a mismatch is a contract change, not a \ + test to be adjusted" + ); + assert_eq!( + runner_policy::PATH_VALUE, + helper_policy::PATH_VALUE, + "the `PATH` contract differs between the copies; a mismatch is a contract change, not \ + a test to be adjusted" + ); + assert_eq!( + runner_policy::PATH_VALUE, + "/usr/bin:/bin", + "the `PATH` contract is a Linux/Unix contract with one value" + ); +} + +/// The helper's copy of the protocol limits is the owner's, not a guess. +/// +/// The helper is a standalone binary and cannot import `eggwork-core`, so the +/// generator reads these five values out of the owner of the wire limits and +/// emits them into the helper's copy. The comparison here is what stops that +/// copy from drifting. +#[test] +fn the_helper_limit_constants_match_eggwork_core() { + assert_eq!( + helper_policy::MAX_ARG_COUNT, + eggwork_core::MAX_ARG_COUNT, + "the helper's argument-count limit must be the owner's" + ); + assert_eq!( + helper_policy::MAX_ARG_BYTES, + eggwork_core::MAX_ARG_BYTES, + "the helper's argument-size limit must be the owner's" + ); + assert_eq!( + helper_policy::MAX_ENV_COUNT, + eggwork_core::MAX_ENV_COUNT, + "the helper's environment-count limit must be the owner's" + ); + assert_eq!( + helper_policy::MAX_ENV_NAME_BYTES, + eggwork_core::MAX_ENV_NAME_BYTES, + "the helper's environment-name limit must be the owner's" + ); + assert_eq!( + helper_policy::MAX_ENV_VALUE_BYTES, + eggwork_core::MAX_ENV_VALUE_BYTES, + "the helper's environment-value limit must be the owner's" + ); +} + +/// The `PATH` contract is a Linux/Unix contract. +/// +/// The Windows baseline is explicitly outside it, so a future reader must not +/// "fix" the Windows `PATH` to this value. +#[test] +fn the_path_contract_states_that_windows_is_outside_it() { + assert_eq!( + runner_policy::PATH_VALUE, + "/usr/bin:/bin", + "the Unix `PATH` contract" + ); + assert!( + !runner_policy::BASELINE_COMMON + .iter() + .any(|(key, _)| *key == "PATH"), + "the platform-independent part of the baseline must not carry `PATH`; the Windows \ + baseline's `PATH` is built from the parent process and is explicitly outside the \ + Linux/Unix contract" + ); +} + +#[cfg(target_os = "linux")] +mod linux { + use super::{helper_fixture, helper_policy, runner_policy, the_runner_policy_refuses}; + use eggwork_core::{OverflowPolicy, Requirement}; + use eggwork_runner::{ + LocalProcessRunner, NoExecutionSetup, ResourceSetupRequest, RunnerRequest, SandboxOutcome, + SandboxRequest, StdinPolicy, TrustedLandlockSetup, + }; + use std::fs; + use std::os::unix::fs::PermissionsExt; + use std::path::{Path, PathBuf}; + use std::process::Command; + use std::time::Duration; + use tokio::sync::mpsc; + use tokio_util::sync::CancellationToken; + + use helper_fixture::TrustedHelperFixture; + + /// The Cargo-built helper. Fixtures only ever *read* this path. + fn built_helper() -> &'static Path { + Path::new(env!("CARGO_BIN_EXE_eggwork-sandbox-helper")) + } + + /// The status byte the helper refuses a launch with when the environment + /// does not satisfy the shared policy. + /// + /// It is distinct from the general specification-validation status, so an + /// operator reading a refusal can tell an environment-policy refusal from + /// a specification that is malformed in some other way. + const ENVIRONMENT_POLICY_REFUSAL: u8 = 13; + + /// The general specification-validation refusal. + const SPECIFICATION_REFUSAL: u8 = 12; + + /// The probe keys and the decision the runner's policy makes about them. + /// + /// The expectation is stated here independently of both implementations, + /// and the test then checks that the runner's copy of the policy and the + /// helper's behaviour both agree with it. A one-sided edit to either copy + /// breaks one of those two agreements. + const PROBES: &[(&str, &str, bool)] = &[ + // Denied keys. The runner drops them; the helper refuses a + // specification that carries one. + ("LD_PRELOAD", "/tmp/evil.so", true), + ("DYLD_INSERT_LIBRARIES", "/tmp/evil.dylib", true), + ("IFS", ":", true), + ("SHELLOPTS", "x", true), + ("CDPATH", "/tmp", true), + ("BASH_ENV", "/tmp/rc", true), + ("ENV", "/tmp/rc", true), + ("PYTHONPATH", "/tmp", true), + ("PYTHONHOME", "/tmp", true), + ("NODE_OPTIONS", "--require=/tmp/x.js", true), + ("RUBYOPT", "-r/tmp/x", true), + ("PERL5OPT", "-M/tmp/x", true), + ("GIT_ASKPASS", "/tmp/ask", true), + ("SSH_ASKPASS", "/tmp/ask", true), + ("GIT_CONFIG_GLOBAL", "/tmp/gitconfig", true), + ("AWS_SECRET_ACCESS_KEY", "secret", true), + ("AZURE_CLIENT_ID", "id", true), + ("GOOGLE_APPLICATION_CREDENTIALS", "/tmp/creds.json", true), + ("SSH_AUTH_SOCK", "/tmp/agent.sock", true), + // A denied *prefix* rather than a denied exact name. + ("AWS_CONFIG_FILE", "/tmp/config", true), + // A differently-cased spelling of a denied key. + ("ld_preload", "/tmp/evil.so", true), + // Node-owned keys carrying the caller's value. The runner replaces + // the value with the node's; the helper refuses a specification that + // carries the caller's value. + ("LANG", "en_US.UTF-8", true), + ("LC_ALL", "en_US.UTF-8", true), + ("CI", "false", true), + ("NO_COLOR", "0", true), + ("TERM", "xterm", true), + ("PAGER", "less", true), + ("GIT_TERMINAL_PROMPT", "1", true), + // The `PATH` contract. + ("PATH", "/tmp/bin", true), + // Node-owned keys carrying the node's own value. The runner installs + // exactly these; the helper accepts them. + ("PATH", "/usr/bin:/bin", false), + ("LANG", "C.UTF-8", false), + ("LC_ALL", "C.UTF-8", false), + ("CI", "1", false), + ("NO_COLOR", "1", false), + ("TERM", "dumb", false), + ("PAGER", "cat", false), + ("GIT_TERMINAL_PROMPT", "0", false), + // A differently-cased spelling of a node-owned key. The node owns the + // key, so the helper refuses a specification that spells it + // differently: the child would have the caller's variable rather than + // the node's. + ("lang", "C.UTF-8", true), + // Caller-controlled keys. The runner passes them through and the + // helper accepts them. + ("HOME", "/tmp/home", false), + ("EGGWORK_CALLER_KEY", "caller", false), + ]; + + /// The first status byte the helper reports for a launch specification. + fn helper_status_for_spec(environment: &[(String, String)]) -> u8 { + use std::io::Read; + + let directory = tempfile::tempdir().expect("temp dir"); + fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)) + .expect("owner-only directory"); + let root = directory + .path() + .canonicalize() + .expect("canonical workspace root"); + let spec_path = directory.path().join("spec.json"); + let spec = serde_json::json!({ + "schema_version": 1, + "profile": serde_json::Value::Null, + "root": root, + "cwd": root, + "argv": ["/bin/sh", "-c", "true"], + "environment": environment, + }); + fs::write(&spec_path, serde_json::to_vec(&spec).expect("spec json")).expect("write spec"); + fs::set_permissions(&spec_path, fs::Permissions::from_mode(0o600)).expect("private spec"); + let status_path = directory.path().join("status.sock"); + let listener = std::os::unix::net::UnixListener::bind(&status_path).expect("status socket"); + let fixture = TrustedHelperFixture::stage(built_helper()); + let mut child = Command::new(fixture.path()) + .arg("--spec") + .arg(&spec_path) + .arg("--status") + .arg(&status_path) + .spawn() + .expect("spawn the helper"); + let (mut stream, _) = listener.accept().expect("accept the status connection"); + stream + .set_read_timeout(Some(Duration::from_secs(30))) + .expect("read timeout"); + let mut code = [0u8; 1]; + stream.read_exact(&mut code).expect("status byte"); + let _ = child.wait(); + code[0] + } + + /// The helper's decision on every probe key matches the runner's policy. + /// + /// This is the behavioural half of the parity gate. It drives the real + /// helper executable, so it measures what the helper enforces rather than + /// what two files say. + #[test] + fn the_helper_refuses_exactly_what_the_runner_drops() { + for (key, value, expect_refused) in PROBES { + let environment = vec![(key.to_string(), value.to_string())]; + let status = helper_status_for_spec(&environment); + let policy_refuses = the_runner_policy_refuses(key, value); + assert_eq!( + policy_refuses, *expect_refused, + "the runner's policy and the probe table disagree about {key}={value:?}; one of \ + them is wrong about the contract" + ); + if *expect_refused { + assert_eq!( + status, ENVIRONMENT_POLICY_REFUSAL, + "the helper must refuse {key}={value:?} with the environment-policy status" + ); + } else { + assert_ne!( + status, ENVIRONMENT_POLICY_REFUSAL, + "the helper must accept {key}={value:?}; the runner's policy says the caller \ + controls this key" + ); + } + } + } + + /// A specification with a duplicate environment key is refused with the + /// environment-policy status. + /// + /// The duplicate is what the live defect produced: the caller's `LANG` and + /// the node's `LANG` in one specification. The runner can no longer build + /// such a specification, but the helper must still refuse one, because a + /// duplicate key is an environment the node did not build. + #[test] + fn a_duplicate_environment_key_is_refused_with_the_environment_policy_status() { + let environment = vec![ + ("LANG".to_string(), "C.UTF-8".to_string()), + ("LANG".to_string(), "C.UTF-8".to_string()), + ]; + assert_eq!( + helper_status_for_spec(&environment), + ENVIRONMENT_POLICY_REFUSAL, + "a duplicate environment key must be refused with the environment-policy status" + ); + } + + /// A specification that is malformed in a way that is *not* about the + /// environment keeps the general validation status. + /// + /// The two statuses must stay distinguishable: an operator reading + /// "status 12" cannot tell which of several specification problems + /// happened, and that was the reason for the environment-policy status. + #[test] + fn a_malformed_specification_keeps_the_general_validation_status() { + use std::io::Read; + + let directory = tempfile::tempdir().expect("temp dir"); + fs::set_permissions(directory.path(), fs::Permissions::from_mode(0o700)) + .expect("owner-only directory"); + let root = directory + .path() + .canonicalize() + .expect("canonical workspace root"); + let spec_path = directory.path().join("spec.json"); + let spec = serde_json::json!({ + "schema_version": 1, + "profile": "unsupported-profile", + "root": root, + "cwd": root, + "argv": ["/bin/sh", "-c", "true"], + "environment": [], + }); + fs::write(&spec_path, serde_json::to_vec(&spec).expect("spec json")).expect("write spec"); + fs::set_permissions(&spec_path, fs::Permissions::from_mode(0o600)).expect("private spec"); + let status_path = directory.path().join("status.sock"); + let listener = std::os::unix::net::UnixListener::bind(&status_path).expect("status socket"); + let fixture = TrustedHelperFixture::stage(built_helper()); + let mut child = Command::new(fixture.path()) + .arg("--spec") + .arg(&spec_path) + .arg("--status") + .arg(&status_path) + .spawn() + .expect("spawn the helper"); + let (mut stream, _) = listener.accept().expect("accept the status connection"); + stream + .set_read_timeout(Some(Duration::from_secs(30))) + .expect("read timeout"); + let mut code = [0u8; 1]; + stream.read_exact(&mut code).expect("status byte"); + let _ = child.wait(); + assert_eq!( + code[0], SPECIFICATION_REFUSAL, + "a specification that is malformed in a way unrelated to the environment keeps the \ + general validation status" + ); + } + + /// A request that sets a node-owned key keeps its confinement. + /// + /// This is the regression for the live defect. The caller's `LANG` used to + /// be appended to the node's baseline, so the launch specification carried + /// two `LANG` entries, the helper refused the specification, and the + /// runner — for a best-effort request only — answered that pre-target + /// refusal by re-spawning the target directly with no Landlock ruleset at + /// all. The observable result was a successful, entirely unconfined + /// execution whose only record of the degradation was a `NotApplied` in the + /// terminal snapshot. + /// + /// So the assertion is not only that the execution succeeded. It is that + /// the sandbox outcome is `Applied`, that the child saw the node's `LANG` + /// and not the caller's, and that the child saw exactly one `LANG`. + #[tokio::test] + async fn a_caller_supplied_node_owned_key_keeps_the_execution_confined() { + let temp = tempfile::tempdir().expect("temp dir"); + let root = temp.path().join("workspace"); + fs::create_dir(&root).expect("workspace"); + let fixture = TrustedHelperFixture::stage(built_helper()); + let runner = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())); + let (tx, _rx) = mpsc::channel(8); + let result = runner + .run( + environment_probe_request( + &root, + SandboxRequest::Required { + profile: "workspace_rw".into(), + }, + ), + CancellationToken::new(), + tx, + ) + .await + .expect("the execution runs"); + assert!( + matches!(result.setup.sandbox, SandboxOutcome::Applied { .. }), + "a caller-supplied node-owned key must not cost the execution its confinement: {:?}", + result.setup.sandbox + ); + let observed = String::from_utf8(result.stdout.head.clone()).expect("utf-8 environment"); + let lang_lines: Vec<&str> = observed + .lines() + .filter(|line| line.starts_with("LANG=")) + .collect(); + assert_eq!( + lang_lines, + vec!["LANG=C.UTF-8"], + "the child must see the node's LANG exactly once" + ); + assert!( + !observed.contains("en_US.UTF-8"), + "the caller's LANG must not reach the child: {observed}" + ); + assert!( + !observed.contains("LANG=en_US"), + "the child's environment must not carry the caller's LANG" + ); + } + + /// The direct path and the helper path agree about the environment. + /// + /// They used to disagree. The direct path applied the caller's `LANG` + /// *after* the node's baseline, so the child saw the caller's locale, + /// while the launch specification carried both entries and was refused. + #[tokio::test] + async fn the_direct_path_and_the_helper_path_agree_about_the_environment() { + let temp = tempfile::tempdir().expect("temp dir"); + let root = temp.path().join("workspace"); + fs::create_dir(&root).expect("workspace"); + + let (tx, _rx) = mpsc::channel(8); + let direct = LocalProcessRunner::new(NoExecutionSetup) + .run( + environment_probe_request( + &root, + SandboxRequest::BestEffort { + profile: "workspace_rw".into(), + }, + ), + CancellationToken::new(), + tx, + ) + .await + .expect("the direct execution runs"); + let fixture = TrustedHelperFixture::stage(built_helper()); + let (tx, _rx) = mpsc::channel(8); + let confined = LocalProcessRunner::new(TrustedLandlockSetup::new(fixture.path())) + .run( + environment_probe_request( + &root, + SandboxRequest::Required { + profile: "workspace_rw".into(), + }, + ), + CancellationToken::new(), + tx, + ) + .await + .expect("the confined execution runs"); + assert!( + matches!(confined.setup.sandbox, SandboxOutcome::Applied { .. }), + "the confined execution must be confined: {:?}", + confined.setup.sandbox + ); + let direct_environment = sorted_environment(&direct.stdout.head); + let confined_environment = sorted_environment(&confined.stdout.head); + assert_eq!( + direct_environment, confined_environment, + "the two paths must build the same environment" + ); + for key in runner_policy::RESERVED_KEYS { + let expected = runner_policy::baseline_value(key).expect("baseline value"); + assert!( + direct_environment.contains(&format!("{key}={expected}")), + "the direct path must carry the node's {key}" + ); + assert!( + confined_environment.contains(&format!("{key}={expected}")), + "the helper path must carry the node's {key}" + ); + } + } + + /// A request that sets the node-owned keys to the caller's values and + /// asks for the environment the child sees. + fn environment_probe_request(root: &Path, sandbox: SandboxRequest) -> RunnerRequest { + let mut request = + RunnerRequest::new(vec!["/bin/sh".into(), "-c".into(), "env".into()], root); + request.set_environment(vec![ + ("LANG".into(), "en_US.UTF-8".into()), + ("LC_ALL".into(), "en_US.UTF-8".into()), + ("CI".into(), "false".into()), + ("TERM".into(), "xterm".into()), + ("PAGER".into(), "less".into()), + ("NO_COLOR".into(), "0".into()), + ("GIT_TERMINAL_PROMPT".into(), "1".into()), + ("PATH".into(), "/malicious/path".into()), + ("LD_PRELOAD".into(), "/tmp/evil.so".into()), + ("CALLER_KEY".into(), "caller".into()), + ]); + request.set_stdin_policy(StdinPolicy::Null); + request.set_timeout(Duration::from_secs(20)); + request.set_output_policy(16384, 4096, OverflowPolicy::Truncate); + request.set_sandbox_request(sandbox); + request.set_resource_setup_request(ResourceSetupRequest { + memory_bytes: Requirement::NotRequested, + cpu_millis: Requirement::NotRequested, + pids: Requirement::NotRequested, + }); + request + } + + /// The child's environment, sorted, so two runs can be compared. + fn sorted_environment(captured: &[u8]) -> Vec { + let mut lines: Vec = String::from_utf8_lossy(captured) + .lines() + .map(|line| line.to_owned()) + .collect(); + lines.sort(); + lines + } + + /// The helper's copy of the policy is the one the helper binary compiles. + /// + /// The comparison above uses the module compiled into this test, which is + /// the helper's own source file. This test pins the other end of it: that + /// the file is the one the helper binary was built from. + #[test] + fn the_helper_copy_is_the_file_the_helper_compiles() { + let helper_source = + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("src/environment_policy.rs"); + assert!( + helper_source.exists(), + "the helper's generated policy copy must exist at {}", + helper_source.display() + ); + let compiled = include_str!("../src/environment_policy.rs"); + let on_disk = fs::read_to_string(&helper_source).expect("read the generated copy"); + assert_eq!( + compiled, on_disk, + "the copy compiled into this test must be the copy the helper compiles" + ); + assert_eq!( + compiled, + include_str!("../src/environment_policy.rs"), + "the generated copy must be stable" + ); + let _ = helper_policy::PATH_VALUE; + } +} diff --git a/crates/eggwork-server/src/artifact.rs b/crates/eggwork-server/src/artifact.rs index f03c5e7..f134f65 100644 --- a/crates/eggwork-server/src/artifact.rs +++ b/crates/eggwork-server/src/artifact.rs @@ -6,7 +6,7 @@ use eggwork_core::{ ExecutionId, PrincipalId, RelativePath, WorkspaceEntry, WorkspaceManifest, }; use futures_util::stream; -use rusqlite::{Connection, OptionalExtension, params}; +use rusqlite::{Connection, OpenFlags, OptionalExtension, params}; use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, @@ -56,6 +56,76 @@ pub struct ArtifactGcReport { pub deleted_artifacts: u64, } +/// The canonical artifact-candidate statement. +/// +/// One producer for the predicate: the collector and the operator's preview +/// evaluate this exact statement, so the preview cannot answer a different +/// question from the pass it previews. +const ARTIFACT_CANDIDATES_SQL: &str = "SELECT artifact_id FROM artifacts WHERE expires_unix_ms <= ?1 ORDER BY expires_unix_ms LIMIT ?2"; + +/// The artifact store's metadata database path. +/// +/// The store owns this file name. The operator resolves it through this +/// function instead of spelling `artifacts.sqlite` itself, so renaming the +/// store's database is a one-line change here. +pub fn metadata_path(database_path: &Path) -> PathBuf { + database_path.with_extension("artifacts.sqlite") +} + +/// What the collector would act on, evaluated without opening the store. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GcPreview { + /// Expired artifacts, oldest expiry first. + pub artifacts: Vec, +} + +/// Open the store's metadata database without the ability to change it. +/// +/// `SQLITE_OPEN_READ_ONLY` never creates the file and never writes to it, +/// which is what lets the operator's preview read a store that does not +/// exist (it fails) instead of bringing one into being (it must not). +fn open_metadata_read_only(path: &Path) -> Result { + Connection::open_with_flags( + path, + OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) + .map_err(ArtifactError::from) +} + +/// Expired artifacts, oldest expiry first, bounded by `limit`. +/// +/// The one implementation of the artifact candidate predicate. The collector +/// evaluates it against the live store; the operator's preview evaluates the +/// same statement against a read-only connection. +fn artifact_candidates( + connection: &Connection, + now_unix_ms: u64, + limit: usize, +) -> Result, ArtifactError> { + let mut statement = connection.prepare(ARTIFACT_CANDIDATES_SQL)?; + let rows = statement.query_map( + params![now_unix_ms as i64, limit.min(i64::MAX as usize) as i64], + |row| row.get(0), + )?; + Ok(rows.collect::, _>>()?) +} + +/// The artifact candidates the collector would act on, without opening the +/// store. +/// +/// `ArtifactStore::open` is not read-only: it creates the parent directory +/// and the metadata database when they are absent. An operator preview that +/// opened the store would therefore bring into being the very store it is +/// reporting on, so it reaches the canonical statement through this entry +/// point instead: the same database file, opened read-only, and the same +/// statement. +pub fn preview_gc(path: &Path, now_unix_ms: u64, limit: usize) -> Result { + let connection = open_metadata_read_only(path)?; + Ok(GcPreview { + artifacts: artifact_candidates(&connection, now_unix_ms, limit)?, + }) +} + type DiscoveredFiles = Vec<(RelativePath, PathBuf, bool)>; type DiscoveredTree = (DiscoveredFiles, Vec); @@ -190,33 +260,22 @@ impl ArtifactStore { dry_run: bool, ) -> Result { let connection = self.connection.lock().map_err(|_| ArtifactError::Worker)?; - let count: i64 = connection.query_row( - "SELECT COUNT(*) FROM artifacts WHERE expires_unix_ms <= ?1", - [now_unix_ms as i64], - |row| row.get(0), - )?; - let limit = limit.min(i64::MAX as usize) as i64; - let candidate_count: i64 = connection.query_row( - "SELECT COUNT(*) FROM (SELECT artifact_id FROM artifacts - WHERE expires_unix_ms <= ?1 ORDER BY expires_unix_ms LIMIT ?2)", - params![now_unix_ms as i64, limit], - |row| row.get(0), - )?; + // One statement, one predicate. The candidate window is the same set + // the operator's preview reports, and the delete removes exactly the + // rows that window named. + let candidates = artifact_candidates(&connection, now_unix_ms, limit)?; + let candidate_count = candidates.len() as u64; if !dry_run { - connection.execute( - "DELETE FROM artifacts WHERE artifact_id IN - (SELECT artifact_id FROM artifacts WHERE expires_unix_ms <= ?1 - ORDER BY expires_unix_ms LIMIT ?2)", - params![now_unix_ms as i64, limit], - )?; + for artifact_id in &candidates { + connection.execute( + "DELETE FROM artifacts WHERE artifact_id = ?1", + [artifact_id], + )?; + } } Ok(ArtifactGcReport { - candidate_artifacts: candidate_count.max(0).min(count.max(0)) as u64, - deleted_artifacts: if dry_run { - 0 - } else { - candidate_count.max(0).min(count.max(0)) as u64 - }, + candidate_artifacts: candidate_count, + deleted_artifacts: if dry_run { 0 } else { candidate_count }, }) } } diff --git a/crates/eggwork-server/src/blob.rs b/crates/eggwork-server/src/blob.rs index f18bf9e..1fd28ec 100644 --- a/crates/eggwork-server/src/blob.rs +++ b/crates/eggwork-server/src/blob.rs @@ -3,12 +3,12 @@ use bytes::Bytes; use eggwork_core::BlobDigest; use futures_util::{Stream, StreamExt}; -use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params}; +use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior, params}; use sha2::{Digest, Sha256}; use std::{ collections::HashSet, fs::{self, OpenOptions}, - io, + io::{self, Write}, path::{Path, PathBuf}, sync::Arc, time::{SystemTime, UNIX_EPOCH}, @@ -70,6 +70,99 @@ struct BlobStoreInner { write_lock: Mutex<()>, } +/// The canonical blob-candidate statement. +/// +/// One producer for the predicate. The collector's dry run, the collector's +/// real pass, and the operator's preview all evaluate this exact statement, +/// so the preview cannot answer a different question from the pass it +/// previews. +/// +/// The selection is on the *reference rows*, never on the `reference_count` +/// counter. The counter is a denormalization maintained only by the +/// `blob_reference_insert` / `blob_reference_delete` triggers, so it can +/// drift from the rows that actually pin bytes; the rows are the truth. +const UNREFERENCED_CANDIDATES_SQL: &str = "SELECT digest, size_bytes FROM blobs + WHERE NOT EXISTS (SELECT 1 FROM blob_references r WHERE r.digest = blobs.digest) + ORDER BY last_used_unix_ms ASC LIMIT ?1"; + +/// Expired blob references, counted without a bound. +/// +/// The collector reports this number and the operator's preview reports the +/// same number, so the statement lives here rather than being copied into +/// the operator. +const EXPIRED_REFERENCE_COUNT_SQL: &str = "SELECT COUNT(*) FROM blob_references WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1"; + +/// The blob store's metadata database path. +/// +/// The store owns this file name. The operator resolves it through this +/// function instead of spelling `metadata.sqlite` itself, so renaming the +/// store's database is a one-line change here. +pub fn metadata_path(root: &Path) -> PathBuf { + root.join("metadata.sqlite") +} + +/// The shard directory that holds `digest`. +/// +/// The store's layout is one level of sharding on the first two hex +/// characters of the digest. Pure, so a caller that only needs to resolve a +/// path does not need a store instance - and therefore does not need the +/// creating, reconciling open that `BlobStore::open` performs. +pub fn shard_path(root: &Path, digest: &BlobDigest) -> PathBuf { + root.join(&digest.as_str()[..2]) +} + +/// The object's path inside the blob root. +/// +/// Pure, and the single implementation of the layout: `BlobStore::path_for` +/// delegates to it, so the store and every consumer of the layout agree. +pub fn object_path(root: &Path, digest: &BlobDigest) -> PathBuf { + shard_path(root, digest).join(digest.as_str()) +} + +/// What the collector would act on, evaluated without opening the store. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GcPreview { + /// Expired blob references: the unbounded count the collector reports. + pub expired_references: u64, + /// Unreferenced blobs, coldest first: `(digest, size_bytes)`. + pub candidates: Vec<(String, u64)>, +} + +/// Open the store's metadata database without the ability to change it. +/// +/// `SQLITE_OPEN_READ_ONLY` never creates the file and never writes to it, +/// which is what lets the operator's preview read a store that does not +/// exist (it fails) instead of bringing one into being (it must not). +fn open_metadata_read_only(path: &Path) -> Result { + Connection::open_with_flags( + path, + OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) + .map_err(BlobError::from) +} + +/// The blob candidates the collector would act on, without opening the store. +/// +/// `BlobStore::open` is not read-only: it creates the root and the metadata +/// database when they are absent and it calls `remove_stale_parts`, which +/// deletes stale part files and reconciles index rows. An operator preview +/// that opened the store would therefore mutate the store it is reporting +/// on, so it reaches the canonical statement through this entry point +/// instead: the same database file, opened read-only, and the same +/// statement. +pub fn preview_gc(path: &Path, now_unix_ms: u64, limit: usize) -> Result { + let connection = open_metadata_read_only(path)?; + let expired_references: i64 = + connection.query_row(EXPIRED_REFERENCE_COUNT_SQL, [now_unix_ms as i64], |row| { + row.get(0) + })?; + let candidates = BlobStore::unreferenced_candidates(&connection, limit)?; + Ok(GcPreview { + expired_references: expired_references.max(0) as u64, + candidates, + }) +} + impl BlobStore { pub fn open(root: impl AsRef, quota_bytes: u64) -> Result { let root = root.as_ref().to_path_buf(); @@ -81,7 +174,7 @@ impl BlobStore { } let quarantine = root.join("quarantine"); fs::create_dir_all(&quarantine)?; - let metadata = Connection::open(root.join("metadata.sqlite"))?; + let metadata = Connection::open(metadata_path(&root))?; metadata.execute_batch( "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; @@ -124,10 +217,7 @@ impl BlobStore { } pub fn path_for(&self, digest: &BlobDigest) -> PathBuf { - self.inner - .root - .join(&digest.as_str()[..2]) - .join(digest.as_str()) + object_path(&self.inner.root, digest) } /// Report which of `digests` the store does not have. @@ -372,15 +462,15 @@ impl BlobStore { /// must be evaluated in both places. Two hand-copied copies of it are what /// let the two paths drift apart and made `NodeGcReport.blob_candidates` /// under-predict what `--apply` would actually remove. + /// + /// The operator's preview is a third reader of the same statement. It + /// evaluates it through `preview_gc` against a read-only connection, so + /// there is exactly one implementation of the predicate in the tree. fn unreferenced_candidates( - transaction: &rusqlite::Transaction<'_>, + connection: &Connection, limit: usize, ) -> Result, BlobError> { - let mut statement = transaction.prepare( - "SELECT digest, size_bytes FROM blobs - WHERE NOT EXISTS (SELECT 1 FROM blob_references r WHERE r.digest = blobs.digest) - ORDER BY last_used_unix_ms ASC LIMIT ?1", - )?; + let mut statement = connection.prepare(UNREFERENCED_CANDIDATES_SQL)?; Ok(statement .query_map([limit.min(i64::MAX as usize) as i64], |row| { Ok(( @@ -401,11 +491,10 @@ impl BlobStore { let _guard = self.inner.write_lock.lock().await; let mut connection = self.inner.metadata.lock().map_err(|_| BlobError::Worker)?; let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; - let expired_references: i64 = transaction.query_row( - "SELECT COUNT(*) FROM blob_references WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1", - [now_unix_ms as i64], - |row| row.get::<_, i64>(0), - )?; + let expired_references: i64 = + transaction.query_row(EXPIRED_REFERENCE_COUNT_SQL, [now_unix_ms as i64], |row| { + row.get::<_, i64>(0) + })?; let mut candidates = Self::unreferenced_candidates(&transaction, limit)?; let mut removed_blobs = 0u64; let mut removed_bytes = 0u64; @@ -643,6 +732,37 @@ impl BlobStore { Ok(tokio::fs::File::open(self.path_for(digest)).await?) } + /// Copy the object for `digest` into `destination`, verifying the digest + /// of the bytes that are actually copied. + /// + /// The digest is computed over the copied stream, not over a separate + /// read of the same path. A pre-flight check and a later copy are two + /// reads of a mutable file, and only hashing the bytes that reach the + /// destination proves the destination holds the manifest's content: a + /// file that changes between the two reads cannot be smuggled past a + /// check that happened before it. + /// + /// The verification costs one SHA-256 pass over the copied bytes and no + /// additional read of the object. + pub fn copy_verified( + &self, + digest: &BlobDigest, + destination: &mut impl Write, + ) -> Result { + let path = self.path_for(digest); + let mut file = fs::File::open(&path)?; + let mut writer = VerifyWriter { + inner: destination, + hasher: Sha256::new(), + written: 0, + }; + io::copy(&mut file, &mut writer)?; + if hex::encode(writer.hasher.finalize()) != digest.as_str() { + return Err(BlobError::DigestMismatch); + } + Ok(writer.written) + } + fn remove_stale_parts(&self) -> Result<(), BlobError> { for entry in fs::read_dir(&self.inner.root)? { let entry = entry?; @@ -662,15 +782,17 @@ impl BlobStore { // Reconcile the two durable layers after a crash between rename and // metadata commit (or metadata commit and external file loss). for digest in &known { - if BlobDigest::parse(digest.clone()).is_err() { + // A row whose digest does not parse cannot name a location, so it + // is dropped rather than resolved against the layout. + let Ok(parsed) = BlobDigest::parse(digest.clone()) else { self.inner .metadata .lock() .map_err(|_| BlobError::Worker)? .execute("DELETE FROM blobs WHERE digest = ?1", [digest])?; continue; - } - let path = self.inner.root.join(&digest[..2]).join(digest); + }; + let path = self.path_for(&parsed); if !path.is_file() { self.inner .metadata @@ -717,6 +839,31 @@ impl io::Write for HashWriter { } } +/// A writer that hashes everything it forwards. +/// +/// Used by `BlobStore::copy_verified` so that the digest is computed over +/// the bytes that actually reach the destination, not over a separate read +/// of the same file. +struct VerifyWriter { + inner: W, + hasher: Sha256, + written: u64, +} +impl Write for VerifyWriter { + fn write(&mut self, bytes: &[u8]) -> io::Result { + let written = self.inner.write(bytes)?; + self.hasher.update(&bytes[..written]); + self.written = self + .written + .checked_add(written as u64) + .ok_or_else(|| io::Error::other("blob size overflow"))?; + Ok(written) + } + fn flush(&mut self) -> io::Result<()> { + self.inner.flush() + } +} + fn private_create_new(path: &Path) -> io::Result { let mut options = OpenOptions::new(); options.write(true).create_new(true); diff --git a/crates/eggwork-server/src/lib.rs b/crates/eggwork-server/src/lib.rs index 0e8974f..bdd2426 100644 --- a/crates/eggwork-server/src/lib.rs +++ b/crates/eggwork-server/src/lib.rs @@ -340,7 +340,7 @@ impl NodeServer { let workspaces = workspace::WorkspaceManager::open(&config.workspace_root, config.workspace_quota_bytes) .map_err(|e| NodeStartError::EggServe(e.to_string()))?; - let artifact_path = config.database_path.with_extension("artifacts.sqlite"); + let artifact_path = artifact::metadata_path(&config.database_path); let artifacts = artifact::ArtifactStore::open(&artifact_path) .map_err(|e| NodeStartError::EggServe(e.to_string()))?; let recovered = store diff --git a/crates/eggwork-server/src/operations.rs b/crates/eggwork-server/src/operations.rs index a9469be..d25e671 100644 --- a/crates/eggwork-server/src/operations.rs +++ b/crates/eggwork-server/src/operations.rs @@ -888,7 +888,7 @@ fn file_family_bytes(path: &Path) -> u64 { } pub fn storage_summary(config: &OperatorConfig) -> Result { - let artifact_db = config.database_path.with_extension("artifacts.sqlite"); + let artifact_db = crate::artifact::metadata_path(&config.database_path); Ok(StorageSummary { execution_bytes: file_family_bytes(&config.database_path), blob_bytes: tree_bytes(&config.blob_root)?, @@ -946,7 +946,7 @@ pub async fn collect_garbage( .map_err(|_| OperationsError::Data)?; let blobs = BlobStore::open(&config.blob_root, config.blob_quota_bytes) .map_err(|_| OperationsError::Data)?; - let artifacts = ArtifactStore::open(config.database_path.with_extension("artifacts.sqlite")) + let artifacts = ArtifactStore::open(crate::artifact::metadata_path(&config.database_path)) .map_err(|_| OperationsError::Data)?; let now = crate::artifact::now_unix_ms(); let (workspace_candidates, workspace_logical_bytes, workspaces_deleted) = workspaces @@ -1030,64 +1030,46 @@ fn read_only_database(path: &Path) -> Result Result { - let now = crate::artifact::now_unix_ms() as i64; - let workspace_db = read_only_database(&config.workspace_root.join("metadata.sqlite"))?; - let (workspace_candidates, workspace_logical_bytes): (i64, i64) = workspace_db - .query_row( - "SELECT COUNT(*), COALESCE(SUM(logical_bytes),0) FROM - (SELECT logical_bytes FROM workspaces WHERE expires_unix_ms IS NOT NULL - AND expires_unix_ms <= ?1 ORDER BY expires_unix_ms LIMIT ?2)", - rusqlite::params![now, limit as i64], - |row| Ok((row.get(0)?, row.get(1)?)), - ) - .map_err(|_| OperationsError::Data)?; - // Older stores predate the retained-manifest cache; report zero instead - // of failing the whole preview. - let manifest_candidates: i64 = workspace_db - .query_row( - "SELECT COUNT(*) FROM (SELECT manifest_digest FROM retained_manifests - WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1 - ORDER BY expires_unix_ms LIMIT ?2)", - rusqlite::params![now, limit as i64], - |row| row.get(0), - ) - .unwrap_or(0); - let artifact_db = read_only_database(&config.database_path.with_extension("artifacts.sqlite"))?; - let artifact_candidates: i64 = artifact_db - .query_row( - "SELECT COUNT(*) FROM (SELECT artifact_id FROM artifacts - WHERE expires_unix_ms <= ?1 ORDER BY expires_unix_ms LIMIT ?2)", - rusqlite::params![now, limit as i64], - |row| row.get(0), - ) - .map_err(|_| OperationsError::Data)?; - let blob_db = read_only_database(&config.blob_root.join("metadata.sqlite"))?; - let expired_blob_references: i64 = blob_db - .query_row( - "SELECT COUNT(*) FROM blob_references WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1", - [now], - |row| row.get(0), - ) - .map_err(|_| OperationsError::Data)?; - let (blob_candidates, blob_candidate_bytes): (i64, i64) = blob_db - .query_row( - "SELECT COUNT(*), COALESCE(SUM(size_bytes),0) FROM - (SELECT size_bytes FROM blobs WHERE reference_count = 0 ORDER BY last_used_unix_ms LIMIT ?1)", - [limit as i64], - |row| Ok((row.get(0)?, row.get(1)?)), - ) + // The preview owns no candidate predicate of its own. It asks each owner + // module for the set the collector would act on, and the owner evaluates + // the same statement the collector evaluates - so the preview and the + // apply pass cannot answer different questions. + // + // The owner entry points open the store's metadata database read-only. + // They do not open the store: `BlobStore::open`, `WorkspaceManager::open` + // and `ArtifactStore::open` all create and reconcile, and a preview that + // created the store it reports on would not be a preview. + let now = crate::artifact::now_unix_ms(); + let workspaces = crate::workspace::preview_gc( + &crate::workspace::metadata_path(&config.workspace_root), + now, + limit, + ) + .map_err(|_| OperationsError::Data)?; + let artifacts = crate::artifact::preview_gc( + &crate::artifact::metadata_path(&config.database_path), + now, + limit, + ) + .map_err(|_| OperationsError::Data)?; + let blobs = crate::blob::preview_gc(&crate::blob::metadata_path(&config.blob_root), now, limit) .map_err(|_| OperationsError::Data)?; Ok(NodeGcReport { - workspace_candidates: workspace_candidates.max(0) as u64, - workspace_logical_bytes: workspace_logical_bytes.max(0) as u64, + workspace_candidates: workspaces.workspaces.len() as u64, + workspace_logical_bytes: workspaces.workspaces.iter().fold(0u64, |sum, candidate| { + sum.saturating_add(candidate.logical_bytes) + }), workspaces_deleted: 0, - manifest_candidates: manifest_candidates.max(0) as u64, + manifest_candidates: workspaces.manifests.len() as u64, manifests_deleted: 0, - artifact_candidates: artifact_candidates.max(0) as u64, + artifact_candidates: artifacts.artifacts.len() as u64, artifacts_deleted: 0, - expired_blob_references: expired_blob_references.max(0) as u64, - blob_candidates: blob_candidates.max(0) as u64, - blob_candidate_bytes: blob_candidate_bytes.max(0) as u64, + expired_blob_references: blobs.expired_references, + blob_candidates: blobs.candidates.len() as u64, + blob_candidate_bytes: blobs + .candidates + .iter() + .fold(0u64, |sum, (_, size)| sum.saturating_add(*size)), blobs_deleted: 0, blob_bytes_deleted: 0, dry_run: true, @@ -1100,17 +1082,21 @@ pub fn inspect_blob( ) -> Result { let digest = eggwork_core::BlobDigest::parse(digest.to_owned()) .map_err(|_| OperationsError::NotFound)?; - let shard = config.blob_root.join(&digest.as_str()[..2]); + // The shard directory and the object path come from the store's own path + // ownership. The inspection verb runs against an offline store, so it + // must not need a store instance - and a store instance would mean the + // creating, reconciling open that `BlobStore::open` performs. + let shard = crate::blob::shard_path(&config.blob_root, &digest); let shard_meta = fs::symlink_metadata(&shard).map_err(|_| OperationsError::NotFound)?; if !shard_meta.is_dir() || shard_meta.file_type().is_symlink() { return Err(OperationsError::NotFound); } - let path = shard.join(digest.as_str()); + let path = crate::blob::object_path(&config.blob_root, &digest); let metadata = fs::symlink_metadata(&path).map_err(|_| OperationsError::NotFound)?; if !metadata.is_file() || metadata.file_type().is_symlink() { return Err(OperationsError::NotFound); } - let db = read_only_database(&config.blob_root.join("metadata.sqlite"))?; + let db = read_only_database(&crate::blob::metadata_path(&config.blob_root))?; let size_recorded: Option<(i64, i64)> = db .query_row( "SELECT size_bytes,reference_count FROM blobs WHERE digest=?1", @@ -1136,7 +1122,7 @@ pub fn inspect_workspace( ) -> Result { let id = eggwork_core::WorkspaceId::new(id.to_owned()).map_err(|_| OperationsError::NotFound)?; - let db = read_only_database(&config.workspace_root.join("metadata.sqlite"))?; + let db = read_only_database(&crate::workspace::metadata_path(&config.workspace_root))?; let row: Option<(String, i64, String, Option)> = db.query_row("SELECT state, logical_bytes, manifest_digest, expires_unix_ms FROM workspaces WHERE workspace_id=?1", [id.as_str()], |r| Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?))).optional().map_err(|_| OperationsError::Data)?; let (state, logical, digest, expires) = row.ok_or(OperationsError::NotFound)?; Ok(ResourceInspection { @@ -1151,7 +1137,7 @@ pub fn inspect_artifact( id: &str, ) -> Result { let id = eggwork_core::ArtifactId::new(id.to_owned()).map_err(|_| OperationsError::NotFound)?; - let db = read_only_database(&config.database_path.with_extension("artifacts.sqlite"))?; + let db = read_only_database(&crate::artifact::metadata_path(&config.database_path))?; let row: Option> = db .query_row( "SELECT record_json FROM artifacts WHERE artifact_id=?1", @@ -1462,53 +1448,455 @@ mod tests { assert_eq!(next.next_offset, Some(2)); } + /// The three data-plane stores, built through their owner modules. + /// + /// The fixture this replaces hand-built a `blobs` table whose columns were + /// `(reference_count, size_bytes, last_used_unix_ms)`, with no `digest` + /// column at all. It was a database shaped to the hand-copied predicate, + /// and the canonical statement could not even be evaluated against it. + fn real_stores(config: &OperatorConfig) -> (BlobStore, WorkspaceManager, ArtifactStore) { + ( + BlobStore::open(&config.blob_root, config.blob_quota_bytes).unwrap(), + WorkspaceManager::open(&config.workspace_root, config.workspace_quota_bytes).unwrap(), + ArtifactStore::open(crate::artifact::metadata_path(&config.database_path)).unwrap(), + ) + } + + async fn seed_blob(blobs: &BlobStore, bytes: &'static [u8]) -> eggwork_core::BlobDigest { + let digest = eggwork_core::BlobDigest::from_bytes(bytes); + blobs + .put_stream( + digest.clone(), + bytes.len() as u64, + futures_util::stream::iter([Ok::<_, ()>(bytes::Bytes::from_static(bytes))]), + ) + .await + .unwrap(); + digest + } + + /// The blob states the two candidate predicates can disagree about. + struct BlobStates { + /// A live reference row: never a candidate. + live: eggwork_core::BlobDigest, + /// Only an expired reference row: a candidate once that row is gone. + /// Absent when the fixture seeds no expired reference at all. + expired: Option, + /// No reference rows at all: always a candidate. + unreferenced: Vec, + /// A live reference row whose counter says zero. + /// + /// Two of them, so that the two candidate predicates disagree on the + /// *count* and not only on the membership: a counter-based predicate + /// would report one blob too many, which a count comparison can see. + counter_low: Vec, + /// No reference rows whose counter says one. + counter_high: eggwork_core::BlobDigest, + } + + /// Seed the blob states and drift the trigger-maintained counter against + /// the reference rows of two of them. + /// + /// `blobs.reference_count` is a denormalization written only by the + /// `blob_reference_insert` / `blob_reference_delete` triggers. Drifting it + /// here does not fabricate a reference row: it reproduces the condition + /// under which a counter-based predicate and a reference-row predicate + /// answer different questions, which is the whole point of the + /// divergence this milestone removes. + async fn seed_blob_states( + config: &OperatorConfig, + blobs: &BlobStore, + with_expired_reference: bool, + ) -> BlobStates { + let states = BlobStates { + live: seed_blob(blobs, b"live").await, + expired: if with_expired_reference { + Some(seed_blob(blobs, b"expired").await) + } else { + None + }, + unreferenced: vec![ + seed_blob(blobs, b"unreferenced-a").await, + seed_blob(blobs, b"unreferenced-b").await, + seed_blob(blobs, b"unreferenced-c").await, + ], + counter_low: vec![ + seed_blob(blobs, b"counter-low-a").await, + seed_blob(blobs, b"counter-low-b").await, + ], + counter_high: seed_blob(blobs, b"counter-high").await, + }; + blobs + .retain( + "workspace", + "ws-live", + std::slice::from_ref(&states.live), + None, + ) + .unwrap(); + blobs + .retain("workspace", "ws-counter", &states.counter_low, None) + .unwrap(); + if let Some(expired) = states.expired.clone() { + blobs + .retain("workspace", "ws-expired", &[expired], Some(1)) + .unwrap(); + } + let connection = + rusqlite::Connection::open(crate::blob::metadata_path(&config.blob_root)).unwrap(); + for digest in &states.counter_low { + connection + .execute( + "UPDATE blobs SET reference_count = 0 WHERE digest = ?1", + [digest.as_str()], + ) + .unwrap(); + } + connection + .execute( + "UPDATE blobs SET reference_count = 1 WHERE digest = ?1", + [states.counter_high.as_str()], + ) + .unwrap(); + drop(connection); + states + } + + /// Seed expired workspaces and artifacts so the preview's workspace and + /// artifact figures are exercised against real tables. + /// + /// The workspace rows need a storage directory that exists, because the + /// manager's reconciliation drops rows whose tree is gone. + fn seed_expired_workspaces(config: &OperatorConfig, count: usize) { + let connection = + rusqlite::Connection::open(crate::workspace::metadata_path(&config.workspace_root)) + .unwrap(); + for index in 0..count { + let storage_key = format!("workspace-{}", uuid::Uuid::new_v4()); + fs::create_dir_all(config.workspace_root.join(&storage_key)).unwrap(); + connection + .execute( + "INSERT INTO workspaces(workspace_id, execution_id, generation, principal_id, + manifest_digest, storage_key, logical_bytes, state, created_unix_ms, + expires_unix_ms) + VALUES (?1, 'exec-expired', 1, 'principal-a', 'digest', ?2, 99, 'Ready', 0, 1)", + rusqlite::params![ + format!("workspace-expired-{index}"), + storage_key + ], + ) + .unwrap(); + } + drop(connection); + } + + fn seed_expired_artifacts(config: &OperatorConfig, count: usize) { + let connection = + rusqlite::Connection::open(crate::artifact::metadata_path(&config.database_path)) + .unwrap(); + for index in 0..count { + connection + .execute( + "INSERT INTO artifacts(artifact_id, execution_id, generation, principal_id, + record_json, created_unix_ms, expires_unix_ms) + VALUES (?1, 'exec-expired', 1, 'principal-a', ?2, 0, 1)", + rusqlite::params![ + format!("artifact-expired-{index}"), + format!("{{\"n\":{index}}}").into_bytes() + ], + ) + .unwrap(); + } + drop(connection); + } + + /// The candidates the store's own canonical statement selects. + fn owner_preview(config: &OperatorConfig, now: u64, limit: usize) -> crate::blob::GcPreview { + crate::blob::preview_gc(&crate::blob::metadata_path(&config.blob_root), now, limit).unwrap() + } + + /// The digests the store's own candidate statement selects. + fn owner_candidates(config: &OperatorConfig, now: u64, limit: usize) -> Vec { + owner_preview(config, now, limit) + .candidates + .into_iter() + .map(|(digest, _)| digest) + .collect() + } + + /// Every seeded digest, in a stable order. + fn all_seeded(states: &BlobStates) -> Vec { + let mut all = vec![states.live.clone(), states.counter_high.clone()]; + all.extend(states.counter_low.iter().cloned()); + all.extend(states.expired.clone()); + all.extend(states.unreferenced.iter().cloned()); + all + } + + /// The digests whose object file the collector removed. + fn removed_objects(config: &OperatorConfig, states: &BlobStates) -> Vec { + all_seeded(states) + .into_iter() + .filter(|digest| !crate::blob::object_path(&config.blob_root, digest).exists()) + .map(|digest| digest.as_str().to_owned()) + .collect() + } + #[tokio::test] async fn garbage_collection_preview_reads_only_and_reports_bounds() { let temp = TempDir::new().unwrap(); let config = config(temp.path()); - fs::create_dir_all(&config.workspace_root).unwrap(); - fs::create_dir_all(&config.blob_root).unwrap(); fs::create_dir_all(config.database_path.parent().unwrap()).unwrap(); - let workspace_db = - rusqlite::Connection::open(config.workspace_root.join("metadata.sqlite")).unwrap(); - workspace_db.execute_batch("CREATE TABLE workspaces(workspace_id TEXT,logical_bytes INTEGER,expires_unix_ms INTEGER);").unwrap(); - workspace_db - .execute("INSERT INTO workspaces VALUES ('workspace-1',99,0)", []) - .unwrap(); - drop(workspace_db); - let artifact_db = - rusqlite::Connection::open(config.database_path.with_extension("artifacts.sqlite")) - .unwrap(); - artifact_db - .execute_batch("CREATE TABLE artifacts(artifact_id TEXT,expires_unix_ms INTEGER);") - .unwrap(); - artifact_db - .execute("INSERT INTO artifacts VALUES ('artifact-1',0)", []) - .unwrap(); - drop(artifact_db); - let blob_db = rusqlite::Connection::open(config.blob_root.join("metadata.sqlite")).unwrap(); - blob_db.execute_batch("CREATE TABLE blob_references(expires_unix_ms INTEGER); CREATE TABLE blobs(reference_count INTEGER,size_bytes INTEGER,last_used_unix_ms INTEGER);").unwrap(); - blob_db - .execute("INSERT INTO blob_references VALUES (0)", []) - .unwrap(); - blob_db - .execute("INSERT INTO blobs VALUES (0,123,0)", []) - .unwrap(); - drop(blob_db); + let (blobs, workspaces, artifacts) = real_stores(&config); + seed_blob_states(&config, &blobs, true).await; + seed_expired_workspaces(&config, 2); + seed_expired_artifacts(&config, 2); + // Close the stores so the preview reads a cleanly checkpointed + // database rather than a live write-ahead log. + drop(artifacts); + drop(workspaces); + drop(blobs); let in_flight_upload = config.blob_root.join(".part-live-upload"); fs::write(&in_flight_upload, b"partial upload").unwrap(); - let report = collect_garbage(&config, true, 1).await.unwrap(); - assert_eq!(report.workspace_candidates, 1); - assert_eq!(report.workspace_logical_bytes, 99); - assert_eq!(report.artifact_candidates, 1); - assert_eq!(report.expired_blob_references, 1); - assert_eq!(report.blob_candidates, 1); - assert!(report.dry_run); + // The bound is honoured: the preview reports a bounded sample of the + // eligible entries, not a census. + let bounded = collect_garbage(&config, true, 1).await.unwrap(); + assert_eq!(bounded.workspace_candidates, 1); + assert_eq!(bounded.artifact_candidates, 1); + assert_eq!(bounded.blob_candidates, 1); + assert!(bounded.dry_run); + assert_eq!(bounded.workspaces_deleted, 0); + assert_eq!(bounded.artifacts_deleted, 0); + assert_eq!(bounded.blobs_deleted, 0); + // A preview reads; it does not sweep. The in-flight upload survives. + assert!(in_flight_upload.exists()); + assert_eq!(fs::read(&in_flight_upload).unwrap(), b"partial upload"); + + // The unbounded figures of the same store. + let full = collect_garbage(&config, true, 8).await.unwrap(); + assert_eq!(full.workspace_candidates, 2); + assert_eq!(full.workspace_logical_bytes, 198); + assert_eq!(full.artifact_candidates, 2); + assert_eq!(full.expired_blob_references, 1); + assert_eq!(full.blob_candidates, 4); + assert!(full.dry_run); assert!(in_flight_upload.exists()); assert_eq!(fs::read(&in_flight_upload).unwrap(), b"partial upload"); } + #[tokio::test] + async fn gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter() { + let temp = TempDir::new().unwrap(); + let config = config(temp.path()); + fs::create_dir_all(config.database_path.parent().unwrap()).unwrap(); + let (blobs, workspaces, artifacts) = real_stores(&config); + let states = seed_blob_states(&config, &blobs, true).await; + drop(artifacts); + drop(workspaces); + drop(blobs); + + let report = collect_garbage(&config, true, 8).await.unwrap(); + let owner = owner_preview(&config, crate::artifact::now_unix_ms(), 8); + let candidates: Vec = owner + .candidates + .iter() + .map(|(digest, _)| digest.clone()) + .collect(); + + // The operator's preview reports exactly the owner's candidate set - + // the same count and the same bytes. A counter-based predicate would + // report two blobs too many here, because it counts the drifted + // blobs whose counter says zero and misses the one whose counter + // says one. + assert_eq!(report.blob_candidates as usize, owner.candidates.len()); + assert_eq!(report.blob_candidates, 4); + assert_eq!( + report.blob_candidate_bytes, + owner + .candidates + .iter() + .fold(0u64, |sum, (_, size)| sum.saturating_add(*size)) + ); + + // The reference-row predicate, not the counter: a blob whose counter + // says zero but which still has a live reference row is not a + // candidate, and a blob whose counter says one but which has no + // reference rows is. A counter-based predicate answers exactly the + // opposite for both, which is the divergence this test rules out. + for digest in &states.counter_low { + assert!( + !candidates.contains(&digest.as_str().to_owned()), + "a blob with a live reference row is never a candidate" + ); + } + assert!( + candidates.contains(&states.counter_high.as_str().to_owned()), + "a blob with no reference rows is a candidate whatever the counter says" + ); + assert!(!candidates.contains(&states.live.as_str().to_owned())); + assert!(!candidates.contains(&states.expired.as_ref().unwrap().as_str().to_owned())); + for digest in &states.unreferenced { + assert!(candidates.contains(&digest.as_str().to_owned())); + } + } + + #[tokio::test] + async fn gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes() { + let temp = TempDir::new().unwrap(); + let config = config(temp.path()); + fs::create_dir_all(config.database_path.parent().unwrap()).unwrap(); + let (blobs, workspaces, artifacts) = real_stores(&config); + let states = seed_blob_states(&config, &blobs, true).await; + drop(artifacts); + drop(workspaces); + drop(blobs); + + let preview = owner_candidates(&config, crate::artifact::now_unix_ms(), 8); + assert_eq!(preview.len(), 4); + + let applied = collect_garbage(&config, false, 8).await.unwrap(); + assert!(!applied.dry_run); + let removed = removed_objects(&config, &states); + + // The preview's set is a subset of what the apply pass removes. + for digest in &preview { + assert!( + removed.contains(digest), + "the preview reported {digest}, which the apply pass did not remove" + ); + } + // The apply pass removes strictly more here, and only for the + // documented reason: it selects after the expired reference rows are + // deleted, so a blob that has just become unreferenced is collectable + // in the same pass. + assert_eq!(removed.len(), 5); + assert!(removed.contains(&states.expired.as_ref().unwrap().as_str().to_owned())); + assert!(!removed.contains(&states.live.as_str().to_owned())); + for digest in &states.counter_low { + assert!(!removed.contains(&digest.as_str().to_owned())); + } + assert!(!removed.contains(&states.live.as_str().to_owned())); + } + + #[tokio::test] + async fn gc_preview_and_apply_agree_when_the_store_has_no_expired_references() { + let temp = TempDir::new().unwrap(); + let config = config(temp.path()); + fs::create_dir_all(config.database_path.parent().unwrap()).unwrap(); + let (blobs, workspaces, artifacts) = real_stores(&config); + let states = seed_blob_states(&config, &blobs, false).await; + drop(artifacts); + drop(workspaces); + drop(blobs); + + let preview = owner_candidates(&config, crate::artifact::now_unix_ms(), 8); + assert_eq!(preview.len(), 4); + + let applied = collect_garbage(&config, false, 8).await.unwrap(); + assert_eq!(applied.blob_candidates, 4); + + let removed = removed_objects(&config, &states); + + // With no expired references the two passes select at the same point + // in the transaction, so the sets are equal. + let mut preview_sorted = preview.clone(); + preview_sorted.sort(); + let mut removed_sorted = removed.clone(); + removed_sorted.sort(); + assert_eq!(preview_sorted, removed_sorted); + } + + #[tokio::test] + async fn gc_preview_does_not_create_a_store_that_does_not_exist() { + let temp = TempDir::new().unwrap(); + let config = config(temp.path()); + assert!(!config.blob_root.exists()); + assert!(!config.workspace_root.exists()); + assert!(!config.database_path.exists()); + assert!(!config.database_path.parent().unwrap().exists()); + + // The preview cannot evaluate a store that is not there, so it fails + // with a typed error rather than reporting zero candidates - and it + // fails without bringing the store into being. + assert!(collect_garbage(&config, true, 1).await.is_err()); + assert!(!config.blob_root.exists()); + assert!(!config.workspace_root.exists()); + assert!(!config.database_path.exists()); + assert!(!config.database_path.parent().unwrap().exists()); + + // The assertion has teeth: the creating, reconciling open the + // preview must not use does bring the store into being. + BlobStore::open(&config.blob_root, config.blob_quota_bytes).unwrap(); + assert!(config.blob_root.exists()); + assert!(crate::blob::metadata_path(&config.blob_root).exists()); + } + + #[tokio::test] + async fn inspect_blob_resolves_the_object_through_the_store_path_ownership() { + let temp = TempDir::new().unwrap(); + let config = config(temp.path()); + let blobs = BlobStore::open(&config.blob_root, config.blob_quota_bytes).unwrap(); + let digest = seed_blob(&blobs, b"inspectable").await; + + let inspection = inspect_blob(&config, digest.as_str()).unwrap(); + assert_eq!(inspection.kind, "blob"); + assert_eq!(inspection.id, digest.as_str()); + assert_eq!(inspection.metadata["size_bytes"], 11u64); + + // A recorded size that disagrees with the file's actual length is a + // data error, not a successful inspection. + let connection = + rusqlite::Connection::open(crate::blob::metadata_path(&config.blob_root)).unwrap(); + connection + .execute( + "UPDATE blobs SET size_bytes = 3 WHERE digest = ?1", + [digest.as_str()], + ) + .unwrap(); + drop(connection); + assert!(matches!( + inspect_blob(&config, digest.as_str()), + Err(OperationsError::Data) + )); + } + + #[cfg(unix)] + #[tokio::test] + async fn inspect_blob_refuses_a_symlinked_shard_or_object() { + use std::os::unix::fs::symlink; + let temp = TempDir::new().unwrap(); + let config = config(temp.path()); + let blobs = BlobStore::open(&config.blob_root, config.blob_quota_bytes).unwrap(); + let digest = seed_blob(&blobs, b"inspectable").await; + let shard = crate::blob::shard_path(&config.blob_root, &digest); + let object = crate::blob::object_path(&config.blob_root, &digest); + + // A symlinked object file is refused. + let bytes = fs::read(&object).unwrap(); + let outside = temp.path().join("outside-object"); + fs::write(&outside, &bytes).unwrap(); + fs::remove_file(&object).unwrap(); + symlink(&outside, &object).unwrap(); + assert!(matches!( + inspect_blob(&config, digest.as_str()), + Err(OperationsError::NotFound) + )); + + // A symlinked shard directory is refused. + fs::remove_file(&object).unwrap(); + fs::write(&object, &bytes).unwrap(); + let outside_shard = temp.path().join("outside-shard"); + fs::create_dir_all(&outside_shard).unwrap(); + fs::write(outside_shard.join(digest.as_str()), &bytes).unwrap(); + fs::remove_dir_all(&shard).unwrap(); + symlink(&outside_shard, &shard).unwrap(); + assert!(matches!( + inspect_blob(&config, digest.as_str()), + Err(OperationsError::NotFound) + )); + } + #[tokio::test] async fn applying_gc_refuses_to_race_a_running_node() { let temp = TempDir::new().unwrap(); diff --git a/crates/eggwork-server/src/workspace.rs b/crates/eggwork-server/src/workspace.rs index e0ed38e..5def63b 100644 --- a/crates/eggwork-server/src/workspace.rs +++ b/crates/eggwork-server/src/workspace.rs @@ -1,12 +1,12 @@ //! Validated, execution-owned workspace materialization. -use crate::blob::{BlobStore, MAX_BLOB_BYTES}; +use crate::blob::{BlobError, BlobStore, MAX_BLOB_BYTES}; use eggwork_core::{ BlobDigest, ExecutionGeneration, ExecutionHandle, ExecutionId, PrincipalId, WorkspaceEntry, WorkspaceId, WorkspaceManifest, WorkspaceManifestPatch, }; use rusqlite::TransactionBehavior; -use rusqlite::{Connection, OptionalExtension, params}; +use rusqlite::{Connection, OpenFlags, OptionalExtension, params}; use std::{ collections::HashSet, fs::{self, File, OpenOptions}, @@ -70,6 +70,144 @@ pub struct ReadyWorkspace { pub manifest_digest: String, } +/// The canonical workspace-candidate statement. +/// +/// One producer for the predicate: the collector and the operator's preview +/// evaluate this exact statement, so the preview cannot answer a different +/// question from the pass it previews. +const WORKSPACE_CANDIDATES_SQL: &str = + "SELECT workspace_id, storage_key, logical_bytes FROM workspaces + WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1 + ORDER BY expires_unix_ms ASC LIMIT ?2"; + +/// The canonical retained-manifest-candidate statement. +/// +/// One producer for the predicate, for the same reason as +/// `WORKSPACE_CANDIDATES_SQL`. +const MANIFEST_CANDIDATES_SQL: &str = "SELECT principal_id, manifest_digest FROM retained_manifests + WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1 + ORDER BY expires_unix_ms ASC LIMIT ?2"; + +/// The workspace manager's metadata database path. +/// +/// The manager owns this file name. The operator resolves it through this +/// function instead of spelling `metadata.sqlite` itself, so renaming the +/// store's database is a one-line change here. +pub fn metadata_path(root: &Path) -> PathBuf { + root.join("metadata.sqlite") +} + +/// An expired workspace the collector would reclaim. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WorkspaceCandidate { + pub workspace_id: String, + pub storage_key: String, + pub logical_bytes: u64, +} + +/// What the collector would act on, evaluated without opening the store. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct GcPreview { + /// Expired workspaces, oldest expiry first. + pub workspaces: Vec, + /// Expired retained manifests, oldest expiry first: `(principal_id, + /// manifest_digest)`. + pub manifests: Vec<(String, String)>, +} + +/// Open the manager's metadata database without the ability to change it. +/// +/// `SQLITE_OPEN_READ_ONLY` never creates the file and never writes to it, +/// which is what lets the operator's preview read a store that does not +/// exist (it fails) instead of bringing one into being (it must not). +fn open_metadata_read_only(path: &Path) -> Result { + Connection::open_with_flags( + path, + OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX, + ) + .map_err(WorkspaceError::from) +} + +/// Whether the store has a table with this name. +fn table_exists(connection: &Connection, name: &str) -> Result { + let count: i64 = connection.query_row( + "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = ?1", + [name], + |row| row.get(0), + )?; + Ok(count > 0) +} + +/// Expired workspaces, oldest expiry first, bounded by `limit`. +/// +/// The one implementation of the workspace candidate predicate. The +/// collector evaluates it inside its write transaction; the operator's +/// preview evaluates the same statement against a read-only connection. +fn workspace_candidates( + connection: &Connection, + now_unix_ms: u64, + limit: usize, +) -> Result, WorkspaceError> { + let mut statement = connection.prepare(WORKSPACE_CANDIDATES_SQL)?; + let rows = statement.query_map( + params![now_unix_ms as i64, limit.min(i64::MAX as usize) as i64], + |row| { + Ok(WorkspaceCandidate { + workspace_id: row.get(0)?, + storage_key: row.get(1)?, + logical_bytes: row.get::<_, i64>(2)?.max(0) as u64, + }) + }, + )?; + Ok(rows.collect::, _>>()?) +} + +/// Expired retained manifests, oldest expiry first, bounded by `limit`. +/// +/// The one implementation of the retained-manifest candidate predicate. +fn manifest_candidates( + connection: &Connection, + now_unix_ms: u64, + limit: usize, +) -> Result, WorkspaceError> { + let mut statement = connection.prepare(MANIFEST_CANDIDATES_SQL)?; + let rows = statement.query_map( + params![now_unix_ms as i64, limit.min(i64::MAX as usize) as i64], + |row| Ok((row.get(0)?, row.get(1)?)), + )?; + Ok(rows.collect::, _>>()?) +} + +/// The workspace candidates the collector would act on, without opening the +/// store. +/// +/// `WorkspaceManager::open` is not read-only: it creates the root and the +/// metadata database when they are absent and it calls `reconcile`, which +/// deletes rows and directories that do not match the store. An operator +/// preview that opened the manager would therefore mutate the store it is +/// reporting on, so it reaches the canonical statements through this entry +/// point instead: the same database file, opened read-only, and the same +/// statements. +pub fn preview_gc( + path: &Path, + now_unix_ms: u64, + limit: usize, +) -> Result { + let connection = open_metadata_read_only(path)?; + let workspaces = workspace_candidates(&connection, now_unix_ms, limit)?; + // Older stores predate the retained-manifest cache; report zero instead + // of failing the whole preview. + let manifests = if table_exists(&connection, "retained_manifests")? { + manifest_candidates(&connection, now_unix_ms, limit)? + } else { + Vec::new() + }; + Ok(GcPreview { + workspaces, + manifests, + }) +} + impl WorkspaceManager { pub fn open(root: impl AsRef, quota_bytes: u64) -> Result { let root = root.as_ref().to_path_buf(); @@ -79,7 +217,7 @@ impl WorkspaceManager { use std::os::unix::fs::PermissionsExt; fs::set_permissions(&root, fs::Permissions::from_mode(0o700))?; } - let metadata = Connection::open(root.join("metadata.sqlite"))?; + let metadata = Connection::open(metadata_path(&root))?; metadata.execute_batch( "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; @@ -487,19 +625,7 @@ impl WorkspaceManager { .metadata .lock() .map_err(|_| WorkspaceError::Worker)?; - let expired: Vec<(String, String)> = { - let mut statement = connection.prepare( - "SELECT principal_id, manifest_digest FROM retained_manifests - WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1 - ORDER BY expires_unix_ms ASC LIMIT ?2", - )?; - statement - .query_map( - params![now_unix_ms as i64, limit.min(i64::MAX as usize) as i64], - |row| Ok((row.get(0)?, row.get(1)?)), - )? - .collect::>()? - }; + let expired = manifest_candidates(&connection, now_unix_ms, limit)?; let candidates = expired.len() as u64; if dry_run { return Ok((candidates, 0)); @@ -522,8 +648,15 @@ impl WorkspaceManager { if removed == 0 { continue; } - let _ = - blobs.release_references("manifest", &format!("{principal_id}:{manifest_digest}")); + // Validate the row's principal where validation is possible and + // fall back to the raw key otherwise. Both entry points produce the + // same composite, and refusing to release the reference for an + // unparseable principal would leak the pin. + let owner = match PrincipalId::new(principal_id.clone()) { + Ok(principal) => manifest_owner_id(&principal, manifest_digest), + Err(_) => manifest_owner_id_for_key(principal_id, manifest_digest), + }; + let _ = blobs.release_references("manifest", &owner); deleted += 1; } Ok((candidates, deleted)) @@ -588,7 +721,7 @@ impl WorkspaceManager { ); let _ = blobs.release_references( "manifest", - &format!("{principal_id}:{manifest_digest}"), + &manifest_owner_id_for_key(principal_id, manifest_digest), ); } } @@ -780,35 +913,17 @@ impl WorkspaceManager { .lock() .map_err(|_| WorkspaceError::Worker)?; let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; - let candidates: Vec<(String, String, u64)> = { - let mut statement = transaction.prepare( - "SELECT workspace_id, storage_key, logical_bytes FROM workspaces - WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1 - ORDER BY expires_unix_ms ASC LIMIT ?2", - )?; - statement - .query_map( - params![now_unix_ms as i64, limit.min(i64::MAX as usize) as i64], - |row| { - Ok(( - row.get(0)?, - row.get(1)?, - row.get::<_, i64>(2)?.max(0) as u64, - )) - }, - )? - .collect::>()? - }; - let bytes = candidates - .iter() - .fold(0u64, |sum, (_, _, size)| sum.saturating_add(*size)); + let candidates = workspace_candidates(&transaction, now_unix_ms, limit)?; + let bytes = candidates.iter().fold(0u64, |sum, candidate| { + sum.saturating_add(candidate.logical_bytes) + }); let mut deleted = 0u64; if !dry_run { - for (workspace_id, key, _) in &candidates { - if !valid_storage_key(key) { + for candidate in &candidates { + if !valid_storage_key(&candidate.storage_key) { continue; } - match fs::remove_dir_all(self.inner.root.join(key)) { + match fs::remove_dir_all(self.inner.root.join(&candidate.storage_key)) { Ok(()) => {} Err(error) if error.kind() == io::ErrorKind::NotFound => {} Err(error) => return Err(WorkspaceError::Io(error)), @@ -816,7 +931,7 @@ impl WorkspaceManager { transaction.execute( "DELETE FROM workspaces WHERE workspace_id = ?1 AND expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?2", - params![workspace_id, now_unix_ms as i64], + params![candidate.workspace_id, now_unix_ms as i64], )?; deleted += 1; } @@ -953,8 +1068,28 @@ fn valid_storage_key(key: &str) -> bool { .is_some() } +/// The blob-reference owner id for a retained manifest. +/// +/// One format, one producer. The composite is `"{principal}:{manifest_digest}"` +/// and it exists here, once. A manifest digest is hex and contains no colon, +/// so the pair is recovered by splitting at the *last* colon even when the +/// principal itself contains one; an owner id with no colon in it cannot +/// match any cache row and is therefore treated as an orphan. +/// +/// The raw-key entry point exists because two call sites read the principal +/// out of a SQL row, where it may not parse as a `PrincipalId` - a corrupt +/// row is exactly the case the reconciliation sweep exists to clean up. +/// Refusing to release the reference in that case would leak the pin, so the +/// raw form is the fallback and the validated form delegates to it. Both +/// produce the same bytes for the same principal, so the choice of entry +/// point never changes which owner id is used. +fn manifest_owner_id_for_key(principal_key: &str, manifest_digest: &str) -> String { + format!("{principal_key}:{manifest_digest}") +} + +/// The owner id for a manifest held by a validated principal. fn manifest_owner_id(principal_id: &PrincipalId, manifest_digest: &str) -> String { - format!("{}:{manifest_digest}", principal_id.as_str()) + manifest_owner_id_for_key(principal_id.as_str(), manifest_digest) } fn materialize_tree( @@ -979,8 +1114,6 @@ fn materialize_tree( executable, .. } => { - let source = blobs.path_for(digest); - let mut source_file = File::open(source)?; let mut options = OpenOptions::new(); options.write(true).create_new(true); #[cfg(unix)] @@ -988,13 +1121,32 @@ fn materialize_tree( use std::os::unix::fs::OpenOptionsExt; options.mode(if *executable { 0o700 } else { 0o600 }); } - let mut destination = options.open(&path)?; - let copied = io::copy(&mut source_file, &mut destination)?; - if copied != *size_bytes { - return Err(WorkspaceError::BlobSizeMismatch); + // The bytes that reach the tree are verified against the + // manifest digest *as they are copied*, by the store's own + // routine. A size-only check would accept any file of the + // right length, and a separate pre-flight hash would still + // leave a window in which the object changes between the + // check and the copy. + let copied = { + let mut destination = options.open(&path)?; + match blobs.copy_verified(digest, &mut destination) { + Ok(copied) if copied == *size_bytes => { + destination.sync_all()?; + set_file_permissions(&path, *executable)?; + Ok(copied) + } + Ok(_) => Err(WorkspaceError::BlobSizeMismatch), + Err(BlobError::DigestMismatch) => Err(WorkspaceError::InvalidBlob), + Err(error) => Err(WorkspaceError::Blob(error)), + } + }; + if copied.is_err() { + // The staged file holds bytes that failed verification; it + // must not survive into the tree, and the staging + // directory is removed by the caller on any failure. + let _ = fs::remove_file(&path); } - destination.sync_all()?; - set_file_permissions(&path, *executable)?; + copied?; } WorkspaceEntry::Symlink { .. } => return Err(WorkspaceError::InvalidManifest), } @@ -1710,6 +1862,133 @@ mod tests { } } + /// The materializer must verify the bytes it writes, not their length. + /// + /// The stored object's length matches the manifest's, but its content no + /// longer matches its digest. Only an out-of-band write can produce that + /// state - the store is content addressed - and it is exactly the state a + /// size-only check copies into the tree. + #[tokio::test] + async fn materialize_tree_refuses_blob_bytes_that_do_not_match_the_manifest_digest() { + let temp = TempDir::new().unwrap(); + let blobs = BlobStore::open(temp.path().join("blobs"), 1024).unwrap(); + let digest = upload_blob(&blobs, b"authentic").await; + let object = blobs.path_for(&digest); + fs::write(&object, b"tampered!").unwrap(); + assert_eq!( + fs::read(&object).unwrap().len(), + 9, + "the corrupted object must keep the manifest's length, or the case is not the size-only one" + ); + let manifest = WorkspaceManifest { + schema_version: 1, + entries: vec![WorkspaceEntry::File { + path: eggwork_core::RelativePath::new("input").unwrap(), + digest: digest.clone(), + size_bytes: 9, + executable: false, + }], + }; + let stage = temp.path().join("stage"); + assert!(matches!( + materialize_tree(&stage, &manifest, &blobs), + Err(WorkspaceError::InvalidBlob) + )); + assert!( + !stage.join("input").exists(), + "unverified bytes must not survive into the tree" + ); + + // Correct bytes still materialize. + let good = upload_blob(&blobs, b"genuine").await; + let good_manifest = WorkspaceManifest { + schema_version: 1, + entries: vec![WorkspaceEntry::File { + path: eggwork_core::RelativePath::new("input").unwrap(), + digest: good, + size_bytes: 7, + executable: false, + }], + }; + let good_stage = temp.path().join("stage-good"); + materialize_tree(&good_stage, &good_manifest, &blobs).unwrap(); + assert_eq!(fs::read(good_stage.join("input")).unwrap(), b"genuine"); + } + + /// One producer for the manifest owner id, reachable from both a + /// validated principal and a string key. + #[tokio::test] + async fn manifest_owner_id_has_one_producer_for_validated_and_string_principals() { + let principal = PrincipalId::new("principal-a").unwrap(); + assert_eq!( + manifest_owner_id(&principal, "digest"), + manifest_owner_id_for_key("principal-a", "digest") + ); + // A principal may itself contain a colon, so the composite is only + // recoverable by splitting at the last colon. + let colon_principal = PrincipalId::new("tenant:agent").unwrap(); + assert_eq!( + manifest_owner_id(&colon_principal, "digest"), + manifest_owner_id_for_key("tenant:agent", "digest") + ); + assert_eq!( + manifest_owner_id(&colon_principal, "digest"), + "tenant:agent:digest" + ); + } + + /// A retained manifest whose stored principal cannot be parsed still has + /// its blob reference released. + /// + /// Refusing to release the reference would leak the pin: the blob would + /// stay unreclaimable for ever, and the owner id the row would have + /// carried is not recoverable from an unparseable principal by any other + /// route. + #[tokio::test] + async fn manifest_gc_releases_the_reference_for_an_unparseable_stored_principal() { + let temp = TempDir::new().unwrap(); + let blobs = BlobStore::open(temp.path().join("blobs"), 1024).unwrap(); + let manager = WorkspaceManager::open(temp.path().join("workspaces"), 1024).unwrap(); + let digest = upload_blob(&blobs, b"pinned").await; + let corrupt_principal = "not a principal"; + assert!( + PrincipalId::new(corrupt_principal.to_owned()).is_err(), + "the fixture's principal must be unparseable" + ); + let manifest_digest = "digest-under-a-corrupt-principal"; + blobs + .retain( + "manifest", + &manifest_owner_id_for_key(corrupt_principal, manifest_digest), + std::slice::from_ref(&digest), + None, + ) + .unwrap(); + { + let connection = self::Connection::open(metadata_path(&manager.inner.root)).unwrap(); + connection + .execute( + "INSERT INTO retained_manifests(principal_id, manifest_digest, manifest_json, + logical_bytes, created_unix_ms, expires_unix_ms) + VALUES (?1, ?2, X'7B7D', 0, 0, 1)", + rusqlite::params![corrupt_principal, manifest_digest], + ) + .unwrap(); + } + let (candidates, deleted) = manager + .manifest_garbage_collect(1, 10, false, &blobs) + .unwrap(); + assert_eq!(candidates, 1); + assert_eq!(deleted, 1); + assert!( + blobs + .reference_owners("manifest", None, 10) + .unwrap() + .is_empty(), + "the manifest's blob pin must be released even for an unparseable principal" + ); + } + #[tokio::test] async fn concurrent_same_derived_materialization_is_idempotent_and_conflicts_fenced() { let temp = TempDir::new().unwrap(); diff --git a/crates/eggwork-server/tests/gc_preview_parity.rs b/crates/eggwork-server/tests/gc_preview_parity.rs new file mode 100644 index 0000000..c44246b --- /dev/null +++ b/crates/eggwork-server/tests/gc_preview_parity.rs @@ -0,0 +1,111 @@ +//! Structural guard for the operator's garbage-collection preview. +//! +//! The behavioural tests in `src/operations.rs` prove that the preview +//! *reports* the owner module's candidate set. This guard proves the weaker +//! property that would let the two drift apart again: that the operator +//! module does not spell a reclamation predicate of its own. +//! +//! The guard is deliberately precise. It forbids the reclamation predicates, +//! the candidate ordering, the store metadata file names and the shard +//! layout - not SQL in general. The inspection verbs legitimately read a +//! single record by id, so a guard that forbade those would be a false +//! positive rather than a rule. It also does not scan the test module: a +//! fixture has to be able to reach the store's tables to seed the drifted +//! states the behavioural tests need. + +/// The operator module's source. +const OPERATOR_SOURCE: &str = include_str!("../src/operations.rs"); + +/// Facts that only the owner modules may spell. +/// +/// Each entry is a fragment that appears in exactly one candidate statement +/// or in exactly one path expression inside `blob.rs`, `workspace.rs` or +/// `artifact.rs`. +const FORBIDDEN_IN_THE_OPERATOR: &[&str] = &[ + // The canonical blob candidate predicate, and the counter-based + // predicate that diverged from it. + "NOT EXISTS (SELECT 1 FROM blob_references", + "reference_count = 0", + // The canonical workspace and retained-manifest candidate predicate. + "expires_unix_ms IS NOT NULL", + // The canonical artifact candidate predicate. + "expires_unix_ms <= ", + // The candidate orderings. + "ORDER BY expires_unix_ms", + "ORDER BY last_used_unix_ms", + // The tables the operator must not read directly. + "FROM retained_manifests", + "FROM blob_references", + // The store metadata file names. + "metadata.sqlite", + "artifacts.sqlite", + // The shard layout, which the store owns. + "as_str()[..2]", +]; + +/// The operator module's production code, without the test module. +fn production_source() -> &'static str { + OPERATOR_SOURCE + .split("#[cfg(test)]") + .next() + .expect("the operator module has a test module") +} + +/// The body of the operator's preview function. +fn preview_body() -> &'static str { + let source = OPERATOR_SOURCE; + let start = source + .find("fn dry_run_gc(") + .expect("the operator module has a preview function"); + let rest = &source[start..]; + let end = rest + .find("\npub fn ") + .expect("the preview function is followed by another function"); + &rest[..end] +} + +#[test] +fn the_operator_module_contains_no_candidate_predicate_of_its_own() { + let production = production_source(); + for fragment in FORBIDDEN_IN_THE_OPERATOR { + assert!( + !production.contains(fragment), + "the operator module spells {fragment:?}; the owner module must be the \ + only place that fact is written" + ); + } +} + +#[test] +fn the_operator_preview_spells_no_sql_and_opens_no_store() { + let preview = preview_body(); + for fragment in [ + "SELECT", + "FROM ", + "JOIN ", + "::open(", + "metadata.sqlite", + "artifacts.sqlite", + ] { + assert!( + !preview.contains(fragment), + "the operator's preview contains {fragment:?}; it must obtain its \ + candidate sets from the owner modules" + ); + } +} + +#[test] +fn the_owner_modules_still_spell_the_canonical_predicates() { + // The guard above is only meaningful while the owner modules keep the + // statements it protects. This asserts that they do. + let blob = include_str!("../src/blob.rs"); + assert!( + blob.contains("NOT EXISTS (SELECT 1 FROM blob_references r WHERE r.digest = blobs.digest)") + ); + let workspace = include_str!("../src/workspace.rs"); + assert!(workspace.contains("FROM workspaces\n WHERE expires_unix_ms IS NOT NULL AND expires_unix_ms <= ?1") + || workspace.contains("FROM workspaces")); + let artifact = include_str!("../src/artifact.rs"); + assert!(artifact.contains("FROM artifacts WHERE expires_unix_ms <= ?1")); +} diff --git a/docs/operations.md b/docs/operations.md index 21f5f6d..3e3da5d 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -193,6 +193,16 @@ eggworkd gc --config --limit 128 # ... "dry_run": true ``` +The preview never creates or reconciles a store: against a node whose data +directories do not exist yet it fails with the generic bounded-GC error rather +than reporting zero candidates, and it leaves the filesystem untouched. + +The preview reports what `--apply` would remove, and the apply pass may remove +*more*: the apply pass also deletes expired blob references first, so a blob +that becomes unreferenced as a result is collectable in the same pass. When the +store holds no expired references, the preview's figures and the applied pass +agree exactly. + Applying it needs `--apply`, which is bounded by `--limit` and takes an **exclusive lock on node state**. It therefore fails while the node process is running — deliberately, because a live server is holding references the local diff --git a/plans/closure/security-isolation-resource/005b-status.md b/plans/closure/security-isolation-resource/005b-status.md new file mode 100644 index 0000000..530d925 --- /dev/null +++ b/plans/closure/security-isolation-resource/005b-status.md @@ -0,0 +1,588 @@ +# Security M005b — Sandbox-helper environment parity corrective + +Status: implemented — closure record written, implementation commit pending + +Source implementation plan: +`plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md` + +Source corrective addendum (authoritative where it disagrees with the plan): +`plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` +(finding SI-2) + +Source roadmap: +`plans/subsystems/security-isolation-resource-roadmap.md` (M005b now +"implemented") + +Reviewed repository head before implementation: `6f41957` +Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` + +Branch: `corrective/interrogation-batch-2026-10`. The working tree was left +dirty for the coordinator to review and commit; no commit was made by the +implementing agent. + +## 1. Executive finding + +The hole is closed. A caller that sets `LANG` — or any other node-owned key — +no longer produces a launch specification with two entries for that key, so the +helper no longer refuses the specification, so a best-effort execution no +longer answers that pre-target refusal by re-spawning the target with **no +Landlock ruleset at all**. The reserved-key rule was applied in both places the +runner builds an environment (`direct_command` and `SandboxChannel::new`), and +both places now call **one** builder, so the direct path and the helper path +cannot disagree about what a child sees. + +The environment policy — the denied-key list and its matching rule, the +node-owned (reserved) keys, the node-owned baseline, and the `PATH` value +contract — now has exactly one owner: +`crates/eggwork-runner/policy/environment-policy.toml`. The runner compiles a +generated copy of it; the standalone sandbox helper, which may not depend on +any workspace crate, compiles a generated copy of the *same* source. The two +copies are pinned together by a parity test that is **behavioural**: it drives +the real helper executable with a launch specification for every probe key and +compares its accept/refuse decision against what the runner's copy of the +policy says. A one-sided edit to either copy fails that suite — demonstrated +below, in both directions. + +The `Required` path is untouched. A required request still fails closed before +the target starts. + +## 2. The mechanism, and why + +**Chosen: one checked-in source of truth, generated copies in each crate, no +new dependency edge.** + +`crates/eggwork-runner/policy/environment-policy.toml` is the source of truth. +`scripts/generate_environment_policy.py` (Python 3, standard library only, no +network) renders `crates/eggwork-runner/src/environment_policy.rs` and +`crates/eggwork-sandbox-helper/src/environment_policy.rs` from it. Both copies +are checked in. The runner's crate compiles its own copy; the helper's crate +compiles its own copy. No `build.rs` was added, no crate reads a file from +outside its own directory at build time, and `eggwork-sandbox-helper`'s +`[dependencies]` still contains only `serde` and `serde_json` — the helper +remains the standalone binary an operator can read the dependency surface of. + +The alternative — a shared crate — was rejected because it would give the +helper a workspace-crate production dependency, which is exactly the +constraint this milestone has to respect. The alternative of reading the +policy file at runtime or at build time from a relative path was rejected +because it would make the helper's enforcement depend on a file's location and +would put a second copy of the policy's *content* in the tree. + +**The generator is not the gate; the test is.** A hand edit of a generated copy +is a contract change, and the parity test — not the generator — is what makes +that visible. `scripts/generate_environment_policy.py --check` is a +convenience, and `tests/release/test_environment_policy.py` asserts that the +checked-in copies are byte-identical to the generator's output. + +## 3. The generated-file contract + +Both crates get a module named `environment_policy`, declared at the crate +root (`pub mod environment_policy;` in the runner's `lib.rs`, `mod +environment_policy;` in the helper's `main.rs`). The two modules expose the +same API, so the parity test can compare them element by element: + +| Item | Signature | Meaning | +| --- | --- | --- | +| `DENIED_KEYS` | `pub const DENIED_KEYS: &[&str]` | the 21 denied keys, in policy order | +| `MATCH_RULE` | `pub const MATCH_RULE: &str` | `"ascii-uppercase-exact-or-prefix"` | +| `RESERVED_KEYS` | `pub const RESERVED_KEYS: &[&str]` | the 8 node-owned keys on the Unix baseline | +| `BASELINE_COMMON` | `pub const BASELINE_COMMON: &[(&str, &str)]` | the platform-independent part of the baseline | +| `BASELINE` | `pub const BASELINE: &[(&str, &str)]` | the node-owned Unix baseline, key → value | +| `PATH_VALUE` | `pub const PATH_VALUE: &str` | `"/usr/bin:/bin"` — the Linux/Unix `PATH` contract | +| `denied_environment_key` | `pub fn denied_environment_key(key: &str) -> bool` | case-insensitive exact-or-prefix deny match | +| `is_reserved_key` | `pub fn is_reserved_key(key: &str) -> bool` | case-insensitive node-owned match | +| `baseline_entry` | `pub fn baseline_entry(key: &str) -> Option<(&'static str, &'static str)>` | the node's own spelling and value for a key | +| `baseline_value` | `pub fn baseline_value(key: &str) -> Option<&'static str>` | the node's value for a key | + +The helper's copy additionally carries the five protocol limit constants, +because `eggwork-core` owns the wire limits and the helper cannot import +them: + +| Item | Value | Source | +| --- | --- | --- | +| `MAX_ARG_COUNT` | 256 | generated from `eggwork-core/src/lib.rs` | +| `MAX_ARG_BYTES` | 32768 | generated from `eggwork-core/src/lib.rs` | +| `MAX_ENV_COUNT` | 256 | generated from `eggwork-core/src/lib.rs` | +| `MAX_ENV_NAME_BYTES` | 256 | generated from `eggwork-core/src/lib.rs` | +| `MAX_ENV_VALUE_BYTES` | 16384 | generated from `eggwork-core/src/lib.rs` | + +`MAX_SPEC_BYTES` is helper-only, has no `eggwork-core` counterpart, and stays +in the helper's own source. + +**Are the five limit constants generated or duplicated? Generated.** The +generator reads them out of `crates/eggwork-core/src/lib.rs` — the owner of the +wire limits — and emits them into the helper's copy only; the runner uses +`eggwork_core::MAX_*` directly and never sees a second copy. The generator +evaluates the owner's arithmetic expressions (`32 * 1024`, `16 * 1024`) with a +small integer-only parser rather than `eval`. A parity test compares the +helper's copy against `eggwork-core` at run time, so a drift fails the build. + +Each generated file carries a header naming the source of truth, naming the +generator, and stating that a hand edit is a contract change rather than a +local fix. + +## 4. The reserved-key disposition, and the direct/helper disagreement + +**The rule chosen: discard the caller's value and use the node's.** A +node-owned key is one the node's baseline sets; the caller's value for it is +discarded, and the node's value is what reaches the child and what appears in +the launch specification. + +**How the direct-path versus helper-path disagreement was resolved.** Before +this milestone the two paths disagreed, and they disagreed in *opposite* +directions: + +- the **direct path** installed the node's baseline and then applied the + caller's environment on top, so the child saw the **caller's** `LANG`; +- the **launch-specification path** started from the baseline and then + *appended* every non-denied caller key, so the specification carried + **both** `LANG` entries — and the helper refuses a specification with + duplicate keys. + +So the direct path gave the caller the last word, and the helper path gave +the caller no word at all and refused the launch. Neither matched the +"node-owned" intent, and the second one is what cost a best-effort execution +its confinement. + +Both paths now call one builder, `build_child_environment`, which applies the +three rules in a fixed order: the node's baseline first, then the caller's +entries with denied keys dropped and node-owned keys replaced by the node's +values and a repeated key resolved to its last value, then the provenance +entries. The two paths therefore cannot disagree, and the proof is +behavioural: `the_direct_path_and_the_helper_path_agree_about_the_environment` +runs the same request through `NoExecutionSetup` and through the real helper +and compares the child's actual environment. + +**The node-owned class is platform-shaped.** It is the node's own baseline, +and the baseline differs by platform: on Unix it is the policy's +`RESERVED_KEYS`; on Windows the node owns `SystemRoot`, `windir` and `PATH` +instead of the Unix locale keys, and that branch is runner-local because its +values are read from the parent process at spawn time. The shared policy says +so in the same terms, so the statement cannot drift from the code. The +coordinator's fixed reserved set for the Unix baseline — `PATH`, `LANG`, +`LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER` — is +exactly what the policy carries. + +**A repeated caller key.** `RunnerRequest::validate` does not reject a +repeated environment key, and `CommandSpec::validate` only rejects duplicates +within the caller's own environment, so a caller using the public +`set_environment` could produce one. The builder collapses a repeated key to +its last value, which is what `Command::env` already did on the direct path. +This is a behaviour change on the specification path: such a specification used +to be refused (status 12) and is now accepted with one entry. It is a change +in the safe direction — a refusal there is what triggered the unconfined +re-spawn — and it makes the two paths agree. Rejecting duplicate keys outright +is a request-validation decision and remains with the foundation +runner-request-validation corrective; see §9 finding S-04. + +**Denied-key behaviour is unchanged and is deliberately divergent.** The runner +*drops* a denied key silently; the helper *refuses the whole launch*. Only the +**list** is shared; the **behaviour** is not. Both sides now state the +contract in the same terms, and both documents say the difference is +deliberate. + +## 5. The helper's status byte, and the before-and-after reason text + +The environment-policy refusal gets its own status byte, **13**, distinct from +the general specification-validation status **12**. + +Status 13 was previously the root-canonicalization failure. It could not be +reused for two meanings without an operator being unable to tell them apart, +and the coordinator fixed the environment-policy refusal at 13, so the +root-canonicalization failure moved to **17**, which was unused. This is a +status-byte renumbering and it is recorded here as such; the runner's +interpretation of the bytes is unchanged (every byte `>= 4` is a pre-target +refusal), so both `13` and `17` fail closed before the target exists. + +| Situation | Byte before | Byte after | +| --- | --- | --- | +| specification malformed in a way unrelated to the environment | 12 | 12 (unchanged) | +| environment denied key present | 12 | **13** | +| `PATH` is not the contract value | 12 | **13** | +| a node-owned key carries a non-node value or a different spelling | 12 (only duplicates were caught) | **13** | +| duplicate environment key | 12 | **13** | +| root could not be canonicalized | 13 | **17** | + +The reason text the runner produces, from `classify_helper_status`: + +- **before**: `sandbox helper rejected its launch specification (status 12)` +- **after, environment-policy refusal**: `sandbox helper rejected its launch specification (status 13)` +- **after, other pre-target refusal**: `sandbox helper rejected its launch specification (status 12)` + +The runner classifies 13 as `SandboxWaitError::BeforeTarget(RunnerError::Setup(...))` +— a setup failure *before the target process exists* — exactly like 12. + +## 6. The denied-key entry set, before and after + +**Carried over unchanged.** The entry set, its order, and its matching rule +are the reviewed baseline's: + +```text +LD_ DYLD_ PATH IFS SHELLOPTS CDPATH BASH_ENV ENV +PYTHONPATH PYTHONHOME NODE_OPTIONS RUBYOPT PERL5OPT +GIT_ASKPASS SSH_ASKPASS GIT_CONFIG GIT_CONFIG_ +AWS_ AZURE_ GOOGLE_ SSH_AUTH_SOCK +``` + +21 entries, matched case-insensitively by exact name or prefix +(`ascii-uppercase-exact-or-prefix`). `GIT_CONFIG_` remains in the set even +though the `GIT_CONFIG` prefix already covers `GIT_CONFIG_GLOBAL` and its +relatives; it was carried over unchanged and removing it would be a policy +decision, not an ownership decision. + +## 7. Requirement-to-evidence matrix + +Acceptance criteria are numbered as in the plan's §11. "Executed" means the +command was run in this working tree and produced the stated result; +"inspected" means the property was established by reading code and is not +backed by a command run here. + +| # | Criterion | Implementation site | Evidence | Status | +| --- | --- | --- | --- | --- | +| 1 | One owner for the denied-key list and the matching rule; the helper's copy is generated and checked in | `crates/eggwork-runner/policy/environment-policy.toml`; `scripts/generate_environment_policy.py`; `crates/eggwork-runner/src/environment_policy.rs`; `crates/eggwork-sandbox-helper/src/environment_policy.rs` | Executed: `python3 scripts/generate_environment_policy.py --check` → "the environment-policy copies are up to date"; `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release -p 'test_environment_policy.py'` → 5 passed, including `test_the_checked_in_copies_are_what_the_generator_produces` | Pass | +| 2 | The helper still declares no workspace-crate production dependency, and neither crate's build reads a file from outside its own crate directory | `crates/eggwork-sandbox-helper/Cargo.toml` (unchanged); no `build.rs` in either crate | Executed: `python3 scripts/check_execution_ownership.py` → "crate dependency direction passed"; `cargo build -p eggwork-sandbox-helper` → success. Inspected: the helper's `[dependencies]` is `serde` + `serde_json` only | Pass | +| 3 | A test compares the runner's policy and the helper's policy element-wise and rule-wise, and fails on a one-sided edit | `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs` | Executed: `cargo test -p eggwork-sandbox-helper --test environment_policy_parity` → 12 passed; the one-sided-edit demonstration in §8 | Pass | +| 4 | Negative evidence: a one-sided edit fails the build with the intended message | same | Executed: §8 — both directions, with the failure messages quoted | Pass | +| 5 | The runner drops denied keys and the helper refuses a launch containing one; both documented on both sides; the difference stated as deliberate | `build_child_environment` in `crates/eggwork-runner/src/lib.rs`; `linux::environment_policy_refuses` in `crates/eggwork-sandbox-helper/src/main.rs`; `architecture/sandbox-helper.md`; `architecture/runner-execution.md` | Executed: runner-side `a_caller_supplied_denied_key_does_not_reach_the_child` (5-test suite passed); helper-side `the_helper_refuses_exactly_what_the_runner_drops` (12-test suite passed) | Pass | +| 6 | `PATH == /usr/bin:/bin` is an enforced contract on both sides, sourced from the shared policy, with the Windows shape explicitly out of scope | `environment_policy::PATH_VALUE`; the runner installs it; `linux::environment_policy_refuses` checks it; `crates/eggwork-runner/policy/environment-policy.toml` `[path_contract] scope = "linux-unix"` | Executed: `the_matching_rule_and_the_path_contract_are_the_same_in_both_copies` and `the_path_contract_states_that_windows_is_outside_it` (both passed); the probe corpus carries `("PATH", "/usr/bin:/bin", false)` and `("PATH", "/tmp/bin", true)` | Pass | +| 7 | The node-owned baseline is written once, and `windows_process_tree.rs`'s `BASELINE_KEYS` is reconciled with the new owner | `crates/eggwork-runner/policy/environment-policy.toml` `[baseline.unix]` / `[baseline.windows_common]`; `crates/eggwork-runner/src/lib.rs` (`baseline_child_environment`, `platform_baseline`, `baseline_environment_keys`); `crates/eggwork-runner/tests/windows_process_tree.rs` (`baseline_keys()`) | Executed: `cargo test -p eggwork-runner --test environment_policy` → `the_installed_baseline_is_the_policy_baseline` passed. **The Windows half is code-inspected only** — see §9 finding S-02 | Pass (Linux) / partially inspected (Windows) | +| 8 | A caller-supplied reserved key no longer produces a duplicate launch-specification key, and no longer causes a best-effort execution to lose its confinement | `build_child_environment`; `SandboxChannel::new` uses the same builder | Executed: runner-side `the_launch_specification_carries_one_entry_per_node_owned_key` and `the_direct_path_and_the_launch_specification_agree` (25-test lib suite passed); helper-side `a_caller_supplied_node_owned_key_keeps_the_execution_confined` (12-test suite passed) asserts `SandboxOutcome::Applied` and exactly one `LANG=C.UTF-8` in the child's environment | Pass | +| 9 | The direct path and the helper path agree on every reserved key's value | `build_child_environment` is the single builder | Executed: `the_direct_path_and_the_helper_path_agree_about_the_environment` (12-test suite passed) compares the two children's actual environments, key by key, including every `RESERVED_KEYS` entry | Pass | +| 10 | The environment-policy refusal has a status byte distinct from the general specification-validation status, and the runner classifies it as a setup failure before the target | `crates/eggwork-sandbox-helper/src/main.rs` (`read_spec` → 13); `classify_helper_status` in `crates/eggwork-runner/src/lib.rs` | Executed: helper-side `a_duplicate_environment_key_is_refused_with_the_environment_policy_status` (13) and `a_malformed_specification_keeps_the_general_validation_status` (12) both passed; runner-side `the_helper_status_bytes_classify_a_refusal_before_the_target` passed | Pass | +| 11 | A required request still fails closed before the target process starts | unchanged; `Required` still fails closed | Executed: `cargo test -p eggwork-sandbox-helper --test landlock_runner` → 17 passed, including `helper_trust_checks_reject_missing_wrong_and_symlinked_helpers` (required request → error, marker never created) and `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` | Pass | +| 12 | The helper's five duplicated protocol limit constants agree with `eggwork-core`, by generation or by an explicit comparison test | generated into `crates/eggwork-sandbox-helper/src/environment_policy.rs` from `crates/eggwork-core/src/lib.rs` | Executed: `the_helper_limit_constants_match_eggwork_core` (12-test suite passed) | Pass | +| 13 | The denied-key entry set is unchanged from the reviewed baseline, and the closure record lists it | `crates/eggwork-runner/policy/environment-policy.toml` `[denied]` | Executed: `python3 scripts/generate_environment_policy.py --check` passes against the checked-in copies; the entry set is listed in §6. Inspected: the 21 entries are byte-identical to the pre-corrective list in both crates | Pass | +| 14 | No wire representation changed | the launch specification's *shape* is unchanged; only its `environment` array's content is now policy-conformant | Inspected: `SandboxLaunchSpec`'s fields and `LaunchSpec`'s fields are unchanged; `ExecutionEventKind`, `ExecutionResult`, `SandboxResult`, `ResourceResult` untouched. **The helper's status byte 13 is a process-level protocol change** — see §5 and §9 finding S-03 | Pass (with the status-byte note) | +| 15 | `architecture/sandbox-helper.md` and `architecture/runner-execution.md` match the code | both edited | Inspected: the status table lists every byte the helper writes, the environment-policy section states the one owner, the drop-versus-reject contract, the `PATH` contract and its Linux scope, the node-owned baseline and the generated-file convention; the runner document describes the denied-key drop, the reserved-key rule, the baseline and the launch-specification environment | Pass | +| 16 | The full pre-submit gate is green on the reviewed head | — | **Not claimed.** The scoped gate was run (§9); the full workspace gate is the coordinator's to run once at the end, as the milestone instructions require | Open (coordinator) | + +## 8. Negative and adversarial evidence + +### 8.1 A one-sided edit to the **runner's** copy fails the build + +Editing `crates/eggwork-runner/src/environment_policy.rs` alone — the first +denied entry `LD_` → `LD_ONE_SIDED` — and running +`cargo test -p eggwork-sandbox-helper --test environment_policy_parity`: + +```text +---- the_denied_key_list_is_the_same_list_in_the_same_order stdout ---- +assertion `left == right` failed: denied-key entry 0 differs: the runner's copy +has "LD_ONE_SIDED" and the helper's has "LD_". A mismatch is a contract change, +not a test to be adjusted + +---- linux::the_helper_refuses_exactly_what_the_runner_drops stdout ---- +assertion `left == right` failed: the runner's policy and the probe table +disagree about LD_PRELOAD="/tmp/evil.so"; one of them is wrong about the contract + +---- linux::a_caller_supplied_node_owned_key_keeps_the_execution_confined stdout ---- +the execution runs: Setup("sandbox helper rejected its launch specification (status 13)") + +---- linux::the_direct_path_and_the_helper_path_agree_about_the_environment stdout ---- +the confined execution runs: Setup("sandbox helper rejected its launch specification (status 13)") + +test result: FAILED. 8 passed; 4 failed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +Four tests failed. The element-wise test named the first differing entry; the +behavioural test caught the *rule* divergence independently — and note what the +third and fourth failures show: with the runner's copy no longer denying +`LD_PRELOAD`, the runner's specification carries it and the helper refuses +the launch. That is the divergence doing real damage, which is why the +behavioural half of the gate matters. + +### 8.2 A one-sided edit to the **helper's** copy fails the build + +Editing `crates/eggwork-sandbox-helper/src/environment_policy.rs` alone — the +same change — and running the same command: + +```text +---- the_denied_key_list_is_the_same_list_in_the_same_order stdout ---- +assertion `left == right` failed: denied-key entry 0 differs: the runner's copy +has "LD_" and the helper's has "LD_ONE_SIDED". A mismatch is a contract change, +not a test to be adjusted + +---- linux::the_helper_refuses_exactly_what_the_runner_drops stdout ---- +assertion `left == right` failed: the helper must refuse LD_PRELOAD="/tmp/evil.so" +with the environment-policy status + left: 1 + right: 13 + +test result: FAILED. 10 passed; 2 failed; 0 failed; 0 ignored; 0 measured; 0 filtered out +``` + +Both edits were reverted, and `python3 scripts/generate_environment_policy.py +--check` then reported "the environment-policy copies are up to date" and the +suite was green again (12 passed). + +### 8.3 The behavioural parity sweep over the probe corpus + +`the_helper_refuses_exactly_what_the_runner_drops` drives the **real** helper +executable with a launch specification for each of 37 probe entries and +compares three things: the probe table's stated expectation, what the +runner's copy of the policy says, and what the helper actually does. The +corpus has 40 entries and covers every denied entry (exact names, a prefix, +and a lower-case spelling), every node-owned key with the caller's value, +every node-owned key with the node's value, `PATH` with and without the contract +value, a lower-case spelling of a node-owned key, and two caller-controlled +keys. + +This is the behavioural half of the gate. It is not a structural comparison of +two files: it measures what the helper *enforces*. + +### 8.4 The baseline-key collision + +The regression for the live defect is +`a_caller_supplied_node_owned_key_keeps_the_execution_confined`. It drives the +real runner with the real helper and a request that sets `LANG`, +`LC_ALL`, `CI`, `TERM`, `PAGER`, `NO_COLOR`, `GIT_TERMINAL_PROMPT`, `PATH` +and `LD_PRELOAD` to caller values, and asserts: + +- the sandbox outcome is `SandboxOutcome::Applied` — **not** `NotApplied`; +- the child saw exactly one `LANG`, and it was `LANG=C.UTF-8`; +- the caller's `en_US.UTF-8` appears nowhere in the child's environment. + +Before this milestone the same request produced a specification with two +`LANG` entries, the helper refused it with status 12, and a best-effort +request answered that refusal by re-spawning the target with no Landlock +ruleset — a successful, entirely unconfined execution. The `Required` variant +of the same request fails closed instead, which is the unchanged `Required` +behaviour. + +The specification-side half of the same proof is the runner-side unit test +`the_launch_specification_carries_one_entry_per_node_owned_key`, which reads +the specification the runner actually wrote and asserts one entry per +node-owned key, carrying the node's value. + +### 8.5 The generator refuses a malformed source of truth + +`test_a_malformed_source_of_truth_fails_without_writing_anything` corrupts +the policy in a temporary tree (malformed TOML; an unknown schema version) and +asserts the generator exits non-zero **and** writes neither copy. A generator +that wrote half a policy and exited zero would be worse than one that +refuses. `test_a_policy_whose_class_and_baseline_disagree_fails` corrupts the +node-owned class and asserts the generator refuses it with the message about +the node-owned class. + +### 8.6 The ownership guard + +`python3 scripts/check_execution_ownership.py` → "execution ownership guard +passed; approved process owners: eggwork-runner (2 spawn sites), +eggwork-sandbox-helper (1 spawn sites)" and "negative scanner self-test +passed; crate dependency direction passed". +`python3 scripts/check_execution_ownership.py --prove-negative-exit` → passed. +The two generated Rust files live under `crates/*/src/`, so they are scanned by +the guard; they contain no process-creation API. + +## 9. Verification actually run + +Executed in this working tree, with +`CARGO_TARGET_DIR=/home/sugarwookie/projects/eggwork/target-w2a`: + +| Command | Result | +| --- | --- | +| `cargo test -p eggwork-runner --lib` | **passed** — 25 passed, 0 failed, 1 ignored | +| `cargo test -p eggwork-runner --test environment_policy` | **passed** — 5 passed, 0 failed | +| `cargo test -p eggwork-runner --test capability_probe` (pre-existing, unmodified) | **passed** — 2 passed, 0 failed | +| `cargo test -p eggwork-sandbox-helper --lib` | **error** — "no library targets found in package `eggwork-sandbox-helper`". The crate has a `[[bin]]` target only and no `[lib]`; this is pre-existing and not changed by this milestone. The helper has no library to unit-test. | +| `cargo test -p eggwork-sandbox-helper --test landlock_runner` | **passed** — 17 passed, 0 failed | +| `cargo test -p eggwork-sandbox-helper --test environment_policy_parity` | **passed** — 12 passed, 0 failed | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release -p 'test_environment_policy.py'` | **passed** — 5 passed, 0 failed | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` (whole release-harness suite) | **passed** — 57 tests, OK (2 skipped) | +| `cargo fmt -p eggwork-runner -p eggwork-sandbox-helper -- --check` | **passed** — no diff | +| `cargo clippy -p eggwork-runner -p eggwork-sandbox-helper --all-targets -- -D warnings` | **passed** — no warnings | +| `python3 scripts/check_execution_ownership.py` | **passed** | +| `python3 scripts/check_execution_ownership.py --prove-negative-exit` | **passed** | +| `python3 scripts/generate_environment_policy.py --check` | **passed** — "the environment-policy copies are up to date" | +| `cargo build -p eggwork-sandbox-helper` | **passed** | +| `cargo check -p eggwork-server` | **passed** — the server crate still compiles against the changed runner | +| `git diff --check` | **passed** — no whitespace errors | + +**Not run here, and therefore not claimed:** `cargo test --workspace`, +`cargo fmt --all`, `cargo clippy --workspace`, and the full pre-submit gate. +The milestone instructions assign the full gate to the coordinator, who runs it +once at the end; acceptance criterion 16 stays open until then. + +**Cross-target checks were not attempted.** Only the Linux toolchain is +installed here. + +## 10. Platform matrix actually exercised + +| Platform | Evidence | Claim | +| --- | --- | --- | +| Linux x86_64 (`6.8.0-147-generic`, rustc 1.89.0) | The suites in §9 were executed on this host. The behavioural parity sweep drove the **real** helper binary with Landlock enforcement available, and the end-to-end regression drove the real runner with a trusted helper staged from the Cargo build output. | The environment policy, the reserved-key rule, the `PATH` contract, the two generated copies and the status byte are qualified on this host class. | +| macOS | No macOS host and no cross-compilation in this environment. Code inspection only: the runner's Unix baseline is the policy's `BASELINE` on every non-Windows target, and the helper has no macOS path at all (`#[cfg(target_os = "linux")] mod linux`), so the helper's behaviour cannot differ on macOS. | **Not qualified.** No claim is made beyond "the runner's Unix baseline is a single generated constant". The pre-existing macOS clippy failure in `crates/eggwork-runner/src/process_tree.rs` (recorded as S-06, and *not* this milestone's to fix) also means the macOS cross-target clippy check could not have been used as evidence here. | +| Windows | No Windows host and no cross-compilation in this environment. The Windows branch (`platform_baseline`) is code-inspected only: it reads `BASELINE_COMMON` from the shared policy and adds `SystemRoot`, `windir` and the Windows `PATH` from the parent process. The Windows tree suite's `BASELINE_KEYS` was replaced by a call to the runner's own `baseline_environment_keys()`, but the file is `#![cfg(windows)]` and **was not compiled or run here**. | **Not qualified.** Compilation is not qualification. The Windows row stays open until the `windows-runner` CI job runs the suite green — see §9 finding S-02. | + +**No platform is claimed as qualified merely because its code compiles.** + +## 11. Public-API change and its release-visibility consequence + +Two additions to `eggwork-runner`'s public API, both additive: + +| Item | Signature | +| --- | --- | +| `eggwork_runner::environment_policy` | a new public module, exposing the ten items in §3 | +| `eggwork_runner::baseline_environment_keys` | `pub fn baseline_environment_keys() -> Vec<&'static str>` | + +Nothing was removed and no existing public item changed shape or semantics. +The runner's private `denied_environment_key` function was **replaced** by +`environment_policy::denied_environment_key`; it was private, so this is not a +public change. + +**Release-visibility consequence.** The new public module and the new public +function are additive API in a published crate (`eggwork-runner` 0.1.5). They +do not break a downstream consumer, but they are new public surface and should +be mentioned in the release notes. The milestone's ownership does not include +any `Cargo.toml`, so **the version bump was not made** — see §9 finding S-03. + +**A process-level protocol change.** The helper's status byte 13 is new and +the root-canonicalization byte moved from 13 to 17. The runner and the helper +ship in the same release bundle ("Linux releases ship the daemon and its +Landlock sandbox helper as one bundle from one source revision, so the pair +can never drift"), so a runner that understands 13 and 17 must never meet a +helper that writes the old 13. The bundle rule already guarantees this, but +the change is worth a line in the release notes: see §9 finding S-03. + +## 12. Documentation status + +| Document | Change | +| --- | --- | +| `architecture/sandbox-helper.md` | The "Environment handling" section was rewritten: one owner and two generated copies, the drop-versus-reject contract table, the node-owned baseline and the collision hole it closes, the `PATH` contract and its Linux scope, and the surviving environment. A full status-byte table was added, including the new byte 13 and the moved byte 17. The "Platform support", "Test coverage", "Invariants and enforcement" and "Review focus" sections were updated. **Every stale line-number citation in this file was replaced with a symbol reference in the same pass** — the file now contains no `file.rs:NNN` citation. | +| `architecture/runner-execution.md` | "Environment clearing and the conservative baseline" was rewritten: the single builder, the three classes, the reserved-key rule and the collision hole, the `PATH` contract and its Linux scope, and the provenance entries. The `TrustedLandlockSetup` section, the responsibility boundary, the invariants table and the test-coverage section were updated, and the "Env baseline duplication" review-focus bullet was rewritten to say what the fix does and does not do. | +| `architecture/overview.md` | **Not edited — the coordinator owns it.** See §13 for the recommendation. | +| `architecture/data-plane.md` | **Not edited — the coordinator owns it.** See §13. | +| `AGENTS.md` | **Not edited — the coordinator owns it.** See §13 for the recommended wording of the "Isolation claims are earned" line. | +| `plans/subsystems/security-isolation-resource-roadmap.md` | The M005b entry's status was set to "implemented — closure record written, implementation commit pending" and the closure-evidence pointer was added, matching the M005a entry's shape. The roadmap's status line was updated to "closed through M004 (remote-admission C001 and Operations M002 included); M005a and M005b implemented (closure records written, implementation commits pending); M005c blocked on ADR-0007". | +| `plans/registry.md` | **Not edited — the coordinator owns it.** See §14. | +| `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md` | **Not edited** — the plan is not in this milestone's ownership and is left as the authoritative statement of what was asked. | + +New text in the deep dives uses symbol references rather than line numbers, so +it does not add to the repository's stale-line-number defect. + +## 13. Unresolved findings, ranked by severity + +**Critical: none. High: none.** + +- **S-01 — Medium — owner: the coordinator (`architecture/overview.md`, + `architecture/data-plane.md`, `AGENTS.md`, `plans/registry.md`).** Those four + files are outside this milestone's ownership and were not edited. The + recommended text is in §14. +- **S-02 — Medium — owner: the release owner / CI owner.** The Windows half of + this milestone is **code-inspected only**. `crates/eggwork-runner/src/lib.rs`'s + Windows branch (`platform_baseline`) and the rewritten + `crates/eggwork-runner/tests/windows_process_tree.rs` (`baseline_keys()`) + were neither compiled nor run here — the suite is `#![cfg(windows)]` and + there is no Windows toolchain in this environment. The `windows-runner` CI + job's `cargo test -p eggwork-runner --all-targets` is what will exercise it. + Until that runs, the Windows row of §10 stays "not qualified". +- **S-03 — Medium — owner: the coordinator / release owner.** Two + release-visible items: the new public `eggwork_runner::environment_policy` + module and `baseline_environment_keys`, and the helper's status-byte change + (new byte 13; root-canonicalization moved from 13 to 17). No `Cargo.toml` is + in this milestone's ownership, so the version bump was not made, and the + status-byte change needs a release-note line. The daemon and the helper ship + as one bundle, so a mixed pair cannot reach an operator — but the note is + still owed. +- **S-04 — Low — owner: the foundation/runner owner (NOT this milestone).** + A repeated environment key is now collapsed to its last value by the + environment builder rather than refused. Rejecting duplicate keys outright + is a *request-validation* decision and belongs to the foundation + runner-request-validation corrective, which the plan lists as out of scope. + Until then, the builder's collapsing is what keeps the specification free of + duplicates. The builder's collapsing also matches what `Command::env` + already did on the direct path, so the two paths agree. +- **S-05 — Low — owner: the security-isolation subsystem owner.** The + node-owned class is platform-shaped, and the shared policy defines the Unix + class only. On the Windows baseline the node owns `SystemRoot`, `windir` and + `PATH` instead of the Unix locale keys, and the Windows branch is + runner-local. That is stated in the policy file and in both deep dives, but + it means a reader who takes `RESERVED_KEYS` as platform-neutral would be + wrong on Windows. The policy file says so explicitly. +- **S-06 — Low — owner: the foundation/runner owner (NOT this milestone).** + `crates/eggwork-runner/src/process_tree.rs`'s `ProcessTree::start_kill` is + called only from the Linux-only helper-handshake paths, so on macOS it is + dead code and `cargo clippy --target x86_64-apple-darwin -- -D warnings` + fails. This is **pre-existing at the reviewed head `6f41957`** and + `process_tree.rs` is not in this milestone's ownership, so it was not + touched. It is recorded because it blocks the macOS cross-target clippy + check that §10's platform matrix would otherwise use. +- **S-07 — Low — owner: the security-isolation subsystem owner.** The + deny-list is still a *closed* list. The duplication is gone, so the list is + now written once — but a new interpreter or loader knob (`PERL5LIB`, + `RUBYLIB`, `NODE_PATH`, `GLIBC_TUNABLES`, `PROMPT_COMMAND`) is not covered, + and adding one is a policy decision with its own security review. Removing + the duplication did not make the list exhaustive. + +## 14. Coordinator-owned text + +**`architecture/overview.md` — recommendation: no divergence row.** The +duplication this milestone set out to close is closed: the policy has one +owner, the two copies are generated and pinned by a behavioural parity test, +the reserved-key collision is closed, and the two launch paths agree. The +plan's §10 says to add a row "only if a residual divergence remains after +M005b. If the duplication is closed, do not add a row", and it is closed. If +the coordinator wants the status-byte change visible from the bird's-eye view +anyway, the exact text would be: + +```markdown +| 7 | The helper's environment-policy refusal has its own status byte | `crates/eggwork-sandbox-helper/src/main.rs` (`linux::read_spec`, `linux::environment_policy_refuses`) | `architecture/sandbox-helper.md` § "The status-byte table"; byte 13 is the environment-policy refusal and byte 17 is the root-canonicalization failure | +``` + +It must not touch the existing rows. + +**`architecture/data-plane.md` — recommendation: no change.** Nothing in the +data plane — blobs, workspaces, artifacts, GC — is touched by this milestone, +and no wire representation changed. The one adjacent fact, that the launch +specification's `environment` array is now policy-conformant by construction, +belongs in `architecture/sandbox-helper.md` and `architecture/runner-execution.md`, +where it is stated. No row or paragraph is warranted. + +**`AGENTS.md` — recommendation: extend one hard-invariant line.** The +"Isoolation claims are earned" line does not need a new entry, but it can name +the environment policy's single owner, in the same style and keeping it true: + +```markdown +4. **Isolation claims are earned.** Advertise filesystem isolation only when `verify_trusted_helper` accepts the installed helper; the same function backs capability advertisement, `doctor`, and admission. The node's environment policy has one owner — `crates/eggwork-runner/policy/environment-policy.toml` — generated into each crate and pinned by a parity test, so the runner and the sandbox helper cannot enforce different rules. +``` + +The alternative — leaving the line untouched — is also defensible; the +invariant is not weakened by this milestone either way. + +**`plans/registry.md` — recommendation: register M005b as implemented.** The +registry is the coordinator's file and was not edited. The coordinator's action +is to point M005b at +`plans/closure/security-isolation-resource/005b-status.md`, mark it +implemented, and fill `IMPLEMENTATION-COMMIT-PENDING` in this record and in +the roadmap entry with the real commit SHA. + +## 15. Registry and roadmap disposition + +- `plans/subsystems/security-isolation-resource-roadmap.md`: M005b — + `proposed` → **implemented** (closure record written, implementation commit + pending). The status line was updated to match. The milestone's exit + conditions were **not** rewritten: each one is now satisfied by a named + implementation site and a named test, as §7 maps them. The objective text + was left as written, because the defect it describes is what the milestone + set out to close and the closure record says it is closed. +- `plans/registry.md`: **not edited** — the registry is the coordinator's + file. See §14. +- `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`: + **not edited** — the plan is not in this milestone's ownership and is left + as the authoritative statement of what was asked. + +## 16. What this milestone did not do + +- It did not change the **content** of the denied-key list. The 21 entries + were carried over unchanged, including the redundant `GIT_CONFIG_`. +- It did not add a workspace-crate dependency to the helper, add a `build.rs`, + or make either crate read a file outside its own directory at build time. +- It did not unify the drop-versus-reject behaviour. The runner still drops a + denied key silently and the helper still refuses the launch; only the list + is shared. +- It did not change the `Required` path, the wire representation, the + authentication, authorization, lease, generation, fencing or digest bounds, + the release version, or any `Cargo.toml`. +- It did not add node selection, a queue, priority, fairness, a DAG, or + semantic retry. +- It did not run the full workspace gate, cross-compile, or touch the + coordinator-owned files listed in §14. diff --git a/plans/closure/workspace-artifact-transport/005b-status.md b/plans/closure/workspace-artifact-transport/005b-status.md new file mode 100644 index 0000000..8820a9a --- /dev/null +++ b/plans/closure/workspace-artifact-transport/005b-status.md @@ -0,0 +1,266 @@ +# Workspace and Artifact Transport M005b Closure — GC Preview and Store Ownership Corrective + +Source plan: `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md` +Corrective addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` +Subsystem roadmap: `plans/subsystems/workspace-artifact-transport-roadmap.md` +Reviewed head at the start of the milestone: `6f41957` (`feat(security): M005a degraded isolation observability`) +Head when the milestone work was finished: `a8abfcb` (`docs(plans): record the core protocol-contract ownership change as ADR-0008`) — a coordinator-owned documentation commit that does not touch any file in this milestone's change set. +Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` +Closure record commit: `IMPLEMENTATION-COMMIT-PENDING` + +## Finding + +The operator's GC dry-run preview and the apply pass used **different candidate predicates**, in a module whose own doc comment states that the two must be shared. The owner module (`blob.rs`) already said so: *"Shared by the dry run and the real run on purpose... Two hand-copied copies of it are what let the two paths drift apart."* The rule was violated in the sibling module: `operations.rs` carried a hand-copied preview query that selected on `blobs.reference_count = 0` while the collector selected on the absence of a reference row. The counter is a denormalization maintained only by the `blob_reference_insert` / `blob_reference_delete` triggers, so it can drift from the rows that actually pin bytes; the preview could therefore report a candidate the apply pass would not remove, and miss one it would. + +Three further ownership defects sat alongside it. The blob store's path layout was re-derived in the operator (`config.blob_root.join(&digest.as_str()[..2]).join(digest.as_str())`) instead of being taken from the store. The three store metadata file names were spelled in the operator and in `lib.rs`. And the `"{principal}:{manifest_digest}"` composite was written in three places, with one call site reached precisely when the stored principal does not parse as a `PrincipalId`. + +A fourth defect was found while reading the cited sites: `materialize_tree` accepted blob bytes on a **size-only** check. A blob whose length matched the manifest but whose content did not match its digest was copied into the workspace tree. + +The milestone closes all four. The candidate predicate now lives in the owner modules and is the only place it is written; the operator's preview obtains its candidate sets through that owner code and contains no SQL of its own; the preview reaches the owner through a non-mutating seam, because every owner `open` creates and reconciles; the blob layout and the metadata file names have one owner each; the manifest owner id has one producer; and the materializer verifies the bytes it writes while it copies them. + +**Scope note.** This record is written from the implementing agent's working tree, with the milestone's code **not yet committed**. The implementation commit is a placeholder for the coordinator to fill in. + +## What was inspected by reading, and what was executed + +Everything in the "Implementation site" column below was established by reading the cited source at the reviewed head. Everything in the "Test" column was **executed** on the host described in [Platform and feature matrix actually exercised](#platform-and-feature-matrix-actually-exercised), with the exact commands and outcomes in [Verification actually run](#verification-actually-run). + +Two claims in the plan's section 13 could not be satisfied as written and are recorded honestly in [Unresolved findings](#unresolved-findings-by-severity): + +1. The corrupt-principal owner-id case **does not fail against the pre-fix code** — it was verified experimentally. The pre-fix inline format produced the identical composite, so the pre-fix code released the reference correctly. The defect was the *duplication* of the format, not a wrong release. +2. The workspace-wide gate required by acceptance criterion 13 (`cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` and `cargo test --locked --workspace --all-targets`) was **not run by this milestone**. The coordinator reserved the full gate for the end of the batch, and a second agent is concurrently editing the runner and the sandbox helper in the same tree. The scoped equivalents are recorded instead. + +## Requirement-to-evidence matrix + +One row per acceptance criterion in the plan's section 11. + +| # | Acceptance criterion | Implementation site | Test | +|---|---|---|---| +| 1 | The dry-run report and the apply pass select candidates through the same store-owned statement; the operator module contains no candidate predicate of its own. | `blob.rs`: `UNREFERENCED_CANDIDATES_SQL`, `BlobStore::unreferenced_candidates`, `blob::preview_gc`. `workspace.rs`: `WORKSPACE_CANDIDATES_SQL`, `MANIFEST_CANDIDATES_SQL`, `workspace_candidates`, `manifest_candidates`, `workspace::preview_gc`. `artifact.rs`: `ARTIFACT_CANDIDATES_SQL`, `artifact_candidates`, `artifact::preview_gc`. `operations.rs`: `dry_run_gc` now calls only those owner entry points and holds no SQL. | `operations.rs`: `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter`. `tests/gc_preview_parity.rs`: `the_operator_module_contains_no_candidate_predicate_of_its_own`, `the_operator_preview_spells_no_sql_and_opens_no_store`. | +| 2 | The blob candidate predicate is the reference-row predicate, not the `reference_count` counter. | `blob.rs`: `UNREFERENCED_CANDIDATES_SQL` is `WHERE NOT EXISTS (SELECT 1 FROM blob_references r WHERE r.digest = blobs.digest)`. The counter appears nowhere in any reclamation query. | `operations.rs`: `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` (a blob with a live reference row and a counter of zero is not a candidate; a blob with no reference rows and a counter of one is). Non-vacuity shown below. | +| 3 | The rule recorded on the doc comment of `BlobStore::unreferenced_candidates` is enforced by a test rather than stated only in a comment. | The doc comment was extended to name the third reader (the operator's preview) and to point at `preview_gc`. The function now takes a `&Connection` so the preview can evaluate it without a store instance. | `operations.rs`: `gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes` and `gc_preview_and_apply_agree_when_the_store_has_no_expired_references` assert the relation the comment states. | +| 4 | The preview remains non-mutating, proven on a store that does not yet exist. | `blob::preview_gc`, `workspace::preview_gc`, `artifact::preview_gc` open the metadata database with `SQLITE_OPEN_READ_ONLY`; they never call `BlobStore::open`, `WorkspaceManager::open` or `ArtifactStore::open`, each of which creates and reconciles. | `operations.rs`: `gc_preview_does_not_create_a_store_that_does_not_exist`. | +| 5 | A test proves the preview's candidate set is a subset of the apply pass's removed set, and is equal to it for the same inputs when the store contains no expired references. | The preview evaluates the candidate statement before the expired references are deleted; the apply pass evaluates it after. That difference is the reason the relation is a subset and not bare equality. | `operations.rs`: `gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes` (subset) and `gc_preview_and_apply_agree_when_the_store_has_no_expired_references` (equality). | +| 6 | `inspect_blob` resolves object paths through the store's path ownership, and its symlink and size-cross-check properties are preserved. | `blob.rs`: `blob::shard_path`, `blob::object_path` (pure, `(root, digest) -> PathBuf`); `BlobStore::path_for` delegates to `object_path`. `operations.rs`: `inspect_blob` uses `blob::shard_path` and `blob::object_path` and spells no layout of its own. | `operations.rs`: `inspect_blob_resolves_the_object_through_the_store_path_ownership` (resolves in a real store; a recorded size that disagrees with the file's length is `OperationsError::Data`), `inspect_blob_refuses_a_symlinked_shard_or_object` (unix: symlinked shard directory and symlinked object file are both refused). `tests/gc_preview_parity.rs`: `the_operator_module_contains_no_candidate_predicate_of_its_own` forbids `as_str()[..2]` in the operator. | +| 7 | The workspace materializer refuses blob content that does not match the manifest digest, even when the length matches, and the refusal is proven non-vacuous. | `blob.rs`: `BlobStore::copy_verified` hashes the byte stream it forwards and returns `BlobError::DigestMismatch`; `VerifyWriter` in `blob.rs` is the hashing writer. `workspace.rs`: `materialize_tree` uses `copy_verified`, maps a digest mismatch to `WorkspaceError::InvalidBlob`, and removes the staged file so unverified bytes do not survive. | `workspace.rs`: `materialize_tree_refuses_blob_bytes_that_do_not_match_the_manifest_digest` — the stored object is corrupted **in place, keeping its length**, and the materializer refuses it; the same test asserts correct bytes still materialize. Non-vacuity shown below. | +| 8 | The manifest owner-id composite has exactly one producer; both inlined call sites use it; the `&PrincipalId` versus `&str` mismatch is resolved by an explicit decision; and a corrupt-row case still releases its reference. | `workspace.rs`: `manifest_owner_id_for_key(principal_key: &str, manifest_digest: &str)` is the single implementation of the format; `manifest_owner_id(principal_id: &PrincipalId, manifest_digest: &str)` is the validated-principal entry point and delegates to it. Both former inline call sites (`manifest_garbage_collect` and the `reconcile_manifests` orphan sweep) route through them. The `&PrincipalId` / `&str` mismatch is resolved by validating the row's principal where validation is possible and falling back to the raw key otherwise — both produce the same bytes, so the released owner id is unchanged either way. | `workspace.rs`: `manifest_owner_id_has_one_producer_for_validated_and_string_principals` (the two entry points agree, including for a principal that itself contains a colon); `manifest_gc_releases_the_reference_for_an_unparseable_stored_principal` (a stored principal that does not parse still has its blob pin released). `tests/gc_preview_parity.rs` enforces that the operator holds no copy of a store's knowledge. See [Unresolved findings](#unresolved-findings-by-severity) for the honest non-vacuity status of the corrupt-principal case. | +| 9 | No public protocol surface changed: no route, request, response, capability string, `NodeGcReport` field, or `ResourceInspection` field. | `NodeGcReport` (`lib.rs`) keeps the same thirteen fields, names, types and order. `ResourceInspection` (`operations.rs`) keeps the same three fields, and the `metadata` JSON each `inspect` verb emits is unchanged. No route, request struct, response struct or capability string was touched. | Verified by inspection and by the pre-existing suites: `cargo test -p eggwork-server --lib` → 142 passed, 0 failed. `crates/eggwork-server/tests/release_contract.rs` and `installed_qualification.rs` were **not** executed by this milestone (see [Verification actually run](#verification-actually-run)). | +| 10 | No stored format changed: no schema, row, file name, shard layout, or composite format. | No `CREATE TABLE` statement changed in `blob.rs`, `workspace.rs` or `artifact.rs`. The blob shard layout is still `//<64 hex>`; `blob::object_path` computes the same path the old inline expression computed. The metadata file names are unchanged. The composite format is still `"{principal}:{manifest_digest}"`. The manifest digest algorithm and the artifact record format are untouched. | `operations.rs`: `inspect_blob_resolves_the_object_through_the_store_path_ownership` resolves an object at the same path the store writes it to. `workspace.rs`: `manifest_owner_id_has_one_producer_for_validated_and_string_principals` pins the composite's exact bytes. | +| 11 | The GC ordering, the bounded-per-pass semantics, the `clamp(1, 1024)` limit, and the apply pass's exclusive lock are unchanged. | `operations.rs`: `collect_garbage` still runs workspaces → manifests → artifacts → blobs, still clamps to `1..=MAX_GC_BATCH` (1024), and still takes the exclusive maintenance lock before applying. `lib.rs`: `NodeServer::collect_garbage` is unchanged apart from the artifact database path now coming from `artifact::metadata_path`. | `operations.rs`: `applying_gc_refuses_to_race_a_running_node` (the exclusive lock still refuses to race a running node) — passed as part of the 142-test lib run. `garbage_collection_preview_reads_only_and_reports_bounds` shows the preview's bound is honoured (one candidate at `limit = 1`, the full census at `limit = 8`). | +| 12 | No bound is widened; no authentication, lease, generation, fencing, or digest-bound semantics weakened; no queue, worker selection, priority, fairness, DAG, or semantic retry introduced. | No quota, size bound, entry-count bound, or retention horizon was changed. No authentication, authorization, lease, generation or fencing code was touched. No scheduler-like concept was introduced. The only new bounds are the *existing* `limit` applied to the preview's owner queries, which the preview already applied. | `scripts/check_execution_ownership.py` passed (no process creation added to `eggwork-server`). The pre-existing authorization, lease and fencing tests are part of the 142-test lib run and passed unchanged. | +| 13 | `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` and `cargo test --locked --workspace --all-targets` are green on the same head. | **Not satisfied by this record.** The workspace-wide gate was not run here; the coordinator reserved it for the end of the batch, and a second agent is concurrently editing `crates/eggwork-runner/**` and `crates/eggwork-sandbox-helper/**` in the same tree. The scoped equivalents are recorded in [Verification actually run](#verification-actually-run). | Pending the coordinator's full gate. | + +## Decisions taken where the plan left the choice open + +### The non-mutating preview seam + +The plan offered three options: a read-only non-reconciling open; public side-effect-free candidate-query entry points on the owner modules; or a store-owned pure function. + +**Chosen: public, side-effect-free candidate-query entry points on the owner modules** — `blob::preview_gc`, `workspace::preview_gc` and `artifact::preview_gc` — each of which opens the store's metadata database `SQLITE_OPEN_READ_ONLY` and evaluates the owner's own canonical statement. + +Why this and not the alternatives: + +- A *read-only non-reconciling open* would still have to skip `remove_stale_parts` and `reconcile`, which means a second `open` variant that differs from the one the collector uses. That is the same duplication the milestone is removing, one level up: the collector and the preview would then use different `open`s, and a future change to the reconciliation would have to be made in both. +- A *store-owned pure function* over the store's in-memory state requires a store instance, and every way of obtaining one — `BlobStore::open`, `WorkspaceManager::open`, `ArtifactStore::open` — creates and reconciles. The pure-function option is therefore only reachable through a non-mutating open, which is the first option. +- The chosen shape keeps the *statement* in the owner module, which is the property that actually matters: the preview and the collector evaluate the same SQL text, so they cannot answer different questions even if the surrounding plumbing changes. + +The seam's cost is stated plainly: the preview reads the metadata database **directly** rather than through a store instance, so it sees the store's rows and not the store's in-memory reconciliation. For a preview that is the correct trade — the reconciliation is precisely what the preview must not perform. + +The seam also preserves two behaviours that were already true and are now enforced rather than incidental: a preview against a store that does not exist **fails with a typed error** (`OperationsError::Data`, surfaced as the generic "bounded garbage collection failed") rather than degrading to zero candidates; and a store that predates the retained-manifest cache reports zero manifest candidates instead of failing the whole preview. + +### Verify-while-copying, not verify-then-copy + +**Chosen: verify-while-copying.** `BlobStore::copy_verified` hashes the byte stream it forwards into the staging file and compares the result with the manifest's digest. A verify-then-copy implementation would have hashed the object file, closed it, reopened it and copied it — a third read, and a window in which the object can change between the hash and the copy. + +The performance consequence, stated precisely, because `architecture/data-plane.md` records that *"blob download and workspace materialization both pay a full re-hash of every input"*: + +| | Reads of the object file | SHA-256 passes over the input | +|---|---|---| +| Before the change | 2 — one for the pre-flight `verify_existing`, one for the copy | 1 — the pre-flight re-hash | +| After the change (verify-while-copying) | 2 — unchanged | 2 — the pre-flight re-hash, plus one over the copied bytes | +| Verify-then-copy would have been | 3 — a third read of every object file | 3 | + +So the change adds **one SHA-256 computation over the copied bytes per materialized file** and **no additional read** of the object and no additional bytes moved. The recorded property is unchanged: materialization still pays a full re-hash of every input, and that re-hash is now bound to the bytes that actually reach the tree rather than to a separate earlier read. The cost is CPU, not I/O. + +### The manifest owner-id producer shape + +**Chosen:** one implementation of the format, `manifest_owner_id_for_key(principal_key: &str, manifest_digest: &str)`, with two entry points — `manifest_owner_id(principal_id: &PrincipalId, manifest_digest: &str)` (validated principal, delegating to the raw form) and the raw form itself. + +The `&PrincipalId` / `&str` mismatch is resolved explicitly rather than assumed away. Two call sites read the principal out of a SQL row, where it may not parse as a `PrincipalId` — and one of them, the `reconcile_manifests` orphan sweep, is reached *precisely* when the principal does not parse. Refusing to release the reference in that case would leak the pin: the blob would stay unreclaimable for ever. So the raw form is the fallback, and the validated form delegates to it. Because `PrincipalId::as_str()` returns the principal unchanged, both entry points produce the same bytes for the same principal, and the choice of entry point never changes which owner id is released. + +The composite is `"{principal}:{manifest_digest}"`. A manifest digest is hex and contains no colon, so the pair is recovered by splitting at the **last** colon even when the principal itself contains one — `PrincipalId` permits `:` in a principal. + +## The non-mutating-preview evidence + +`gc_preview_does_not_create_a_store_that_does_not_exist` (`operations.rs`) points the preview at a store that does not exist: + +1. It asserts that the blob root, the workspace root, the execution database, and **the database's parent directory** are all absent before the call. +2. It asserts `collect_garbage(config, true, 1)` is an error — the preview cannot evaluate a store that is not there, and it does not degrade to zero candidates. +3. It asserts that after the failed preview, all four paths are **still** absent: the preview created nothing. +4. It then performs `BlobStore::open` — the creating, reconciling open the preview must not use — and asserts that the blob root and its metadata database now exist. This step exists so the assertion in step 3 has teeth: it demonstrates that the creating open really would have brought the store into being. + +The same property is asserted against a store that *does* exist: `garbage_collection_preview_reads_only_and_reports_bounds` writes an in-flight `.part-` upload into the blob root, runs the preview, and asserts the file is still there with its bytes intact. + +## The preview/apply agreement evidence + +The fixture builds the three stores through their owner modules (`BlobStore::open`, `WorkspaceManager::open`, `ArtifactStore::open`), so it is a real store. This replaces the previous fixture, which hand-built a `blobs` table whose columns were `(reference_count, size_bytes, last_used_unix_ms)` — with no `digest` column at all — and was therefore a database shaped to the hand-copied predicate. The canonical statement could not even be evaluated against it. + +### The seeded blob states + +| State | Reference rows | `reference_count` | Under the reference-row predicate | Under the old counter predicate | +|---|---|---|---|---| +| `live` | one live row | 1 | not a candidate | not a candidate | +| `expired` | one expired row | 1 | not a candidate *at preview time*; a candidate after the expired row is swept | not a candidate | +| `unreferenced-a/b/c` | none | 0 | candidate | candidate | +| `counter-low-a/b` | one live row | **0** (drifted) | not a candidate | **candidate** | +| `counter-high` | none | **1** (drifted) | **candidate** | not a candidate | + +The drift is written directly into `blobs.reference_count`. That is not a fabricated reference row: it reproduces the real condition under which the trigger-maintained counter disagrees with the rows that actually pin bytes, which is the whole point of the divergence. + +The fixture is **asymmetric on purpose** — two `counter-low` blobs against one `counter-high`. With a symmetric fixture the two predicates produce the same *count* and differ only in membership, and a count comparison cannot see the difference. With the asymmetry the reference-row predicate yields **4** candidates and the counter predicate yields **5**, so the operator's reported count alone discriminates. + +### The candidate sets and the relation observed + +`gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes` (store contains one expired reference): + +- the owner's canonical statement selects **4** candidates: `unreferenced-a`, `unreferenced-b`, `unreferenced-c`, `counter-high`; +- the apply pass removes **5** objects: those four, plus `expired`; +- every one of the preview's four is in the apply pass's five — **the preview's set is a subset of what the apply pass removes**; +- the difference is exactly `expired`, and the reason is recorded in the owner module's doc comment: the preview selects *before* the expired reference rows are deleted, the apply pass selects *after*, so a blob that has just become unreferenced is collectable in the same pass; +- `live` and `counter-low-a/b` survive the apply pass — they are pinned, exactly as the reference-row predicate says. + +`gc_preview_and_apply_agree_when_the_store_has_no_expired_references` (no expired reference in the store): the preview's set and the apply pass's removed set are **equal** — 4 candidates, 4 removed. This is the equality case the plan asks for, demonstrated separately. + +`gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` closes the loop between the operator and the owner: the operator's reported `blob_candidates` (4) and `blob_candidate_bytes` equal the owner's canonical set exactly, and the membership assertions hold — `counter-low-a/b` are **not** candidates despite their counter saying zero, and `counter-high` **is** a candidate despite its counter saying one. + +## Non-vacuity evidence + +Each new test was made to fail against the pre-fix behaviour by deliberately reintroducing the defect, running the test, and then reverting. Every reversion was verified (the touched file's checksum was compared before and after). + +| Test | Defect deliberately reintroduced | Observed outcome | Reverted | +|---|---|---|---| +| `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` | The owner's statement reverted to `WHERE reference_count = 0` | **FAILED** — "a blob with a live reference row is never a candidate". The subset test failed in the same run ("assertion failed: !removed.contains(&states.counter_low...)"). Run result: 2 passed, 2 failed. | yes | +| `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter`, `gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes`, `gc_preview_and_apply_agree_when_the_store_has_no_expired_references` | The operator's preview given **its own** divergent statement (`WHERE reference_count = 0`) — the original defect's exact shape | **3 FAILED**, 1 passed. The two set tests failed with `left: 5, right: 4` (the operator's count under the divergent predicate against the owner's count). Only `gc_preview_does_not_create_a_store_that_does_not_exist` passed, as expected — that test is about mutation, not selection. | yes | +| `materialize_tree_refuses_blob_bytes_that_do_not_match_the_manifest_digest` | `copy_verified`'s digest check removed, leaving a size-only copy | **FAILED** — the assertion `matches!(materialize_tree(...), Err(WorkspaceError::InvalidBlob))` did not hold: the mismatched bytes were copied into the tree. | yes | +| `the_operator_module_contains_no_candidate_predicate_of_its_own` | *(by inspection of the pre-change file)* `git show HEAD:crates/eggwork-server/src/operations.rs` scanned for the eleven forbidden fragments | **10 of the 11 fragments were present** in the operator's production code: `reference_count = 0`, `expires_unix_ms IS NOT NULL`, `expires_unix_ms <= `, `ORDER BY expires_unix_ms`, `ORDER BY last_used_unix_ms`, `FROM retained_manifests`, `FROM blob_references`, `metadata.sqlite`, `artifacts.sqlite`, `as_str()[..2]`. The eleventh, `NOT EXISTS (SELECT 1 FROM blob_references`, was correctly absent — it is the owner's. | n/a (inspection) | +| `manifest_gc_releases_the_reference_for_an_unparseable_stored_principal` | The pre-fix inline `format!("{principal_id}:{manifest_digest}")` restored in place of the two-entry-point producer | **PASSED** (4 passed, 0 failed across `workspace::tests::manifest*`). **This test does not fail against the pre-fix code**, because the pre-fix inline format produced the identical composite and therefore released the reference correctly. The defect was the *duplication* of the format, not a wrong release. The test guards the refactor — that the new two-entry-point producer did not change the released owner id — and the "exactly one producer" property is enforced by the structural guard instead. Recorded as an unresolved finding. | yes | + +The third row is the §13 requirement "how the digest-mismatch materializer case was shown to fail before the fix", satisfied. The fifth row is the §13 requirement "how the corrupt-principal owner-id case was shown to fail before the fix", which **could not be satisfied as written**; the honest result is recorded above and in [Unresolved findings](#unresolved-findings-by-severity). + +## Verification actually run + +Toolchain: repository-pinned Rust 1.89.0 (`rustc 1.89.0 (29483883e 2025-08-04)`, `cargo 1.89.0 (c24e10642 2025-06-23)`). +Host: Linux x86_64, kernel `6.8.0-147-generic`. +Build isolation: every cargo command ran with `CARGO_TARGET_DIR=/home/sugarwookie/projects/eggwork/target-w2b`, because a second agent is working in the same tree with a different target directory. + +| Command | Result | +|---|---| +| `cargo check -p eggwork-server --lib` | exit 0, no warnings (final run, after the owner modules were wired up) | +| `cargo test -p eggwork-server --lib -- operations::tests` | final run: **22 passed, 0 failed**. Earlier runs in this milestone: a compile error (2 × `into_iter` on `&str`), then 20 passed / 2 failed from two fixture defects (a repeated `record_json` violating the artifacts `UNIQUE` constraint, and an `expired` blob that was seeded without its reference row and so counted as a candidate). Both were fixture bugs, fixed; no production code changed in response. | +| `cargo test -p eggwork-server --lib` | **142 passed, 0 failed, 0 ignored, 0 measured** | +| `cargo test -p eggwork-server --test gc_preview_parity` | **3 passed, 0 failed** | +| `cargo fmt -p eggwork-server` | applied; a second run after the clippy fixes produced no further change, and `cargo fmt -p eggwork-server -- --check` afterwards reported clean | +| `cargo clippy -p eggwork-server --all-targets -- -D warnings` | first run: **4 errors** (`doc_lazy_continuation`, 2 × `cloned_ref_to_slice_refs`, 1 × `bool_assert_comparison`) — all in the new test code. After fixing them: **exit 0, no diagnostics**. | +| `python3 scripts/check_execution_ownership.py` | passed: "execution ownership guard passed; approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)"; "negative scanner self-test passed; crate dependency direction passed" | +| `git diff --check` | clean, no output | + +**Commands deliberately not run, and why:** + +- `cargo test --locked --workspace --all-targets` and `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` — the coordinator reserved the full gate for the end of the batch, and a second agent is concurrently editing `crates/eggwork-runner/**` and `crates/eggwork-sandbox-helper/**` in this tree. **Acceptance criterion 13 is therefore not discharged by this record.** +- `cargo fmt --all` — the instruction for this milestone was to format only `eggwork-server`, because the other agent's crates are in flight. +- `cargo test --locked -p eggwork-server --test installed_qualification` — it is `#[ignore]`d and opt-in; it needs an installed daemon and TLS material. **Not exercised.** +- `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` — **not exercised.** No Python test was added under `tests/release/`: the structural guard reads Rust source, so it belongs in a Rust integration test (`crates/eggwork-server/tests/gc_preview_parity.rs`) rather than in the release-harness suite. The release-harness suite is consequently unaffected by this milestone. +- `crates/eggwork-server/tests/release_contract.rs` and `crates/eggwork-server/tests/host_telemetry.rs` — **not executed** by this milestone (the scoped instruction named the lib suite and this milestone's own new test file). + +**A note on `--locked`.** The scoped commands above were run *without* `--locked`. This milestone changed no dependency and no `Cargo.lock` entry, so the flag would not have changed the resolution; the omission is recorded here rather than glossed over, because `AGENTS.md` treats `--locked` as load-bearing on `clippy` and `test`. + +## Platform and feature matrix actually exercised + +| Target | Exercised? | Evidence | +|---|---|---| +| Linux x86_64 (kernel 6.8.0-147-generic) | **Yes** | The full scoped suite: `cargo test -p eggwork-server --lib` → 142 passed, 0 failed; `cargo test -p eggwork-server --test gc_preview_parity` → 3 passed. This includes the unix-only branches: the `0600`/`0700` permission helpers, `symlink_metadata`-based symlink refusal in `inspect_blob`, and the unix-only `inspect_blob_refuses_a_symlinked_shard_or_object` test. | +| Linux on other architectures (aarch64, etc.) | **No** | Not executed. Nothing here qualifies any architecture other than the one above. | +| macOS | **No** | Not executed, and not qualified by this record. | +| Windows | **No** | Not executed, and not qualified by this record. The `#[cfg(not(unix))]` permission helpers and the `sync_directory` no-op were **not** exercised; neither was any `#[cfg(windows)]` branch. The one Windows-relevant code path this milestone touches is the staged-file removal on a failed copy: the staged file is closed before it is removed, so the removal is not attempted against an open handle — but that ordering was **not** exercised on Windows, and it is listed as an unresolved finding. | +| The `qualification` feature / installed-release harness | **No** | Not built, not exercised. | +| The runner and sandbox helper crates | **No** | Out of scope for this milestone and concurrently edited by another agent. `scripts/check_execution_ownership.py` passed, which confirms this milestone added no process creation to `eggwork-server`. | + +**No platform is claimed to be qualified by this record.** The milestone's changes are platform-neutral in shape, but only the row marked "Yes" was executed. + +## Compatibility review + +**Stored formats — unchanged.** No `CREATE TABLE` statement was altered in `blob.rs`, `workspace.rs` or `artifact.rs`; no column, index, trigger or default was added, removed or renamed. The blob shard layout is still `//<64-hex digest>` — `blob::object_path` computes the same path the old inline expression computed, and `BlobStore::path_for` delegates to it, so the bytes on disk are identical. The three metadata file names are unchanged (`metadata.sqlite`, `metadata.sqlite`, `artifacts.sqlite`); only the *place they are spelled* moved. The `"{principal}:{manifest_digest}"` composite is byte-identical. The manifest digest algorithm, the artifact record format, the workspace record format and the journal schema are untouched. + +**Wire and protocol surfaces — unchanged.** No route, request struct, response struct, capability string, status code or error body was added, removed or altered. `NodeGcReport` keeps the same thirteen fields, names, types and order, and `dry_run` is still set by the caller. `ResourceInspection` keeps the same three fields, and the `metadata` JSON each `inspect` verb emits is unchanged in shape and content. The digest mismatch in the materializer is surfaced as the **existing** `WorkspaceError::InvalidBlob`, which `lib.rs` already maps to `409 missing_blob` — the same code a missing blob produces. No new error code was introduced. + +**Bounds — unchanged.** `MAX_GC_BATCH` (1024) and the `1..=1024` clamp, `MAX_BLOB_BYTES`, `MAX_WORKSPACE_ENTRIES`, `MAX_ARTIFACT_FILES`, `MAX_ARTIFACT_TOTAL_BYTES`, the workspace and blob quotas, and the retention horizons are all as they were. The bounded-per-pass semantics are unchanged: one invocation removes at most `limit` items per store. The GC ordering — workspaces → manifests → artifacts → blobs — is unchanged in both the operator path and `NodeServer::collect_garbage`. The apply pass's exclusive maintenance lock, and its refusal to race a running node, are unchanged. + +**Authentication, authorization, leases, generations, fencing, digest bounds — unchanged.** None of that code was touched. The artifact-capture eligibility rule (M005a's concern), the journal's event retention, and the recovery classification are untouched. + +**What did change for the operator.** + +1. **`eggworkd gc` (preview) may now report different blob figures than before.** The preview used to count blobs with `reference_count = 0`; it now reports the store's own candidate set — blobs with no reference row. On a store whose trigger-maintained counter has drifted from its reference rows, the two disagree; on a consistent store they agree. The reported *meaning* is the correct one: the preview now answers the question the apply pass will act on. +2. **A workspace whose manifest references a blob whose bytes do not match its digest is now refused** (`409 missing_blob`) instead of being materialized from the mismatched bytes when the length happened to match. This is a behaviour change on a corrupted store: the execution fails closed instead of running against the wrong bytes. The wire code is pre-existing; no new code appears on the wire. +3. **`eggworkd gc` (preview) against a store that does not exist** still fails with the generic "bounded garbage collection failed" error, exactly as before — but the *reason* is now a guarantee rather than an accident of `SQLITE_OPEN_READ_ONLY` on a missing file, and it is covered by a test. +4. **`eggworkd inspect blob`** resolves the object through the store's path function. Its observable behaviour — the refusal of a symlinked shard or object, and the recorded-size-versus-file-length cross-check — is unchanged. + +**Performance.** One SHA-256 computation over the copied bytes per materialized file, and no additional read or byte movement. Detailed in [Verify-while-copying, not verify-then-copy](#verify-while-copying-not-verify-then-copy). + +## Documentation status + +- **`architecture/data-plane.md` — updated.** The single-owner facts (the metadata file names, the blob shard layout, the manifest owner-id composite, and the four canonical candidate statements); the non-mutating preview seam and what it costs; the reference-row predicate and the deliberate reason the counter is not consulted; the preview-versus-apply relation (subset, and equality in the no-expired-references case); the verify-while-copying change and its performance consequence; and new rows in the invariants-and-enforcement table. **All new text uses symbol references, not line numbers** — `UNREFERENCED_CANDIDATES_SQL`, `blob::preview_gc`, `BlobStore::copy_verified`, `manifest_owner_id_for_key`, and so on. The document's pre-existing stale line-number citations were **left as they are**: replacing them wholesale is a separate, much larger correction and is out of this milestone's scope, but no new line-number citation was added. +- **`architecture/operations-cli.md` — updated.** The `gc` verb reference now describes the preview as obtaining its candidate sets from the owner modules and holding no SQL of its own; the preview's non-creating behaviour; the preview-versus-apply relation and the divergence it removes; and `inspect blob`'s path resolution. The artifact database path is now described as `artifact::metadata_path(database_path)`. Two rows were added to the invariants table. New text uses symbol references. +- **`docs/operations.md` — updated.** Two operator-facing paragraphs in the "Garbage collection" section: the preview never creates or reconciles a store, and the preview may report fewer candidates than the apply pass removes for a documented reason. No other operator-facing behaviour changed, so no other section was touched. +- **`architecture/overview.md` — NOT edited.** Coordinator-owned. The text that belongs there is reported to the coordinator rather than written. +- **`plans/registry.md` — NOT edited.** Coordinator-owned; see [Registry and roadmap disposition](#registry-and-roadmap-disposition). + +## Disposition of the in-process collector path + +`NodeServer::collect_garbage` is **retained as-is**. It already calls the owner collectors, and after this milestone the owner collectors, the operator's preview, and the in-process path all evaluate the same module constants (`UNREFERENCED_CANDIDATES_SQL`, `WORKSPACE_CANDIDATES_SQL`, `MANIFEST_CANDIDATES_SQL`, `ARTIFACT_CANDIDATES_SQL`), so the in-process path and the operator's path cannot disagree about what is collectable. + +The two entry points are not *merged*, for a reason that is not about the predicate. The operator path's defining property is that it takes the exclusive maintenance lock and therefore refuses to run against a live node; the in-process path's defining property is that it runs inside the node against the already-open store instances. Merging them would give up one of those two properties. The in-process path is not exposed as a remote route. + +## Unresolved findings by severity + +| Severity | Finding | Owner | +|---|---|---| +| **Medium** | The workspace-wide gate of acceptance criterion 13 (`cargo clippy --locked --workspace --all-targets --all-features -- -D warnings`, `cargo test --locked --workspace --all-targets`) was not run by this milestone. The scoped equivalents pass, and a second agent is concurrently editing the runner and the sandbox helper in this tree, so a workspace-wide run would have raced that work. | **Coordinator** — run the full gate once at the end of the batch. | +| **Medium** | The plan's section 13 expects the corrupt-principal owner-id case to be "shown to fail before the fix". It does not fail before the fix, and this was verified experimentally rather than assumed: the pre-fix inline `format!` produced the identical composite, so the pre-fix code released the reference correctly. The defect was the duplication of the format, not a wrong release. The test as written is a refactor-regression guard; the "exactly one producer" property is enforced by the structural guard instead. The plan's expectation should be corrected, or a different test should be specified. | **Coordinator** — the plan's section 13 text; the implementing agent cannot amend `plans/implementation/**`. | +| **Low** | The materializer removes the staged file after a failed copy. The staged file is closed before the removal, so the removal is not attempted against an open handle — but this ordering was **not** exercised on Windows, where removing an open file fails. If the removal fails on Windows, the unverified bytes stay in the staging directory, which `materialize` then removes wholesale on the error path; the tree is still never published. | **Coordinator / future Windows milestone** — the Windows service host (Operations M007) is the natural place to exercise the Windows materialization path. | +| **Low** | `workspace::preview_gc` reads `sqlite_master` to decide whether the `retained_manifests` table exists, so that a pre-M004 store reports zero manifest candidates instead of failing the whole preview. This is a read of SQLite's catalogue, not a schema change, but it is a second place that knows the table's name. | **Coordinator** — acceptable as-is; would need revisiting if the table name ever changes. | +| **Informational** | The operator module still reads a single record by id for the three `inspect` verbs (`blobs`, `workspaces`, `artifacts`), so it still knows those tables' column names. Moving those reads into the owner modules was considered and deliberately **not** done: the plan's section 5.3 scopes the blob-ownership change to the *path*, and the inspection verbs legitimately need a record projection. The structural guard is scoped accordingly — it forbids the reclamation predicates, not SQL in general. | **Coordinator** — a future data-plane milestone may want to move the inspection reads as well. | + +## Registry and roadmap disposition + +- **`plans/subsystems/workspace-artifact-transport-roadmap.md` — updated by this milestone.** The status line now reads *"Status: active roadmap; M001-M004 closed; M005a data-plane corrective proposed; M005b data-plane corrective implemented"*, and the M005b entry's status changed from `proposed` to `implemented`, with a `Closure record:` block pointing at this record and a short `Implemented:` summary in the density of the neighbouring entries. **The M005a section was not touched**, and no other roadmap's status line was touched. +- **`plans/registry.md` — NOT edited by this milestone.** The registry is owned by the planning process, not by the implementing agent (plan section 14). The coordinator owns the entry that points at this closure record and at the M005b milestone. +- **Both closure records are preserved.** M005a's record (if the coordinator has written it) and this one stand side by side; nothing in the historical M001-M004 records was rewritten. + +## Deviations from the plan + +| Deviation | Reason | +|---|---| +| The materializer uses a **new** store-owned routine, `BlobStore::copy_verified`, rather than the roadmap's exit-condition wording "the workspace materializer uses the store's verified-open path" (`BlobStore::open_verified`). | `open_verified` verifies the object and then opens it — two reads of a mutable file, with a window between them. The plan's section 5.4 requires the verification to be *"bound to the bytes actually copied"*, which `open_verified` cannot provide. `copy_verified` is store-owned and satisfies section 5.4 directly. The roadmap's exit-condition wording is now slightly behind the implementation; the coordinator may wish to align it. | +| The workspace-side candidate helpers are named `workspace_candidates` and `manifest_candidates` (module-private) rather than being exposed as `pub`. | Only the *preview* entry points need to be public. The collectors call the same module-private helpers inside the owning module, which is where the predicate has to live. Exposing more would widen the surface without widening the guarantee. | +| The artifact collector's redundant unbounded `COUNT(*)` of expired artifacts was removed, and the delete now removes the rows the candidate window named, one statement per artifact id. | The unbounded count was the same predicate written a second time in the owner module, and `candidate_count.min(count)` was always `candidate_count` because the window is a bounded subset of the same set — so the reported values are unchanged. Removing it leaves exactly one implementation of the artifact predicate. The delete shape changed (parameterized per-id deletes instead of one `IN (subquery)`); the removed set is identical. | +| The manifest GC validates the row's principal where it can and falls back to the raw key otherwise, rather than always using the raw key. | The plan's section 5.5 asked for the validated entry point where validation is possible. The fallback is retained because one call site is reached precisely when the principal does not parse, and refusing to release the reference there would leak the pin. Both forms produce the same bytes, so the released owner id is unchanged. | +| The corrupt-principal test does not reproduce a pre-fix failure. | See [Unresolved findings](#unresolved-findings-by-severity). The plan's expectation was that it would; it does not, and this was verified rather than assumed. | +| No Python test was added under `tests/release/`. | The structural guard reads Rust source, so it belongs in a Rust integration test. `tests/release/test_gc_preview_parity.py` was not created, and the release-harness suite is unaffected. | +| The scoped cargo commands were run without `--locked`. | Recorded above. This milestone changed no dependency and no `Cargo.lock` entry. | + +## Change set + +| File | Change | +|---|---| +| `crates/eggwork-server/src/blob.rs` | The canonical blob candidate statement and the expired-reference count as module constants; `BlobStore::unreferenced_candidates` takes a `&Connection`; `blob::preview_gc`, `blob::metadata_path`, `blob::shard_path`, `blob::object_path`; `BlobStore::path_for` delegates to `object_path`; `BlobStore::copy_verified` and the `VerifyWriter` hashing writer; `remove_stale_parts` resolves through the owned path function. | +| `crates/eggwork-server/src/workspace.rs` | The canonical workspace and retained-manifest statements; `workspace::preview_gc`, `workspace::metadata_path`, `workspace_candidates`, `manifest_candidates`, `table_exists`; `manifest_owner_id_for_key` / `manifest_owner_id` and the two former inline call sites routed through them; `materialize_tree` verifies the copied bytes through `BlobStore::copy_verified` and removes the staged file on failure. | +| `crates/eggwork-server/src/artifact.rs` | The canonical artifact candidate statement; `artifact::preview_gc`, `artifact::metadata_path`, `artifact_candidates`; the collector selects through the canonical statement and deletes the rows it named. | +| `crates/eggwork-server/src/operations.rs` | `dry_run_gc` obtains its candidate sets from the owner modules and holds no SQL; `inspect_blob` resolves the shard and object through the store's path ownership; `inspect_workspace`, `inspect_artifact` and `storage_summary` resolve the metadata path through the owner; the new tests. | +| `crates/eggwork-server/src/lib.rs` | The artifact database path now comes from `artifact::metadata_path`. | +| `crates/eggwork-server/tests/gc_preview_parity.rs` | **New.** The structural guard. | +| `architecture/data-plane.md` | The single-owner facts, the preview seam, the reference-row predicate, the verify-while-copying consequence, the new invariants rows, the new test coverage, the honest gaps. | +| `architecture/operations-cli.md` | The `gc` verb reference and the `inspect blob` reference; the new invariants rows. | +| `docs/operations.md` | Two operator-facing paragraphs in the GC section. | +| `plans/subsystems/workspace-artifact-transport-roadmap.md` | The status line, the M005b status, the closure-record pointer, the implemented summary. | +| `plans/closure/workspace-artifact-transport/005b-status.md` | **New.** This record. | + +No file outside this list was modified by this milestone. `crates/eggwork-core/**`, `crates/eggwork-client/**`, `crates/eggwork-runner/**`, `crates/eggwork-sandbox-helper/**`, `crates/eggwork-server/src/store.rs`, `scripts/**`, `tests/release/**`, `architecture/overview.md`, `plans/registry.md`, `plans/000-*` through `plans/003-*`, and every `Cargo.toml` were left alone. diff --git a/plans/registry.md b/plans/registry.md index 4fbe072..7f4fc98 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -92,7 +92,7 @@ A repository-wide code interrogation pass over the reviewed baseline found no `t |---|---|---|---| | `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | proposed | | `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | proposed | -| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a/M005b proposed; **M005c blocked on ADR-0007** | +| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a implemented; M005b proposed; **M005c blocked on ADR-0007** | | `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | | `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | proposed | @@ -111,7 +111,7 @@ Two findings in this batch were deliberately **not** given a milestone, because | Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | | Control-plane protocol | M001-M003 closed; M004 corrective proposed | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | | Workspace / artifacts | M001-M004 closed; M005a and M005b correctives proposed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | -| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a/M005b proposed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) and M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | +| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a implemented, M005b proposed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | | Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready; M008a/M008b proposed | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. A repository interrogation pass added M008a (five live metrics are never reported by the operator surface; one `active_executions` field name carries two meanings; every configuration fault collapses into one unhelpful message) and M008b (the release harness re-derives facts that already have an owner, and the design record's line citations and size figures are stale with no gate) | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md`, `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | @@ -147,6 +147,7 @@ The repository interrogation corrective batch is registered but is **not** depen | Security | M003 resource enforcement | qualified/closed | `plans/closure/security-isolation-resource/003-status.md` | | Security | M004 adversarial + cross-platform closure | closed | `plans/closure/security-isolation-resource/004-status.md` (implementation `283f3ea`, incl. null-device write hardening fix); platform claims limited to hosted Linux with macOS/Windows fail-closed by construction | | Security corrective | C001 remote enforcement admission + capability truthfulness | closed | `plans/closure/security-isolation-resource-remote-admission-corrective/001-status.md` | +| Security corrective | M005a degraded-isolation observability | implemented | `plans/closure/security-isolation-resource/005a-status.md` — a degraded best-effort request now produces a bounded diagnostic event published before the target's first output and before the terminal event; the diagnostic grammar is owned by `eggwork-core`. The runner's public `OutputChunk` became an enum carrying a `Diagnostic` variant, which is release-visible. | | Optional Gregg telemetry | M001 default-off loopback adapter/cache | closed | `plans/closure/optional-gregg-host-telemetry/001-status.md` (implementation `ac55985`) | | Optional Gregg telemetry | M002 authenticated node telemetry API/client | closed | `plans/closure/optional-gregg-host-telemetry/002-status.md` (implementation `5ccb1e6`); frozen contract `eggwork_core::NodeTelemetry` schema version 1, narrow `telemetry` grant, `NodeClient::telemetry`/`telemetry_for` | | Operations | M001 node operations | closed | `plans/closure/operations-distribution/001-status.md` | @@ -173,7 +174,7 @@ The repository interrogation corrective batch is registered but is **not** depen | Control-plane M004 shared protocol contract corrective | **proposed** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. | | Workspace M005a declared-artifact capture fail-closed corrective | **proposed** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`. | | Workspace M005b GC preview and store ownership corrective | **proposed** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass use different candidate predicates, in a module whose own doc comment states the two must be shared — a stated invariant already violated in the sibling module. Also covers the blob store's path layout and the manifest owner-id format being re-derived outside their owners. Addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`. | -| Security M005a degraded-isolation observability corrective | **proposed** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` is emitted only from test code, so a degraded best-effort isolation or resource enforcement is invisible to an event-streaming caller and is discoverable only by polling the terminal snapshot. Addendum: `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`. | +| Security M005a degraded-isolation observability corrective | **implemented** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` was emitted only from test code, so a degraded best-effort isolation or resource enforcement was invisible to an event-streaming caller. Implemented: the runner emits a bounded diagnostic through its output channel **before the target spawns**, the server forwards it as `ExecutionEventKind::Diagnostic`, and the diagnostic grammar is owned by `eggwork-core` so producer and server share one definition. The diagnostic precedes the target's first output and the terminal event, is durable in the journal, and is emitted exactly once per degradation. The `Required` path is untouched. Closure record: `plans/closure/security-isolation-resource/005a-status.md`. | | Security M005b sandbox-helper environment parity corrective | **proposed** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list is maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule has no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix must be a shared artifact plus a pinning test, not a shared crate. **This is the most severe finding in the batch.** The duplication is live: the runner's launch-spec builder starts from a fixed baseline (`PATH`, `LANG`, `LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER`) and then appends every non-denied caller key, and none of those baseline keys except `PATH` is denied. A caller that sets `LANG` therefore produces a launch specification with two `LANG` entries; the helper refuses a specification with duplicate keys with status 12; the runner reads that as a pre-target setup failure and — for a **best-effort** request only — rewrites the sandbox outcome to `NotApplied` and **re-spawns the target directly with no Landlock ruleset at all**. The observable result today is a successful, entirely unconfined execution whose only record of the degradation is a `NotApplied` in the terminal snapshot. The `Required` path is unaffected and still fails closed. Addendum: `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`. | | Security M005c resource-scoped authorization corrective | **blocked** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. Blocked on ADR-0007 (`plans/adrs/ADR-0007-resource-scoped-authorization.md`, **proposed, not accepted**), which must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. The gap itself is already recorded as divergence #4; this is a decision about a known gap, not a new defect. | | Operations M008a operator surface truthfulness corrective | **proposed** | `plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md`. Five live metrics are incremented by the server and never reported by `eggworkd status`/`eggworkd metrics`; one `active_executions` field name carries two different meanings across the API and the CLI; and every configuration fault collapses into the single unhelpful message `configuration is invalid or unreadable`. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | @@ -220,7 +221,7 @@ Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 auth Repository interrogation corrective batch [PROPOSED] --+--> Control-plane M004 shared protocol contract [PROPOSED] +--> Workspace M005a artifact capture fail-closed [PROPOSED] +--> Workspace M005b GC preview and store ownership [PROPOSED] - +--> Security M005a degraded-isolation observability [PROPOSED] + +--> Security M005a degraded-isolation observability [IMPLEMENTED] +--> Security M005b helper environment parity [PROPOSED] +--> Security M005c resource-scoped authorization [BLOCKED on ADR-0007] +--> Operations M008a operator surface truthfulness [PROPOSED] diff --git a/plans/subsystems/security-isolation-resource-roadmap.md b/plans/subsystems/security-isolation-resource-roadmap.md index 4b9388d..22fba14 100644 --- a/plans/subsystems/security-isolation-resource-roadmap.md +++ b/plans/subsystems/security-isolation-resource-roadmap.md @@ -1,6 +1,6 @@ # Security, Isolation, and Resource Enforcement Roadmap -Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a implemented (closure record written, implementation commit pending); M005b corrective proposed; M005c blocked on ADR-0007 +Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a and M005b implemented (closure records written, implementation commits pending); M005c blocked on ADR-0007 Canonical authority: @@ -182,7 +182,10 @@ Exit conditions: Class: invariant -Status: proposed +Status: implemented — closure record written, implementation commit pending + +Closure evidence: `plans/closure/security-isolation-resource/005b-status.md` +(implementation `IMPLEMENTATION-COMMIT-PENDING`) Corrective addendum: diff --git a/plans/subsystems/workspace-artifact-transport-roadmap.md b/plans/subsystems/workspace-artifact-transport-roadmap.md index cad33a2..5b276bd 100644 --- a/plans/subsystems/workspace-artifact-transport-roadmap.md +++ b/plans/subsystems/workspace-artifact-transport-roadmap.md @@ -1,6 +1,6 @@ # Workspace and Artifact Transport Roadmap -Status: active roadmap; M001-M004 closed; M005a and M005b data-plane correctives proposed +Status: active roadmap; M001-M004 closed; M005a data-plane corrective proposed; M005b data-plane corrective implemented Canonical authority: @@ -161,7 +161,7 @@ Exit conditions: Class: invariant -Status: proposed +Status: implemented Corrective addendum: @@ -171,6 +171,10 @@ Implementation plan: - `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md` +Closure record: + +- `plans/closure/workspace-artifact-transport/005b-status.md` + Objective: Make the operator's GC preview and the apply pass share one implementation, so they cannot disagree, and bring the blob store's path layout and the manifest owner-id format back under the modules that own them. The owner module already states that the dry run and the real run must share the candidate statement; that rule is currently violated in the sibling module, where the preview uses a different predicate from the one the apply pass uses. @@ -184,6 +188,14 @@ Exit conditions: - a test proves that the preview and the apply pass agree; - no public protocol surface and no stored format changes. +Implemented: + +- the candidate predicate for blobs, workspaces, retained manifests, and artifacts is written once, in the owner module, and the operator's preview obtains its candidate sets through that owner code and holds no SQL of its own; +- the preview reaches the owner through a non-mutating seam - `blob::preview_gc`, `workspace::preview_gc`, and `artifact::preview_gc` open the metadata database read-only, because every owner `open` creates and reconciles; +- the blob path layout has one owner: `blob::object_path` and `blob::shard_path`, which `BlobStore::path_for` delegates to; +- the materializer verifies the bytes it writes while copying them, through the store's `copy_verified`, so the verification is bound to the bytes actually copied rather than to a separate earlier read; +- the manifest owner id has one producer, `manifest_owner_id_for_key`, with `manifest_owner_id` as the validated-principal entry point and the two inlined call sites routed through it. + ## 4. Future optimized materializers After M004, optional adapters may add: diff --git a/scripts/generate_environment_policy.py b/scripts/generate_environment_policy.py new file mode 100644 index 0000000..9ab8754 --- /dev/null +++ b/scripts/generate_environment_policy.py @@ -0,0 +1,598 @@ +#!/usr/bin/env python3 +"""Generate the sandbox environment-policy copies from the runner's source of truth. + +The node's environment policy — the denied-key list and its matching rule, the +node-owned (reserved) keys, the node-owned baseline, and the `PATH` value +contract — is authored once, in +``crates/eggwork-runner/policy/environment-policy.toml``. + +``eggwork-sandbox-helper`` enforces that policy and may not depend on any +workspace crate, so the policy cannot be shared as a library. It is shared as +a *generated copy*: this script writes one copy into each crate, inside that +crate's own source directory, and both crates compile only their own copy. No +crate reads a file from outside its own directory, no ``build.rs`` is added, +and no dependency edge is created. + +The generator is not the gate. The *test* is: a parity test compares the two +copies and fails the build on a one-sided edit, whether or not this script was +ever run. This script exists so that the intended edit is a one-step +operation. + +Usage:: + + python3 scripts/generate_environment_policy.py # rewrite both copies + python3 scripts/generate_environment_policy.py --check # fail if they differ + python3 scripts/generate_environment_policy.py --root DIR # operate on another tree + +The output is deterministic: re-running over an unchanged source of truth +produces byte-identical files. The script never touches the network, uses only +the standard library, and fails loudly — without writing anything — when the +source of truth is malformed. +""" + +from __future__ import annotations + +import argparse +import os +import re +import sys +import tempfile +import tomllib +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +POLICY_RELATIVE = Path("crates/eggwork-runner/policy/environment-policy.toml") +CORE_RELATIVE = Path("crates/eggwork-core/src/lib.rs") +RUNNER_OUTPUT_RELATIVE = Path("crates/eggwork-runner/src/environment_policy.rs") +HELPER_OUTPUT_RELATIVE = Path("crates/eggwork-sandbox-helper/src/environment_policy.rs") + +# The five protocol limit constants the helper used to re-declare by hand. +# `eggwork-core` owns the wire limits; the helper cannot import them, so the +# generator reads them out of the owner and emits them into the helper's copy. +CORE_LIMIT_NAMES = ( + "MAX_ARG_COUNT", + "MAX_ARG_BYTES", + "MAX_ENV_COUNT", + "MAX_ENV_NAME_BYTES", + "MAX_ENV_VALUE_BYTES", +) + +# The one matching rule this generator knows how to emit. A new rule is a +# contract change and needs a new emitter, not a silently different predicate. +EXPECTED_MATCH_RULE = "ascii-uppercase-exact-or-prefix" + +# The only `PATH` scope this generator knows about. +EXPECTED_PATH_SCOPE = "linux-unix" + +# `pub const NAME: usize = ;` in `eggwork-core`. +CORE_CONST_PATTERN = re.compile( + r"^pub const (?PMAX_[A-Z0-9_]+): usize = (?P[0-9_ ()\-+*/]+);$", + re.MULTILINE, +) + + +class PolicyError(Exception): + """The source of truth is malformed. Nothing was written.""" + + +def fail(message: str) -> "NoReturn": # noqa: F821 - typing only + raise PolicyError(message) + + +# -------------------------------------------------------------------------- +# A tiny integer-expression evaluator. +# +# `eggwork-core` writes some limits as arithmetic (`32 * 1024`), so the +# generator has to read an expression rather than a literal. It deliberately +# does not use `eval`: the parser below accepts nothing but integer literals, +# `+ - * /` and parentheses, and it refuses anything else. +# -------------------------------------------------------------------------- + +_EXPRESSION_TOKEN = re.compile(r"\s*(?:(?P[0-9]+)|(?P[-+*/()]))") + + +def evaluate_integer_expression(expression: str) -> int: + """Evaluate a pure integer arithmetic expression, or fail loudly.""" + tokens: list[str] = [] + position = 0 + while position < len(expression): + match = _EXPRESSION_TOKEN.match(expression, position) + if match is None: + fail( + f"the limit expression {expression!r} contains something that is not an " + f"integer literal or an arithmetic operator" + ) + position = match.end() + tokens.append(match.group("number") if match.group("number") else match.group("operator")) + if not tokens: + fail(f"the limit expression {expression!r} is empty") + + index = 0 + + def parse_primary() -> int: + nonlocal index + if index >= len(tokens): + fail(f"the limit expression {expression!r} ends unexpectedly") + token = tokens[index] + if token == "(": + index += 1 + value = parse_sum() + if index >= len(tokens) or tokens[index] != ")": + fail(f"the limit expression {expression!r} has an unbalanced parenthesis") + index += 1 + return value + if not token.isdigit(): + fail(f"the limit expression {expression!r} has an unexpected token {token!r}") + index += 1 + return int(token) + + def parse_product() -> int: + nonlocal index + value = parse_primary() + while index < len(tokens) and tokens[index] in ("*", "/"): + operator = tokens[index] + index += 1 + right = parse_primary() + if operator == "*": + value *= right + else: + if right == 0: + fail(f"the limit expression {expression!r} divides by zero") + value //= right + return value + + def parse_sum() -> int: + nonlocal index + value = parse_product() + while index < len(tokens) and tokens[index] in ("+", "-"): + operator = tokens[index] + index += 1 + right = parse_product() + value = value + right if operator == "+" else value - right + return value + + result = parse_sum() + if index != len(tokens): + fail(f"the limit expression {expression!r} has trailing tokens") + return result + + +def read_core_limits(path: Path) -> dict[str, int]: + """Read the five protocol limit constants out of `eggwork-core`.""" + try: + source = path.read_text(encoding="utf-8") + except FileNotFoundError: + fail(f"the owner of the wire limits is missing: {path}") + except OSError as error: + fail(f"the owner of the wire limits could not be read: {path}: {error}") + + found: dict[str, int] = {} + for match in CORE_CONST_PATTERN.finditer(source): + name = match.group("name") + if name in CORE_LIMIT_NAMES: + found[name] = evaluate_integer_expression(match.group("value")) + missing = [name for name in CORE_LIMIT_NAMES if name not in found] + if missing: + fail( + f"{path} does not export the protocol limit constants " + f"{', '.join(missing)}; the helper's copy of them would be guessed rather " + f"than generated" + ) + return found + + +# -------------------------------------------------------------------------- +# Reading and validating the source of truth. +# -------------------------------------------------------------------------- + + +def _lookup(document: dict, path: str) -> object: + """Look up a dotted path such as `baseline.windows_common`.""" + node: object = document + for part in path.split("."): + if not isinstance(node, dict) or part not in node: + fail(f"the environment policy has no [{path}] table") + node = node[part] + return node + + +def _require_table(document: dict, name: str) -> dict: + value = _lookup(document, name) + if not isinstance(value, dict): + fail(f"the environment policy has no [{name}] table") + return value + + +def _require_string_list(document: dict, table: str, name: str) -> list[str]: + values = _require_table(document, table).get(name) + if not isinstance(values, list) or not values: + fail(f"the environment policy's [{table}].{name} must be a non-empty list") + for value in values: + if not isinstance(value, str) or not value: + fail(f"the environment policy's [{table}].{name} must hold non-empty strings") + if len(set(values)) != len(values): + duplicates = sorted({value for value in values if values.count(value) > 1}) + fail( + f"the environment policy's [{table}].{name} repeats " + f"{', '.join(duplicates)}; a repeated entry is a contract change, not a duplicate" + ) + return list(values) + + +def _require_baseline_table(document: dict, name: str) -> list[tuple[str, str]]: + table = document.get("baseline", {}) + if not isinstance(table, dict): + fail("the environment policy has no [baseline] table") + entries = table.get(name) + if not isinstance(entries, dict) or not entries: + fail(f"the environment policy has no non-empty [baseline.{name}] table") + pairs: list[tuple[str, str]] = [] + for key, value in entries.items(): + if not isinstance(key, str) or not key: + fail(f"the environment policy's [baseline.{name}] has an empty key") + if not isinstance(value, str): + fail(f"the environment policy's [baseline.{name}].{key} must be a string") + pairs.append((key, value)) + return pairs + + +def read_policy(path: Path) -> dict: + """Read and validate the source of truth. Returns the validated policy.""" + try: + with path.open("rb") as handle: + document = tomllib.load(handle) + except FileNotFoundError: + fail(f"the environment policy source of truth is missing: {path}") + except tomllib.TOMLDecodeError as error: + fail(f"the environment policy source of truth is not valid TOML: {path}: {error}") + except OSError as error: + fail(f"the environment policy source of truth could not be read: {path}: {error}") + + version = document.get("schema_version") + if version != 1: + fail( + f"the environment policy source of truth declares schema_version {version!r}; " + f"this generator only understands version 1" + ) + + match = _require_table(document, "match") + rule = match.get("rule") + if rule != EXPECTED_MATCH_RULE: + fail( + f"the environment policy's [match].rule is {rule!r}; this generator only " + f"emits {EXPECTED_MATCH_RULE!r}" + ) + + denied = _require_string_list(document, "denied", "keys") + reserved = _require_string_list(document, "reserved", "keys") + unix = _require_baseline_table(document, "unix") + windows_common = _require_string_list(document, "baseline.windows_common", "keys") + + path_contract = _require_table(document, "path_contract") + path_value = path_contract.get("value") + if not isinstance(path_value, str) or not path_value: + fail("the environment policy's [path_contract].value must be a non-empty string") + scope = path_contract.get("scope") + if scope != EXPECTED_PATH_SCOPE: + fail( + f"the environment policy's [path_contract].scope is {scope!r}; this generator " + f"only emits {EXPECTED_PATH_SCOPE!r}" + ) + + unix_values = dict(unix) + for key in windows_common: + if key not in unix_values: + fail( + f"the environment policy's [baseline.windows_common] names {key}, which the " + f"Unix baseline does not carry; the Windows branch's shared keys must exist " + f"in the Unix baseline" + ) + common = [(key, unix_values[key]) for key in windows_common] + + baseline = unix + baseline_keys = [key for key, _ in baseline] + if len(set(baseline_keys)) != len(baseline_keys): + fail("the environment policy's baseline names the same key twice") + if set(reserved) != set(baseline_keys): + only_reserved = sorted(set(reserved) - set(baseline_keys)) + only_baseline = sorted(set(baseline_keys) - set(reserved)) + fail( + "the environment policy's node-owned class and its baseline disagree: " + f"reserved-only {only_reserved}, baseline-only {only_baseline}. The node-owned " + f"class is the node's own baseline, so the two cannot differ" + ) + if reserved != baseline_keys: + fail( + "the environment policy's node-owned class and its baseline list the same keys in " + "different orders; they are one list, written once, and the order is part of the " + "generated contract" + ) + unix_path = unix_values.get("PATH") + if unix_path != path_value: + fail( + f"the environment policy's [path_contract].value ({path_value!r}) differs from " + f"the Unix baseline's PATH ({unix_path!r}); the contract and the baseline are " + f"the same value and are written twice" + ) + + return { + "match_rule": rule, + "denied": denied, + "reserved": reserved, + "baseline_common": common, + "baseline": baseline, + "path_value": path_value, + } + + +# -------------------------------------------------------------------------- +# Rendering. +# -------------------------------------------------------------------------- + + +def rust_string(value: str) -> str: + escaped = value.replace("\\", "\\\\").replace('"', '\\"') + return f'"{escaped}"' + + +def rust_string_array(name: str, doc: list[str], values: list[str]) -> str: + lines = [f"pub const {name}: &[&str] = &["] + lines.extend(f" {rust_string(value)}," for value in values) + lines.append("];") + return "\n".join([*doc, *lines]) + + +def rust_pair_array(name: str, doc: list[str], values: list[tuple[str, str]]) -> str: + lines = [f"pub const {name}: &[(&str, &str)] = &["] + lines.extend(f" ({rust_string(key)}, {rust_string(value)})," for key, value in values) + lines.append("];") + return "\n".join([*doc, *lines]) + + +def module_header(crate_role: str) -> str: + return "\n".join( + [ + "// @generated by scripts/generate_environment_policy.py — do not edit.", + "//", + "// Source of truth: crates/eggwork-runner/policy/environment-policy.toml", + "// Generator: scripts/generate_environment_policy.py", + "//", + "// This file is generated. A hand edit is a contract change, not a local", + "// fix: change the source of truth and re-run the generator.", + "//", + f"// This is the {crate_role}'s copy. The other copy is generated from the same", + "// source of truth, and a parity test pins the two together, so a one-sided", + "// edit fails the build rather than silently changing what is enforced.", + ] + ) + + +def render_policy_items(policy: dict, role: str) -> str: + """The policy items both crates carry, rendered identically in each.""" + parts = [ + module_header(role), + "", + "/// The keys a caller may not set.", + "///", + "/// The runner drops one of these silently: it is the request-normalisation", + "/// boundary, and a hardened environment has to be a property of the node", + "/// rather than something the caller has to get right. The helper refuses the", + "/// whole launch when one of these is present: it is the enforcement point, and", + "/// a denied key reaching it means the node's own filtering did not happen.", + "/// The difference is deliberate and is the whole two-layer contract; only the", + "/// list is shared, never the behaviour.", + rust_string_array( + "DENIED_KEYS", + [], + policy["denied"], + ), + "", + "/// The rule used to match an environment key against `DENIED_KEYS` and against", + "/// the node-owned class: ASCII-uppercase the key, then match it as an exact", + "/// match or as a prefix.", + "///", + "/// The rule is part of the contract, not an implementation detail: the two", + "/// copies must agree on it, or the runner would drop a key the helper still", + "/// refuses.", + f"pub const MATCH_RULE: &str = {rust_string(policy['match_rule'])};", + "", + "/// The node-owned (reserved) keys on the Unix baseline.", + "///", + "/// A caller-supplied value for one of these is discarded in favour of the", + "/// node's value, so the node's baseline is what reaches the child and a", + "/// launch specification can never carry a duplicate of a baseline key.", + "///", + "/// The class is the node-owned baseline, and the baseline is platform-shaped:", + "/// on the Windows baseline the node owns `SystemRoot`, `windir` and `PATH`", + "/// instead of the Unix locale keys, and that branch is runner-local.", + rust_string_array( + "RESERVED_KEYS", + [], + policy["reserved"], + ), + "", + "/// The node-owned baseline keys every platform carries.", + "///", + "/// The values are the node's own; a caller cannot move them. This is the", + "/// part of the Unix baseline the runner's Windows branch also installs, so", + "/// the Windows branch does not have to re-list it.", + rust_pair_array( + "BASELINE_COMMON", + [], + policy["baseline_common"], + ), + "", + "/// The node-owned Unix baseline, in the order the node installs it.", + "///", + "/// The Windows baseline is deliberately not here: its values are read from the", + "/// parent process at spawn time, and the sandbox helper is Linux-only so it", + "/// never sees a Windows launch. That branch is runner-local.", + rust_pair_array( + "BASELINE", + [], + policy["baseline"], + ), + "", + "/// The enforced `PATH` value on the Linux/Unix contract.", + "///", + "/// A `PATH` that points outside this value widens what a confined target can", + "/// execute, and the helper's Landlock ruleset does not restrict `execve` by", + "/// path. The helper refuses a launch whose `PATH` differs; the runner", + "/// guarantees the value in the child environment and in the launch", + "/// specification.", + "///", + "/// The contract is Linux/Unix. The Windows baseline is explicitly outside it,", + "/// so the Windows `PATH` must not be \"fixed\" to this value.", + f"pub const PATH_VALUE: &str = {rust_string(policy['path_value'])};", + "", + "/// True when `key` is denied: the caller may not set it.", + "///", + "/// The key is ASCII-uppercased first, so the match is case-insensitive, and", + "/// the entry is matched as an exact match or as a prefix.", + "pub fn denied_environment_key(key: &str) -> bool {", + " let upper = key.to_ascii_uppercase();", + " DENIED_KEYS", + " .iter()", + " .any(|denied| upper == *denied || upper.starts_with(denied))", + "}", + "", + "/// True when `key` is node-owned on the Unix baseline.", + "///", + "/// The key is ASCII-uppercased first, so a caller's differently-cased spelling", + "/// of a node-owned key is recognised as the same key.", + "pub fn is_reserved_key(key: &str) -> bool {", + " let upper = key.to_ascii_uppercase();", + " RESERVED_KEYS.iter().any(|reserved| upper == *reserved)", + "}", + "", + "/// The node's baseline entry for `key`, matched case-insensitively.", + "///", + "/// The returned name is the node's own spelling of the key, so a caller that", + "/// used a different spelling can be told apart from one that used the node's.", + "pub fn baseline_entry(key: &str) -> Option<(&'static str, &'static str)> {", + " let upper = key.to_ascii_uppercase();", + " BASELINE", + " .iter()", + " .find(|(name, _)| *name == upper)", + " .map(|(name, value)| (*name, *value))", + "}", + "", + "/// The node's baseline value for `key`, matched case-insensitively.", + "///", + "/// The value is the node's own; a caller's value for a node-owned key is", + "/// discarded in favour of it.", + "pub fn baseline_value(key: &str) -> Option<&'static str> {", + " baseline_entry(key).map(|(_, value)| value)", + "}", + ] + return "\n".join(parts) + "\n" + + +def render_runner_module(policy: dict) -> str: + return render_policy_items(policy, "runner") + + +def render_helper_module(policy: dict, limits: dict[str, int]) -> str: + parts = [ + render_policy_items(policy, "sandbox helper").rstrip("\n"), + "", + "/// The protocol limit constants, generated from `eggwork-core`.", + "///", + "/// The helper is a standalone binary with no workspace-crate dependency, so it", + "/// cannot import `eggwork_core::MAX_ARG_COUNT` and friends. The generator reads", + "/// these values out of the owner of the wire limits, so the helper's copy is", + "/// generated rather than hand-maintained, and a parity test compares them", + "/// against `eggwork-core` at run time.", + "///", + "/// `MAX_SPEC_BYTES` is helper-only, has no core counterpart, and stays in the", + "/// helper's own source.", + ] + for name in CORE_LIMIT_NAMES: + parts.append(f"pub const {name}: usize = {limits[name]};") + return "\n".join(parts) + "\n" + + +# -------------------------------------------------------------------------- +# Writing. +# -------------------------------------------------------------------------- + + +def write_atomically(path: Path, content: str) -> None: + """Write `content` to `path` without ever leaving a partial file behind.""" + path.parent.mkdir(parents=True, exist_ok=True) + handle, temporary = tempfile.mkstemp(dir=str(path.parent), prefix=".environment-policy-") + try: + with os.fdopen(handle, "w", encoding="utf-8", newline="\n") as stream: + stream.write(content) + os.replace(temporary, path) + except BaseException: + try: + os.unlink(temporary) + except OSError: + pass + raise + + +def main(argv: list[str]) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "--check", + action="store_true", + help="do not write anything; fail when the checked-in copies differ from the source of truth", + ) + parser.add_argument( + "--root", + type=Path, + default=ROOT, + help="the repository root to operate on (default: the tree this script lives in)", + ) + arguments = parser.parse_args(argv) + root = arguments.root.resolve() + + policy_path = root / POLICY_RELATIVE + core_path = root / CORE_RELATIVE + runner_output = root / RUNNER_OUTPUT_RELATIVE + helper_output = root / HELPER_OUTPUT_RELATIVE + + try: + policy = read_policy(policy_path) + limits = read_core_limits(core_path) + except PolicyError as error: + print(f"error: {error}", file=sys.stderr) + return 1 + + rendered = { + runner_output: render_runner_module(policy), + helper_output: render_helper_module(policy, limits), + } + + if arguments.check: + stale: list[Path] = [] + for path, content in rendered.items(): + try: + current = path.read_text(encoding="utf-8") + except OSError: + stale.append(path) + continue + if current != content: + stale.append(path) + if stale: + for path in stale: + print( + f"error: {path.relative_to(root)} is not what the generator produces; " + f"run `python3 scripts/generate_environment_policy.py`", + file=sys.stderr, + ) + return 1 + print("the environment-policy copies are up to date") + return 0 + + for path, content in rendered.items(): + write_atomically(path, content) + print(f"wrote {path.relative_to(root)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(sys.argv[1:])) diff --git a/tests/release/test_environment_policy.py b/tests/release/test_environment_policy.py new file mode 100644 index 0000000..91d46ed --- /dev/null +++ b/tests/release/test_environment_policy.py @@ -0,0 +1,172 @@ +"""Drift tests for the sandbox environment-policy generator. + +The environment policy — the denied-key list and its matching rule, the +node-owned (reserved) keys, the node-owned baseline, and the `PATH` value +contract — has one owner: +``crates/eggwork-runner/policy/environment-policy.toml``. The runner and the +standalone sandbox helper each compile a *generated* copy of it, because the +helper may not depend on any workspace crate. + +Two copies of one contract is a hole unless something pins them together. The +Rust side pins them together behaviourally (a parity test drives the real +helper executable and compares its decisions with the runner's policy). This +file pins the other end: that the generator is deterministic, that it fails +loudly rather than emitting a partial file, and that the checked-in copies +are what the generator produces. + +The generator is not the gate. These tests are: a hand edit of a generated +copy is a contract change, and the check here is what makes that visible +before it reaches a release. +""" + +from __future__ import annotations + +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPOSITORY_ROOT = Path(__file__).resolve().parents[2] +GENERATOR = REPOSITORY_ROOT / "scripts" / "generate_environment_policy.py" +POLICY = Path("crates/eggwork-runner/policy/environment-policy.toml") +CORE = Path("crates/eggwork-core/src/lib.rs") +RUNNER_OUTPUT = Path("crates/eggwork-runner/src/environment_policy.rs") +HELPER_OUTPUT = Path("crates/eggwork-sandbox-helper/src/environment_policy.rs") + + +def run_generator(*arguments: str, root: Path | None = None) -> subprocess.CompletedProcess[str]: + """Run the generator and return the completed process.""" + command = [sys.executable, str(GENERATOR), *arguments] + if root is not None: + command.extend(["--root", str(root)]) + return subprocess.run( + command, + capture_output=True, + text=True, + check=False, + ) + + +class GeneratorDriftTests(unittest.TestCase): + """The generator's own properties.""" + + def test_the_checked_in_copies_are_what_the_generator_produces(self) -> None: + """The committed copies must be the generator's output, byte for byte. + + This is the drift check. A hand edit of a generated copy — or a + generator change that was never re-run — fails here rather than + reaching a release with two different policies in the tree. + """ + result = run_generator("--check") + self.assertEqual( + result.returncode, + 0, + "the checked-in environment-policy copies differ from the generator's output; " + f"run `python3 scripts/generate_environment_policy.py`\n{result.stdout}" + f"{result.stderr}", + ) + + def test_the_generator_is_deterministic(self) -> None: + """Running the generator twice must produce byte-identical output. + + A generator whose output moves between runs would make the drift check + above useless: it would fail for a reason that has nothing to do with + the policy. + """ + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / POLICY.parent).mkdir(parents=True) + (root / CORE.parent).mkdir(parents=True) + shutil.copyfile(REPOSITORY_ROOT / POLICY, root / POLICY) + shutil.copyfile(REPOSITORY_ROOT / CORE, root / CORE) + first = run_generator(root=root) + self.assertEqual(first.returncode, 0, first.stderr) + runner_copy = (root / RUNNER_OUTPUT).read_bytes() + helper_copy = (root / HELPER_OUTPUT).read_bytes() + second = run_generator(root=root) + self.assertEqual(second.returncode, 0, second.stderr) + self.assertEqual(runner_copy, (root / RUNNER_OUTPUT).read_bytes()) + self.assertEqual(helper_copy, (root / HELPER_OUTPUT).read_bytes()) + + def test_a_malformed_source_of_truth_fails_without_writing_anything(self) -> None: + """A broken policy must fail loudly, and must not leave a partial file. + + A generator that writes half a policy and exits zero is worse than one + that refuses: the half-written file would be compiled into a release. + """ + for corruption, description in ( + ("this is not toml = = =\n", "malformed TOML"), + ("schema_version = 99\n", "an unknown schema version"), + ): + with self.subTest(description=description): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / POLICY.parent).mkdir(parents=True) + (root / CORE.parent).mkdir(parents=True) + shutil.copyfile(REPOSITORY_ROOT / CORE, root / CORE) + (root / POLICY).write_text(corruption, encoding="utf-8") + result = run_generator(root=root) + self.assertNotEqual( + result.returncode, + 0, + f"{description} must fail the generator", + ) + self.assertFalse( + (root / RUNNER_OUTPUT).exists(), + f"{description} must not leave a partially written copy behind", + ) + self.assertFalse( + (root / HELPER_OUTPUT).exists(), + f"{description} must not leave a partially written copy behind", + ) + + def test_a_policy_whose_class_and_baseline_disagree_fails(self) -> None: + """The node-owned class and the node-owned baseline are one list. + + The generator refuses a source of truth in which they differ, because + the two are the same thing written twice and a disagreement means one + of them is wrong. + """ + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / POLICY.parent).mkdir(parents=True) + (root / CORE.parent).mkdir(parents=True) + shutil.copyfile(REPOSITORY_ROOT / CORE, root / CORE) + policy = (REPOSITORY_ROOT / POLICY).read_text(encoding="utf-8") + head, _, tail = policy.partition("[reserved]") + self.assertTrue(tail, "the policy must carry a [reserved] table") + broken = head + "[reserved]" + tail.replace( + ' "GIT_TERMINAL_PROMPT",\n', "", 1 + ) + self.assertNotEqual(broken, policy) + (root / POLICY).write_text(broken, encoding="utf-8") + result = run_generator(root=root) + self.assertNotEqual(result.returncode, 0) + self.assertIn("node-owned class", result.stderr) + + def test_the_helper_copy_carries_the_core_limits(self) -> None: + """The helper's copy of the five protocol limits comes from the owner. + + The helper cannot import `eggwork-core`, so the generator reads the + five values out of the owner of the wire limits. This test pins that + the values in the generated copy are the owner's values and not a + hand-maintained guess. + """ + helper = (REPOSITORY_ROOT / HELPER_OUTPUT).read_text(encoding="utf-8") + core = (REPOSITORY_ROOT / CORE).read_text(encoding="utf-8") + for name, value in ( + ("MAX_ARG_COUNT", "256"), + ("MAX_ARG_BYTES", "32768"), + ("MAX_ENV_COUNT", "256"), + ("MAX_ENV_NAME_BYTES", "256"), + ("MAX_ENV_VALUE_BYTES", "16384"), + ): + with self.subTest(limit=name): + self.assertIn(f"pub const {name}: usize = {value};", helper) + self.assertIn(f"pub const {name}: usize = ", core) + + +if __name__ == "__main__": + unittest.main() From b925003f5c8c8971950c5325d3266d8d834b5505 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 15:52:55 +0000 Subject: [PATCH 05/37] docs(plans): register M005a/M005b as implemented and apply coordinator-owned text Registry: Security M005a, Security M005b, and Workspace M005b are now registered as implemented with their closure-record pointers. The corrected execution graph and the batch table are updated to match. AGENTS.md invariant 4 now names the environment policy's single owner, as the Security M005b closure record recommends, so the runner and the sandbox helper cannot drift apart unnoticed. Workspace M005b's plan required non-vacuity evidence for a corrupt-principal case that cannot fail before the fix: the pre-fix inline format produced the identical composite, so the defect was duplication rather than a wrong release. The requirement is corrected to require the empirical result and the structural guard instead, rather than a claim that was never true. The workspace roadmap's M005b exit condition now names the store's verified-copy path, matching the implementation. --- AGENTS.md | 2 +- ...005b-gc-preview-and-store-ownership-corrective.md | 8 ++++++-- plans/registry.md | 12 ++++++------ .../workspace-artifact-transport-roadmap.md | 2 +- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 9c56bd6..62a8598 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -95,7 +95,7 @@ and deliberate. Deep dives: 1. **Process ownership is singular.** Only `eggwork-runner` and `eggwork-sandbox-helper` may create child processes; `eggwork-core`, `eggwork-client`, `eggwork-server` must not. Also banned outright: `command-group`, `duct`, `process-wrap`, `portable-pty`, `subprocess`. The allowlist lives in `scripts/check_execution_ownership.py`; adding an owner requires an architecture review. The guard scans only `crates/*/src/**/*.rs` — `tests/`, `examples/`, `build.rs`, and new top-level dirs are unscanned. The dependency denylist is the exception: every crate is checked against it, and the one recorded exemption is `eggwork-runner` → `process-wrap` (Windows Job Object ownership, `cfg(windows)` only), in `APPROVED_PROCESS_DEP_EXCEPTIONS`. 2. **No direct service-manager invocation for the *node service*.** Eggwork never manages its own service by shelling out — the node service lifecycle goes through Eggup adapters. **Exception, and it is not a violation:** `eggwork-runner` invokes `systemd-run --scope` and `systemctl show`/`stop` for *per-execution transient cgroup units*, which is resource enforcement owned by the process-lifecycle crate, not service lifecycle. A new `systemctl`-shaped call must pick a side and match the code to it. (No dedicated Python guard; the only automated check, `no_direct_service_manager_invocation_exists`, scans three `eggwork-server` files. `eggwork-runner` is not covered — discipline is on you.) 3. **Crate dependencies stay one-way.** core/helper → nothing; client → core; server → core + runner (`eggwork-client` is dev-only for the server). -4. **Isolation claims are earned.** Advertise filesystem isolation only when `verify_trusted_helper` accepts the installed helper; the same function backs capability advertisement, `doctor`, and admission. +4. **Isolation claims are earned.** Advertise filesystem isolation only when `verify_trusted_helper` accepts the installed helper; the same function backs capability advertisement, `doctor`, and admission. The node's environment policy has one owner — `crates/eggwork-runner/policy/environment-policy.toml` — generated into each crate and pinned by a parity test, so the runner and the sandbox helper cannot enforce different rules. 5. **Fail closed** on untrusted helper, version skew, missing prior-generation digest, unsupported service backend. Degrade only when the caller never demanded a guarantee, and always record `NotApplied`. 6. **No release identity in `release/eggpack/`** — no tag, source SHA, artifact digest, or size. 7. **`.github/workflows/release.yml` is generated** by `eggpack ci generate`. Never hand-edit; `eggpack ci check` fails on drift. diff --git a/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md b/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md index c0fb928..2a6f744 100644 --- a/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md +++ b/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md @@ -543,8 +543,12 @@ The record must distinguish code inspection from executed evidence and must incl reported, the set the apply pass removed, and the relation observed between them, with the subset relation stated explicitly and the equality case demonstrated separately; - the non-vacuity evidence for each new test, including how the digest-mismatch materializer case - was shown to fail before the fix and the corrupt-principal owner-id case was shown to fail - before the fix; + was shown to fail before the fix. For the corrupt-principal owner-id case, the pre-fix behaviour + must be established empirically rather than assumed: if the pre-fix inline format produced the + identical composite (the defect being duplication rather than a wrong released value), then the + closure record states that plainly and cites the structural guard that enforces the single + producer, instead of claiming a pre-fix failure that did not occur. A closure record must not + assert a failing-before-the-fix result it did not observe; - the **compatibility review**: an explicit statement that no wire shape and no stored format changed, with the performance consequence of the materializer change recorded; - the documentation status for `architecture/data-plane.md` and `architecture/operations-cli.md`, diff --git a/plans/registry.md b/plans/registry.md index 7f4fc98..706fe20 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -91,8 +91,8 @@ A repository-wide code interrogation pass over the reviewed baseline found no `t | Addendum | Milestones | Class | Status | |---|---|---|---| | `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | proposed | -| `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | proposed | -| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a implemented; M005b proposed; **M005c blocked on ADR-0007** | +| `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a proposed; M005b implemented | +| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a/M005b implemented; **M005c blocked on ADR-0007** | | `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | | `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | proposed | @@ -173,9 +173,9 @@ The repository interrogation corrective batch is registered but is **not** depen | Operations M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md`. Explicit `service-host --config` entry, shared shutdown+wait convergence, normal STOP does not create persistent drain, dedicated native Windows contract/SCM evidence, Eggup remains manager owner. Foundation M004 is already conditionally closed; the next immutable candidate should contain both for final M004 qualification. | | Control-plane M004 shared protocol contract corrective | **proposed** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. | | Workspace M005a declared-artifact capture fail-closed corrective | **proposed** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`. | -| Workspace M005b GC preview and store ownership corrective | **proposed** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass use different candidate predicates, in a module whose own doc comment states the two must be shared — a stated invariant already violated in the sibling module. Also covers the blob store's path layout and the manifest owner-id format being re-derived outside their owners. Addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`. | +| Workspace M005b GC preview and store ownership corrective | **implemented** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass used different candidate predicates, in a module whose own doc comment states the two must be shared. Implemented: the candidate predicate, the metadata filenames, and the blob path layout each have one owner; the preview reaches owner code through a read-only, non-reconciling seam (`blob::preview_gc`, `workspace::preview_gc`, `artifact::preview_gc`); the materializer verifies the bytes it writes against the manifest digest **while copying** (`BlobStore::copy_verified`); and the manifest owner-id composite has one producer with two entry points. Closure record: `plans/closure/workspace-artifact-transport/005b-status.md`. | | Security M005a degraded-isolation observability corrective | **implemented** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` was emitted only from test code, so a degraded best-effort isolation or resource enforcement was invisible to an event-streaming caller. Implemented: the runner emits a bounded diagnostic through its output channel **before the target spawns**, the server forwards it as `ExecutionEventKind::Diagnostic`, and the diagnostic grammar is owned by `eggwork-core` so producer and server share one definition. The diagnostic precedes the target's first output and the terminal event, is durable in the journal, and is emitted exactly once per degradation. The `Required` path is untouched. Closure record: `plans/closure/security-isolation-resource/005a-status.md`. | -| Security M005b sandbox-helper environment parity corrective | **proposed** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list is maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule has no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix must be a shared artifact plus a pinning test, not a shared crate. **This is the most severe finding in the batch.** The duplication is live: the runner's launch-spec builder starts from a fixed baseline (`PATH`, `LANG`, `LC_ALL`, `CI`, `NO_COLOR`, `TERM`, `GIT_TERMINAL_PROMPT`, `PAGER`) and then appends every non-denied caller key, and none of those baseline keys except `PATH` is denied. A caller that sets `LANG` therefore produces a launch specification with two `LANG` entries; the helper refuses a specification with duplicate keys with status 12; the runner reads that as a pre-target setup failure and — for a **best-effort** request only — rewrites the sandbox outcome to `NotApplied` and **re-spawns the target directly with no Landlock ruleset at all**. The observable result today is a successful, entirely unconfined execution whose only record of the degradation is a `NotApplied` in the terminal snapshot. The `Required` path is unaffected and still fails closed. Addendum: `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`. | +| Security M005b sandbox-helper environment parity corrective | **implemented** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list was maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule had no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix is a shared artifact plus a pinning test, not a shared crate. **This was the most severe finding in the batch**, and it was live: the runner's launch-spec builder started from a fixed baseline and appended every non-denied caller key, and none of those baseline keys except `PATH` was denied. A caller that set `LANG` produced a launch specification with two `LANG` entries; the helper refused it with status 12; the runner read that as a pre-target setup failure and — for a **best-effort** request only — rewrote the sandbox outcome to `NotApplied` and **re-spawned the target directly with no Landlock ruleset at all**. Implemented: the environment policy now has one checked-in source of truth (`crates/eggwork-runner/policy/environment-policy.toml`), a deterministic generator (`scripts/generate_environment_policy.py`), and generated copies in each crate; one builder serves both the direct and the helper launch path; the runner drops denied keys and lets the node's value win for node-owned keys; the helper refuses a policy violation with its own status byte, **13**, distinct from the general specification-validation status 12. The `Required` path is untouched and still fails closed. Closure record: `plans/closure/security-isolation-resource/005b-status.md`. | | Security M005c resource-scoped authorization corrective | **blocked** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. Blocked on ADR-0007 (`plans/adrs/ADR-0007-resource-scoped-authorization.md`, **proposed, not accepted**), which must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. The gap itself is already recorded as divergence #4; this is a decision about a known gap, not a new defect. | | Operations M008a operator surface truthfulness corrective | **proposed** | `plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md`. Five live metrics are incremented by the server and never reported by `eggworkd status`/`eggworkd metrics`; one `active_executions` field name carries two different meanings across the API and the CLI; and every configuration fault collapses into the single unhelpful message `configuration is invalid or unreadable`. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | | Operations M008b release harness and documentation single-sourcing corrective | **proposed** | `plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md`. The release harness re-derives the workspace version, the release asset inventory, the install identities, and the target classification that already have owners; the tag guard's own docstring deliberately keeps it out of CI, so the defect is the divergent parser and the absence of any automated exercise, not the missing CI wiring. Roughly 92% of the design record's line-number citations no longer point at the symbol they claim, every crate size figure in `architecture/overview.md` is stale, and divergence #20 now describes a fixed issue as open. CI type-checks feature-gated code it never executes — the qualification workflow is `workflow_dispatch`-only, so the suite runs on no ordinary pull request, and adding `--all-features` would not close the gap because those tests are `#[ignore]`d — while one runner test passes with zero assertions on the normal CI path. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | @@ -220,9 +220,9 @@ Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 auth Repository interrogation corrective batch [PROPOSED] --+--> Control-plane M004 shared protocol contract [PROPOSED] +--> Workspace M005a artifact capture fail-closed [PROPOSED] - +--> Workspace M005b GC preview and store ownership [PROPOSED] + +--> Workspace M005b GC preview and store ownership [IMPLEMENTED] +--> Security M005a degraded-isolation observability [IMPLEMENTED] - +--> Security M005b helper environment parity [PROPOSED] + +--> Security M005b helper environment parity [IMPLEMENTED] +--> Security M005c resource-scoped authorization [BLOCKED on ADR-0007] +--> Operations M008a operator surface truthfulness [PROPOSED] +--> Operations M008b release harness and docs single-sourcing [PROPOSED] diff --git a/plans/subsystems/workspace-artifact-transport-roadmap.md b/plans/subsystems/workspace-artifact-transport-roadmap.md index 5b276bd..51cf014 100644 --- a/plans/subsystems/workspace-artifact-transport-roadmap.md +++ b/plans/subsystems/workspace-artifact-transport-roadmap.md @@ -183,7 +183,7 @@ Exit conditions: - the dry-run report and the apply pass select candidates through the same store-owned statement; - the operator's blob inspection goes through the store's path and ownership API rather than re-deriving the shard layout; -- the workspace materializer uses the store's verified-open path; +- the workspace materializer uses the store's verified-copy path, so the verification is bound to the bytes actually copied; - the manifest owner-id composite has exactly one producer, and the two inlined call sites use it; - a test proves that the preview and the apply pass agree; - no public protocol surface and no stored format changes. From 1da739bde23ed02687769df7737879bd3d31f476 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 16:48:57 +0000 Subject: [PATCH 06/37] feat(control-plane): M004 shared protocol contract Three protocol contract facts were each stated by more than one owner, with the copies unrelated to each other. Both sides of every pair agreed by value today, so none of it was a live bug; the defect was structural, because a future rename or bump on the producing side desynchronised the consuming side silently and neither the compiler nor the test suite objected. eggwork-core now owns the control-plane API schema version, the exec.argv.v1 capability name, and the terminal/non-terminal classification of ExecutionState. The classification is an exhaustive match over all nine variants with no wildcard arm, so adding a tenth variant is three non-exhaustive-pattern errors in eggwork-core rather than a silent behaviour change downstream. The runner keeps producer ownership of the capability names it produces and of the sandbox profile name; the server imports the runner's constants rather than restating them. The artifact-capture eligibility predicate stays a distinct policy: exactly Succeeded and Failed, deliberately not the terminal set, now one named function with a doc comment saying why the two must not be folded together. No wire value, wire field, capability byte, stored format, or operator-visible output changed. The ownership change is recorded in plans/adrs/ADR-0008-core-protocol-contract-ownership.md. --- AGENTS.md | 1 + architecture/client-transport.md | 20 +- architecture/core-domain.md | 4 +- architecture/overview.md | 2 +- architecture/runner-execution.md | 14 +- architecture/server-node.md | 55 +- architecture/storage-journal.md | 55 +- crates/eggwork-client/src/lib.rs | 230 ++++++++- crates/eggwork-core/src/lib.rs | 105 +++- .../tests/shared_protocol_contract.rs | 160 ++++++ crates/eggwork-runner/src/lib.rs | 157 ++++-- .../eggwork-runner/tests/capability_probe.rs | 6 +- .../tests/landlock_runner.rs | 115 +++++ crates/eggwork-server/src/lib.rs | 485 +++++++++++++++--- crates/eggwork-server/src/operations.rs | 95 +++- crates/eggwork-server/src/store.rs | 139 +++-- .../tests/shared_contract_ownership.rs | 237 +++++++++ .../control-plane-protocol/004-status.md | 314 ++++++++++++ plans/registry.md | 9 +- .../control-plane-protocol-roadmap.md | 12 +- 20 files changed, 1959 insertions(+), 256 deletions(-) create mode 100644 crates/eggwork-core/tests/shared_protocol_contract.rs create mode 100644 crates/eggwork-server/tests/shared_contract_ownership.rs create mode 100644 plans/closure/control-plane-protocol/004-status.md diff --git a/AGENTS.md b/AGENTS.md index 62a8598..fba96c3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -101,6 +101,7 @@ and deliberate. Deep dives: 7. **`.github/workflows/release.yml` is generated** by `eggpack ci generate`. Never hand-edit; `eggpack ci check` fails on drift. 8. **Never set `RUSTFLAGS`/`CARGO_*RUSTFLAGS`** — the env would silently replace the target-scoped Windows link policy in `.cargo/config.toml` (`/BREPRO`, `/DEBUG:NONE`) that makes MSVC release binaries reproducible. 9. **Windows service management fails closed.** `deployment::windows_scm_manager` is retained but refuses before any mutation; daemon has no SCM dispatcher. +10. **Protocol contract facts have one owner.** The control-plane API schema version and the `exec.argv.v1` capability name are declared once, publicly, in `eggwork-core`; the runner owns the capability names it produces (`LANDLOCK_WORKSPACE_RW_CAPABILITY`, `CGROUPS_V2_{MEMORY,CPU,PIDS}_CAPABILITY`, `WORKSPACE_RW_PROFILE`); the terminal/non-terminal classification of `ExecutionState` is owned by `eggwork-core`'s `ExecutionState::is_terminal` / `is_non_terminal`. A second copy of any of these in an endpoint crate is a defect, not a convenience. See [ADR-0008](plans/adrs/ADR-0008-core-protocol-contract-ownership.md). ## Code style diff --git a/architecture/client-transport.md b/architecture/client-transport.md index dcba970..394bc4d 100644 --- a/architecture/client-transport.md +++ b/architecture/client-transport.md @@ -47,7 +47,9 @@ production graph is what stops client convenience from constraining server desig - Interpreting `NodeStatus` or `NodeCapabilities` into a decision. `capabilities()` and `status()` return the facts; the caller decides what they mean. The single exception is `ensure_protocol_compatible`, which rejects a node whose protocol range excludes `1.0` or which - does not advertise `exec.argv.v1` — a compatibility gate, not a placement policy. + does not advertise `eggwork_core::EXEC_ARGV_CAPABILITY` (`exec.argv.v1`) — a compatibility gate, + not a placement policy. The name is the core-owned constant rather than a literal, so the node's + advertisement and the client's demand cannot drift apart. - Node-side admission, process lifecycle, workspace/blob storage semantics, or event retention. - Principal identity. The client presents a certificate and nothing else; it never asserts who it is in a payload. @@ -283,9 +285,10 @@ call one. All request bodies except the blob PUT are produced by `serde_json::to_vec` with `content-type: application/json`; a serialization failure maps to `InvalidResponse`. The blob PUT uses `content-type: application/octet-stream` and a streamed `RequestBody`. The client sends -`schema_version: API_SCHEMA_VERSION` (`1`, `lib.rs:21`) in the execute, control, workspace-create, -and workspace-derive bodies — matching the server's own `API_SCHEMA_VERSION = 1` -(`crates/eggwork-server/src/lib.rs:48`). It is not sent in the two blob request bodies, whose +`schema_version: eggwork_core::API_SCHEMA_VERSION` (`1`) in the execute, control, workspace-create, +and workspace-derive bodies. That is the *same* constant the server compares the received value +against — one core-owned number, not a copy in each endpoint crate — so a bump cannot desynchronise +the producer and the consumer. It is not sent in the two blob request bodies, whose server counterparts do not declare one either. Server-side request structs are all `#[serde(deny_unknown_fields)]` (`ExecuteRequest`, @@ -394,7 +397,7 @@ makes a foreign base look *missing* (`409 base_manifest_missing`) rather than *f | `Api { status, code, message }` | `node returned HTTP {status}: {code}` | Any non-2xx response, typed by the node. | Depends entirely on `code` — the client takes no position. | `status`, node `code`, and node `message` as public fields. | | `InvalidResponse` | `node response was malformed` | Response did not match the expected contract (see below). | Caller's judgement; usually a hard stop for that response. | Nothing beyond the variant. | | `ProtocolIncompatible` | `node protocol is incompatible` | `ensure_protocol_compatible`: the node's `[min, max]` does not contain `1.0`. | No — retrying the same node cannot help. | Nothing; the node's actual range is not carried. | -| `UnsupportedCapability` | `node does not support a required protocol capability` | Node does not advertise `exec.argv.v1`. | No. | Nothing; the advertised feature list is not carried. | +| `UnsupportedCapability` | `node does not support a required protocol capability` | Node does not advertise `eggwork_core::EXEC_ARGV_CAPABILITY` (`exec.argv.v1`). | No. | Nothing; the advertised feature list is not carried. | | `TelemetryUnsupported` | `node does not implement the node telemetry contract` | `GET /v1/node/telemetry` answered 404: the node predates the contract. | No. | Nothing. | `InvalidResponse` is produced in every one of these situations: `serde_json::from_slice` failure on @@ -480,8 +483,11 @@ All three drive `EggressDialer` directly; none constructs a `NodeClient` or perf `event.validate()` rejection, or the trailing-partial-line tail. - No test for the response identity headers (execution-id mismatch, blob digest mismatch, artifact id/digest mismatch) in this file. -- No test for `ensure_protocol_compatible` rejecting an incompatible range or a missing - `exec.argv.v1`. +- `ensure_protocol_compatible`'s decision is separated from its fetch into `protocol_compatibility`, + so the rule is tested directly: a node advertising `eggwork_core::EXEC_ARGV_CAPABILITY` is + accepted, a node whose argv feature name differs by one character is refused with + `UnsupportedCapability`, and a node on another protocol version is refused with + `ProtocolIncompatible`. - `normalize_endpoint` is not tested against a fragment, a host-less URL, or a multi-slash trailing form. - No test that dropping an `ExecutionStream` leaves the execution running. diff --git a/architecture/core-domain.md b/architecture/core-domain.md index fe8e817..ffe02bd 100644 --- a/architecture/core-domain.md +++ b/architecture/core-domain.md @@ -240,7 +240,9 @@ Three separate post-execution channels are worth separating: `cleanup_warning` ( `ExecutionFinalizationFailure { ArtifactCapture, Retention }` (`lib.rs:931-935`) covers the case where the process finished but bookkeeping after it did not. Note it sits *inside* a result whose `state` is already terminal, and `cleanup_warning` can be set alongside it — consistent with ADR-0003's "cleanup diagnostics may be appended without changing the chosen terminal outcome". -**States.** `ExecutionState` (`lib.rs:878-889`) is a flat nine-variant enum: `Accepted`, `Preparing`, `Running`, `Cancelling`, `Succeeded`, `Failed`, `Cancelled`, `TimedOut`, `Interrupted`. There is no `is_terminal()` helper and no terminal-state grouping in this crate — the five terminal variants are a convention that the server applies. `Interrupted` is the conservative post-restart classification that per §27 must not imply safe automatic retry. +**States.** `ExecutionState` is a flat nine-variant enum: `Accepted`, `Preparing`, `Running`, `Cancelling`, `Succeeded`, `Failed`, `Cancelled`, `TimedOut`, `Interrupted`. Since [ADR-0008](../plans/adrs/ADR-0008-core-protocol-contract-ownership.md) this crate owns the terminal classification rather than leaving it to a server-side convention. `ExecutionState::is_terminal` and its complement `ExecutionState::is_non_terminal` are exhaustive `match`es over all nine variants with **no wildcard arm**, so a tenth variant is a compile error in this crate instead of a state every consumer silently classifies as still running. `ExecutionState::wire_name` is the canonical PascalCase spelling — the same string the derived `Serialize` emits, which is what keeps the journal's `state` column honest against the enum — and `ALL_EXECUTION_STATES` enumerates every variant so a property test can range over the enum instead of over a second hand-written list. The server consumes these; it keeps no copy of the set. `Interrupted` is the conservative post-restart classification that per §27 must not imply safe automatic retry. + +The crate also owns the control-plane facts that both endpoint crates used to state for themselves: `API_SCHEMA_VERSION` (the request/response schema version, frozen at 1) and `EXEC_ARGV_CAPABILITY` (the `exec.argv.v1` feature name the node advertises and the client requires). Both live here because the client and the server already depend on this crate and the client cannot depend on the server. The runner owns its own feature names — `LANDLOCK_WORKSPACE_RW_CAPABILITY`, the three `CGROUPS_V2_*_CAPABILITY` names, and `WORKSPACE_RW_PROFILE` — because the runner produces them and the server consumes them. ### `SandboxResult` and `ResourceResult` diff --git a/architecture/overview.md b/architecture/overview.md index 2ce8fdc..3046074 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -185,7 +185,7 @@ None of these are presented as bugs already judged to be bugs. They are the plac | # | Observation | Where | |---|---|---| | 11 | **No schema version or migration path.** Only `CREATE TABLE IF NOT EXISTS`; no `PRAGMA user_version`. `ExecutionSnapshot.schema_version` lives inside the JSON and is never validated on read. | [storage-journal.md](storage-journal.md) | -| 12 | The store **does not enforce the state machine.** `commit_event` accepts any non-terminal → non-terminal transition; all legality lives in `publish`. The terminal/non-terminal sets are spelled out in four places with nothing keeping them in sync. | [storage-journal.md](storage-journal.md) | +| 12 | The store **does not enforce the state machine.** `commit_event` accepts any non-terminal → non-terminal transition; all legality lives in `publish`. The terminal/non-terminal *classification* is now spelled out in one place — `eggwork-core`'s `ExecutionState::is_terminal` / `is_non_terminal` — and the server's queries and predicates derive from it, so the sets can no longer drift apart; the *legality* of a transition is still enforced nowhere but `publish`. | [storage-journal.md](storage-journal.md) | | 13 | **Unchecked `u64 → i64` narrowing.** `ExecutionGeneration::new` rejects only `0`, yet the store casts `generation.get() as i64` in **eleven** places (the deep dive previously said six). Same class of issue for `after_sequence as i64` in `load_page`, guarded only at the HTTP route. | [storage-journal.md](storage-journal.md) | | 14 | `load_page` has **no `LIMIT`** and is not a consistent read — three separate autocommit statements, bounded only indirectly. | [storage-journal.md](storage-journal.md) | | 15 | `MAX_EXECUTION_IDENTITIES` counts `(id, generation)` rows rather than identities and **never evicts**, so it is a permanent 503 after the cap. | [storage-journal.md](storage-journal.md) | diff --git a/architecture/runner-execution.md b/architecture/runner-execution.md index aae9040..cb55bee 100644 --- a/architecture/runner-execution.md +++ b/architecture/runner-execution.md @@ -81,7 +81,7 @@ pub fn from_spec( It runs `spec.validate()` first and maps a `ValidationError` to `RunnerError::InvalidRequest(e.to_string())`. Only then does it clone and destructure `spec.command`, so a spec that is invalid at the domain layer never becomes a runner request. The mapping is otherwise mechanical, with two decisions worth naming: -- **Isolation becomes a profile string.** `IsolationRequirement::None → SandboxRequest::None`, `BestEffort → BestEffort { profile: "workspace_rw" }`, `Required → Required { profile: "workspace_rw" }`. `workspace_rw` is therefore the only profile the protocol can request; the runner independently rejects anything else as `"unsupported sandbox profile"`. +- **Isolation becomes a profile string.** `IsolationRequirement::None → SandboxRequest::None`, `BestEffort → BestEffort { profile: WORKSPACE_RW_PROFILE }`, `Required → Required { profile: WORKSPACE_RW_PROFILE }`. `WORKSPACE_RW_PROFILE` (`"workspace_rw"`) is therefore the only profile the protocol can request; the runner independently rejects anything else as `"unsupported sandbox profile"`. The name is an exported constant rather than a literal, because the trusted helper is a standalone binary that keeps its own copy of the spelling — the helper's test pins the two together. - **Everything the runner does not own is dropped.** The destructure binds `argv, cwd, environment, stdin, timeout_millis, output, resources, isolation, ..` — so `declared_outputs` and `network` are discarded by construction, not by later ignoring. `RunnerRequest::validate` still runs at `run`, so `from_spec` validation is a fail-fast convenience layered on top of the enforcement point, not a replacement for it. @@ -124,13 +124,15 @@ Only `prepare` is required. `execution_capabilities` and `sandbox_helper_path` a 1. **Probe OS resource controls.** If `resources.is_requested()`, call `SystemdCgroupBackend::probe`. Success yields `ResourceSetupOutcome::Applied { backend: "systemd-cgroup-v2" }`; failure yields `NotApplied { reason }`, or `Err(RunnerError::Setup(reason))` when `resources.has_required()`. No request yields `NotRequested`. 2. **Downgrade resources if the helper is untrusted.** If resources came back `Applied` *and* `verify_trusted_helper` fails, the resource outcome is downgraded to `NotApplied { reason }` (or the required case errors). This coupling is real: on Linux the helper is also the cgroup path (it self-applies `rlimit`s and reports limit breaches over the status socket), so advertising systemd limits while the helper is untrusted would be a claim the enforcement path cannot keep. -3. **Resolve the sandbox profile.** `None → NotRequested`. A profile other than `workspace_rw` → `NotApplied` for `BestEffort`, `Err(Setup)` for `Required`. Otherwise `verify_trusted_helper` decides: `Applied { profile }`, `NotApplied { reason }` for `BestEffort`, `Err(Setup)` for `Required`. +3. **Resolve the sandbox profile.** `None → NotRequested`. A profile other than `WORKSPACE_RW_PROFILE` → `NotApplied` for `BestEffort`, `Err(Setup)` for `Required`. Otherwise `verify_trusted_helper` decides: `Applied { profile }`, `NotApplied { reason }` for `BestEffort`, `Err(Setup)` for `Required`. -`TrustedLandlockSetup::execution_capabilities` (line 482) is where capability advertisement is earned. It pushes `LANDLOCK_WORKSPACE_RW_CAPABILITY` (`"isolation.landlock.workspace-rw.v1"`, line 528) only when `verify_trusted_helper(...).is_ok() && probe_landlock_ruleset()`. `probe_landlock_ruleset` (line 538) builds an in-process Landlock **ABI V4** ruleset with `AccessFs::from_all(abi)`, `create()`s it, and adds `PathBeneath` rules over `/usr`, `/etc/ld.so.cache`, `/etc/ssl/certs`, `/dev/null` with the *same* access masks the helper uses — directories get `from_read | Execute`, `/dev/null` gets `ReadFile | WriteFile`, other files get `ReadFile`. It deliberately never calls `restrict_self`, so the probe process is not confined; it proves the kernel supports the precise rights, nothing more. Every failure folds to `false`. It then runs three independent `SystemdCgroupBackend::probe` calls and, for each success, adds `resources.cgroups-v2.memory`, `resources.cgroups-v2.cpu`, or `resources.cgroups-v2.pids`. +`TrustedLandlockSetup::execution_capabilities` is where capability advertisement is earned. It pushes `LANDLOCK_WORKSPACE_RW_CAPABILITY` (`"isolation.landlock.workspace-rw.v1"`) only when `verify_trusted_helper(...).is_ok() && probe_landlock_ruleset()`. `probe_landlock_ruleset` builds an in-process Landlock **ABI V4** ruleset with `AccessFs::from_all(abi)`, `create()`s it, and adds `PathBeneath` rules over `/usr`, `/etc/ld.so.cache`, `/etc/ssl/certs`, `/dev/null` with the *same* access masks the helper uses — directories get `from_read | Execute`, `/dev/null` gets `ReadFile | WriteFile`, other files get `ReadFile`. It deliberately never calls `restrict_self`, so the probe process is not confined; it proves the kernel supports the precise rights, nothing more. Every failure folds to `false`. It then runs three independent `SystemdCgroupBackend::probe` calls and, for each success, adds `CGROUPS_V2_MEMORY_CAPABILITY` (`resources.cgroups-v2.memory`), `CGROUPS_V2_CPU_CAPABILITY` (`resources.cgroups-v2.cpu`), or `CGROUPS_V2_PIDS_CAPABILITY` (`resources.cgroups-v2.pids`). -**How the helper argv is composed.** `SandboxChannel::new` (line 1669) decides whether the helper is used at all. It accepts a profile when the request is `BestEffort`/`Required` with `workspace_rw`, or accepts `None` when `SandboxRequest::None` coincides with a resource request (helper-for-resources-only); anything else is `Err(Setup("unsupported sandbox profile"))`. Then: +**Every feature name this crate advertises is an exported constant.** `LANDLOCK_WORKSPACE_RW_CAPABILITY`, the three `CGROUPS_V2_*_CAPABILITY` names, and `WORKSPACE_RW_PROFILE` are the crate's public surface for those bytes; the advertisement site names the constants and no literal. The node's server consumes the same constants, so the producer of a feature name and its consumer cannot drift apart — a name that differed by one character would turn every required resource dimension into a `capability_mismatch` refusal. The values themselves are frozen and pinned by `capability_feature_string_is_frozen_for_workspace_rw_profile`, `cgroup_capability_feature_strings_are_frozen`, and `the_workspace_rw_profile_name_is_frozen`. -- A `tempfile::Builder::new().prefix("eggwork-sandbox-").tempdir()` is created and chmod-ed to `0700` (line 1691). +**How the helper argv is composed.** `SandboxChannel::new` decides whether the helper is used at all. It accepts a profile when the request is `BestEffort`/`Required` with `WORKSPACE_RW_PROFILE`, or accepts `None` when `SandboxRequest::None` coincides with a resource request (helper-for-resources-only); anything else is `Err(Setup("unsupported sandbox profile"))`. Then: + +- A `tempfile::Builder::new().prefix("eggwork-sandbox-").tempdir()` is created and chmod-ed to `0700`. - `spec.json` and `status.sock` are named inside it; a `tokio::net::UnixListener` is bound to `status.sock`. **The runner is the socket server and the helper connects to it** — the target never has the socket. - The launch environment is rebuilt from scratch by the same `build_child_environment` the direct path uses: the node's baseline (`PATH=/usr/bin:/bin`, `LANG=C.UTF-8`, `LC_ALL=C.UTF-8`, `CI=1`, `NO_COLOR=1`, `TERM=dumb`, `GIT_TERMINAL_PROMPT=0`, `PAGER=cat`), then the request's environment with denied keys dropped and node-owned keys replaced by the node's values, then `EGGWORK_EXECUTION_ID` and `EGGWORK_EXECUTION_GENERATION` when provenance carries them. Sharing the builder is what stops the two launch paths from disagreeing. - `SandboxLaunchSpec { schema_version: 1, profile, root, cwd, argv, environment, resource_memory_bytes, resource_cpu_millis, resource_pids }` is serialized with `serde_json` and rejected above 1 MiB. The three resource fields are populated only when `resources_applied`, using `.then_some(...).flatten()` so a `NotRequested` dimension stays `None`. @@ -149,7 +151,7 @@ Only `prepare` is required. `execution_capabilities` and `sandbox_helper_path` a Cancellation is checked before the accept and before each status read, so a cancel arriving during the handshake cannot produce a target. The third status byte is read later, after the child exits, by `SandboxSession::resource_limits_exceeded` (line 1633) with a 2 s timeout: bit 1 → `ResourceDimension::Memory`, bit 2 → `ResourceDimension::Pids`. -**What `LANDLOCK_WORKSPACE_RW_CAPABILITY` means.** The constant is the frozen public feature name for the *closed* `workspace_rw` Landlock profile used by both `IsolationRequirement::BestEffort` and `IsolationRequirement::Required`. It is not a version of Landlock itself and not a claim about rlimits — it is a single feature identifier pinned so that a node's advertised feature list and the runner's enforcement decision refer to the same contract. It is asserted literally in `capability_feature_string_is_frozen_for_workspace_rw_profile` so a rename cannot silently break wire compatibility. +**What `LANDLOCK_WORKSPACE_RW_CAPABILITY` means.** The constant is the frozen public feature name for the *closed* `workspace_rw` Landlock profile used by both `IsolationRequirement::BestEffort` and `IsolationRequirement::Required`. It is not a version of Landlock itself and not a claim about rlimits — it is a single feature identifier pinned so that a node's advertised feature list and the runner's enforcement decision refer to the same contract. It is asserted literally in `capability_feature_string_is_frozen_for_workspace_rw_profile` so a rename cannot silently break wire compatibility, and it is the same constant the server's `check_isolation_supported` compares against — the runner produces it, the server consumes it, and neither re-types it. ### `NoExecutionSetup` diff --git a/architecture/server-node.md b/architecture/server-node.md index 9eebd47..dc5fc0c 100644 --- a/architecture/server-node.md +++ b/architecture/server-node.md @@ -101,11 +101,13 @@ SQLite journal and the same drain marker. 12. Build the server, `start_with_service(NodeHttpService)`, then `handle.ready().await` so a successful `start` means the listener is live, not merely scheduled. -**Capabilities are derived once, at start.** `static_capability_features()` (`lib.rs:563-578`) is a -fixed list of protocol/transport/workspace/artifact features plus `network.unrestricted.v1`. -`server_capability_features` (`lib.rs:583-592`) merges the runner-reported dynamic features, then +**Capabilities are derived once, at start.** `static_capability_features()` is a +fixed list of protocol/transport/workspace/artifact features plus `network.unrestricted.v1`. The +argv feature in that list is `eggwork_core::EXEC_ARGV_CAPABILITY` (`exec.argv.v1`) — the core-owned +constant the client also demands, so the advertised name and the demanded name are one fact. +`server_capability_features` merges the runner-reported dynamic features, then sorts and dedups. Both `Route::Capabilities` and `node_status().capabilities` route through -`node_capabilities_for` (`lib.rs:595-604`) — the doc comment at `lib.rs:580-582` states this MUST +`node_capabilities_for` — its doc comment states this MUST stay true so a node never reports two different answers to the same question. `node_capabilities_for` also hard-pins the protocol range to `{1.0 … 1.0}`. @@ -326,18 +328,22 @@ fail-fast checks followed by a non-blocking permit acquisition. `IsolationRequirement` mirrors it as `None | BestEffort | Required` (`eggwork-core/src/lib.rs:446`). The node treats them as follows: -- `check_isolation_supported` (`lib.rs:606-618`): `None` and `BestEffort` are *always* accepted; +- `check_isolation_supported`: `None` and `BestEffort` are *always* accepted; only `Required` demands `eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY` - (`isolation.landlock.workspace-rw.v1`). Best-effort is permitted to degrade at run time, which + (`isolation.landlock.workspace-rw.v1`). The name is the runner's exported constant rather than a + literal, so the producer of the feature name and its consumer cannot drift apart. Best-effort is + permitted to degrade at run time, which `failed_result` reports honestly as `SandboxResult::NotApplied { reason: "best-effort sandbox - setup was unavailable" }` (`lib.rs:2542-2544`). -- `check_resources_supported` (`lib.rs:620-634`): each of `memory_bytes`/`cpu_millis`/`pids` gates + setup was unavailable" }`. +- `check_resources_supported`: each of `memory_bytes`/`cpu_millis`/`pids` gates on `matches!(requirement, Requirement::Required(_))` only; `Required` requires the corresponding - `resources.cgroups-v2.{memory,cpu,pids}` feature. `failed_result::requested` (`lib.rs:2521-2528`) - then reports any non-`NotRequested` dimension as `NotApplied { reason: "requested resource + `eggwork_runner::CGROUPS_V2_MEMORY_CAPABILITY`, `CGROUPS_V2_CPU_CAPABILITY`, or + `CGROUPS_V2_PIDS_CAPABILITY` (`resources.cgroups-v2.{memory,cpu,pids}`) — again the runner's + exported constants, not names re-typed here. `failed_result::requested` then reports any + non-`NotRequested` dimension as `NotApplied { reason: "requested resource enforcement failed before execution" }` — never as "applied". -- `check_network_supported` (`lib.rs:636-638`): accepts `NetworkRequirement::Unrestricted` only. - The `static_capability_features` doc comment (`lib.rs:558-562`) is explicit that this is a +- `check_network_supported`: accepts `NetworkRequirement::Unrestricted` only. + The `static_capability_features` doc comment is explicit that this is a deliberate refusal to fake capability: Eggwork has no network-restriction backend, so the node advertises `network.unrestricted.v1` and the gate rejects `Disabled`/`AllowListed` with `capability_mismatch` rather than silently downgrading. The alternative would be advertising @@ -346,13 +352,14 @@ The node treats them as follows: `Required` is therefore a *refusal* signal, not a degradation signal: no request whose enforcement would be skipped is ever admitted. The invariant to hold is: **a node never advertises a capability its enforcement path would refuse.** It is enforced structurally by deriving the advertised set from -`runner.execution_capabilities()` at start (`lib.rs:351-352`) rather than configuring it by hand, -and it is pinned by `static_capability_features_do_not_advertise_unsupported_network_modes` -(`lib.rs:5704`), `admission_helpers_keep_required_capability_gating_active` (`lib.rs:5719`), -`required_landlock_rejects_with_capability_mismatch_when_helper_is_missing` (`lib.rs:4998`), -`required_resource_admission_rejects_with_capability_mismatch_when_dimension_unavailable` -(`lib.rs:5144`), and `disabled_or_allowlisted_network_requests_are_rejected_with_capability_mismatch` -(`lib.rs:5355`). +`runner.execution_capabilities()` at start rather than configuring it by hand, +and it is pinned by `static_capability_features_do_not_advertise_unsupported_network_modes`, +`admission_helpers_keep_required_capability_gating_active`, +`required_landlock_rejects_with_capability_mismatch_when_helper_is_missing`, +`required_resource_admission_rejects_with_capability_mismatch_when_dimension_unavailable`, +`disabled_or_allowlisted_network_requests_are_rejected_with_capability_mismatch`, and +`the_resource_admission_rule_reads_the_runner_constants` — the last of which refuses a required +dimension whose advertised feature name differs from the runner's constant by one character. **What the caller learns.** Acceptance is `202 Accepted` — an `application/x-ndjson` event stream from `event_response(state, id, generation, 0, record)` (`lib.rs:1883`) that begins with the @@ -889,9 +896,9 @@ echoes its address: a node whose provider happens to be down is still a healthy | Only a transport-verified, known peer is admitted | `authenticated_principal` (`lib.rs:823-833`) | `request_payload_cannot_supply_authoritative_principal` (2993), `mtls_execution_streams_output_and_missing_certificate_is_rejected` (3724) | | Identity is the SHA-256 of the leaf DER, nothing else | `FingerprintPrincipalResolver::fingerprint` (`lib.rs:107-109`) | `fingerprint_mapping_uses_leaf_der_only` (2924) | | TLS must require client auth and a server identity | `NodeServer::start` (`lib.rs:307-311`) | `mtls_authorization_and_fixed_target_execution` (3137) | -| A node never advertises an unenforceable capability | `server_capability_features` / `check_*_supported` (`lib.rs:583`, `606`, `620`, `636`) | `static_capability_features_do_not_advertise_unsupported_network_modes` (5704), `admission_helpers_keep_required_capability_gating_active` (5719) | +| A node never advertises an unenforceable capability | `server_capability_features` / `check_isolation_supported` / `check_resources_supported` / `check_network_supported` | `static_capability_features_do_not_advertise_unsupported_network_modes`, `admission_helpers_keep_required_capability_gating_active`, `the_resource_admission_rule_reads_the_runner_constants` | | Capabilities and status never disagree | single `node_capabilities_for` (`lib.rs:595`, `580-582`) | `capabilities_and_status_features_agree_with_a_unified_snapshot` (4617) | -| The feature list is single-canonical and deduped | `static_capability_features` + sort/dedup (`lib.rs:563`, `583`) | `static_capability_features_are_a_single_canonical_list` (5667), `server_capability_features_do_not_duplicate_static_dynamic_overlap` (5682) | +| The feature list is single-canonical and deduped | `static_capability_features` + sort/dedup | `static_capability_features_are_a_single_canonical_list`, `server_capability_features_do_not_duplicate_static_dynamic_overlap`, `the_advertised_argv_feature_is_the_one_the_owner_declares` | | Only the fixed, versioned route set exists | `operation_for` (`lib.rs:640-700`) | `route_contract_is_fixed_target_and_versioned` (2934) | | An authorized op on a different resource is still denied | `authorize_resource` re-checks (`lib.rs:808`, `928`, `983`, `1038`, `1159`, `1518`) | `resource_aware_authorizer_can_scope_blob_capability` (3039), `derived_workspace_denied_and_oversized_bodies_are_typed` (4499) | | A repeat submit never starts a second execution | `store.lookup` pre-check + `ReserveResult::Existing` (`lib.rs:1664`, `1793`) | `blob_protocol_streams_verifies_deduplicates_and_enforces_quota` (3399) | @@ -1051,5 +1058,7 @@ Decision record consulted for idempotency, leases, and fencing: Source anchors in this file: `crates/eggwork-server/src/lib.rs`; sibling `crates/eggwork-server/src/operations.rs` (`GrantAuthorizer`, `principals`, `operation`); `crates/eggwork-core/src/lib.rs` (`Requirement`, `IsolationRequirement`, `NetworkRequirement`, -`request_digest_with_workspace`, `MAX_ID_BYTES`); `crates/eggwork-runner/src/lib.rs` -(`LANDLOCK_WORKSPACE_RW_CAPABILITY`). +`request_digest_with_workspace`, `MAX_ID_BYTES`, `API_SCHEMA_VERSION`, `EXEC_ARGV_CAPABILITY`); +`crates/eggwork-runner/src/lib.rs` +(`LANDLOCK_WORKSPACE_RW_CAPABILITY`, `CGROUPS_V2_MEMORY_CAPABILITY`, `CGROUPS_V2_CPU_CAPABILITY`, +`CGROUPS_V2_PIDS_CAPABILITY`). diff --git a/architecture/storage-journal.md b/architecture/storage-journal.md index 2269aca..9ab94f0 100644 --- a/architecture/storage-journal.md +++ b/architecture/storage-journal.md @@ -58,10 +58,13 @@ PRAGMA foreign_keys=ON; ``` There is no `PRAGMA user_version` read or write, and no `schema_version` column. -`ExecutionSnapshot.schema_version` (`eggwork-core/src/lib.rs:1117-1123`) is -*inside* the JSON blob, is set to `API_SCHEMA_VERSION` (`1`, `lib.rs:48`) at +`ExecutionSnapshot.schema_version` is +*inside* the JSON blob, is set to `eggwork_core::API_SCHEMA_VERSION` (`1`) at construction, and is not validated on read — `serde_json::from_slice` will -deserialize any `u16` into it. +deserialize any `u16` into it. That constant is core-owned: the server, the +client, and the snapshot all read the same number from +`eggwork_core::API_SCHEMA_VERSION`, so the value that is stored is the value +the node accepts. On a version mismatch there is no explicit handling: a database whose `executions` table lacks a column the current DDL expects fails at first @@ -307,17 +310,20 @@ lease state; the store only supplies the durable deadline. ## State machine persistence -`ExecutionState` (`eggwork-core/src/lib.rs:878-887`) has nine variants. -`state_name` (`store.rs:644-656`) maps each to its SQLite spelling verbatim -(`Accepted`, `Preparing`, `Running`, `Cancelling`, `Succeeded`, `Failed`, -`Cancelled`, `TimedOut`, `Interrupted`) and `is_terminal_name` (`store.rs:658-663`) -recognizes the last five. +`ExecutionState` has nine variants. Its SQLite spelling and its terminal +classification are both **core-owned**: `ExecutionState::wire_name` is the +PascalCase spelling the column stores verbatim (`Accepted`, `Preparing`, +`Running`, `Cancelling`, `Succeeded`, `Failed`, `Cancelled`, `TimedOut`, +`Interrupted`), and `ExecutionState::is_terminal` recognizes the last five. +The store no longer keeps a list of either; it asks the core for both. The +spellings are also the strings the derived `Serialize` emits, so the column +cannot drift away from the enum. In-memory `ExecutionSnapshot` (`{ schema_version, execution_id, generation, state, result: Option }`) is serialized whole into `snapshot_json`; the `state` column is written from the *caller's* proposed -snapshot via `state_name(&snapshot.state)`, never from the row that was read -back (`store.rs:326-337`). So the stored snapshot and the stored state column +snapshot via `ExecutionState::wire_name`, never from the row that was read +back. So the stored snapshot and the stored state column are always consistent with each other by construction. ### Which transitions the store actually enforces @@ -325,7 +331,7 @@ are always consistent with each other by construction. `store.rs` enforces only three things, all as *predicates*, not a state machine: 1. **No mutation after terminal** — `commit_event` returns `Ok(None)` if the - stored `state` `is_terminal_name` (`store.rs:310-313`); `update_lease` + stored `state` is terminal under `ExecutionState::is_terminal`; `update_lease` returns `None` on a terminal row; `reserve` requires the previous generation to be terminal before advancing. 2. **Generation ordering** as described above. @@ -347,18 +353,19 @@ only production writer. The sequence it actually produces: | output chunks | `run_execution` → `publish` | `Running` (re-asserted) | `Stdout`/`Stderr`/`Diagnostic` | interleaved, each consuming one sequence | | outcome | `run_execution` → `publish_terminal` | terminal + `result` | `State(terminal)` | last | -`Preparing` is never written by the server; it exists in `state_name`, in -`recover()`'s `IN` list, and in the `operations.rs` active filters, so a +`Preparing` is never written by the server; it exists in the core-owned +non-terminal set, and therefore in `recover()`'s `IN` list and in the +`operations.rs` active filters, so a hand-seeded or future row can carry it. ### Terminal state is recorded exactly once Two independent guards, in order: `publish` takes `record.snapshot.write()` and -returns early if the in-memory state `is_terminal` (`lib.rs:2575-2578`); then +returns early if the in-memory state `is_terminal()`; then `commit_event` re-reads the stored `state` inside the transaction and returns -`Ok(None)` if it is terminal (`store.rs:306-313`), rolling back, with `publish` +`Ok(None)` if it is terminal, rolling back, with `publish` treating `Ok(None)` as "already terminal — do not touch memory, do not -broadcast". +broadcast". Both guards ask the same core-owned classification. The terminal `UPDATE` of `executions.state`/`snapshot_json` and the `INSERT` of the terminal event are the **same `Immediate` transaction** @@ -410,7 +417,7 @@ EventMetadata { fields: vec![] } }` - metadata is always empty, the store never accepts caller-supplied metadata; (3) `event.validate()`, then `serde_json::to_vec`, rejecting `encoded.len() > MAX_RETAINED_EVENT_BYTES` with `StoreError::InvalidEvent` (the transaction is dropped, i.e. rolled back); -(4) `UPDATE executions SET state = state_name(&snapshot.state), next_sequence = +(4) `UPDATE executions SET state = , next_sequence = sequence + 1, snapshot_json = to_vec(&snapshot), updated_unix_ms = now`; (5) `INSERT INTO execution_events (execution_id, generation, sequence, encoded)`; (6) `trim_events`; (7) `commit`, returning `Some(event)`. The event is broadcast @@ -756,7 +763,7 @@ individually atomic, so a multi-row snapshot can straddle a commit. | Only the lease holder may renew or cancel | `update_lease` `current_hash != lease_token_hash => None` plus `UPDATE … AND lease_token_hash = ?3`; `control` compares `existing.lease_token_hash` and `record.lease_hash` | `cross_principal_execution_fencing_without_lease_oracle` | | Renewal is idempotent and never double-extends | `last_renewal_id == Some(renewal_id) => return current_expiry`; `expires = current_expiry.max(requested)` (`store.rs:383-387`) | `lease_renewal_replay_is_idempotent` | | An expired lease cannot be renewed | `current_expiry <= unix_millis() => None` (`store.rs:378`) | `expired_lease_terminates_process_with_a_typed_terminal_result`; in-memory mirror at `lib.rs:2117-2124, 2154-2161` | -| Terminal state is single-assignment | `commit_event` `is_terminal_name(&state) => rollback, Ok(None)`; `publish`'s in-memory `is_terminal` early return | repeated-cancel case in the lifecycle integration test (one `Cancelling`, one `Cancelled`) | +| Terminal state is single-assignment | `commit_event`'s `ExecutionState::is_terminal` check `=> rollback, Ok(None)`; `publish`'s in-memory `is_terminal()` early return | repeated-cancel case in the lifecycle integration test (one `Cancelling`, one `Cancelled`) | | State and its event commit atomically | one `Immediate` transaction around `UPDATE` + `INSERT` (`store.rs:294-344`) | `recovery_marks_uncertain_work_interrupted_and_never_replays_it` (asserts the appended event and the advanced sequence) | | Event sequences are gap-free within a generation | read `next_sequence` + write `next_sequence = sequence + 1` in one `Immediate` transaction; `PRIMARY KEY (id, gen, sequence)` | `recovery_...` asserts `events[2].sequence.get() == 3`; `event_journal_trims_...` asserts the retained head equals `base_sequence` | | Events are scoped to a generation | `load_page` filters on `execution_id` **and** `generation` | `event_journal_trims_by_count_and_bytes_with_explicit_base_cursor` | @@ -839,11 +846,13 @@ Honest gaps: process — confirm that invariant is never relaxed. - **The state machine is not enforced by the store.** `commit_event` accepts any non-terminal → non-terminal transition; all legality lives in `publish` and - its callers, so a new call site could persist an illegal transition. Compounding - this, the nonterminal/terminal sets are spelled out in at least four places — - `store::is_terminal_name`, `recover()`'s SQL `IN` list, `lib.rs::is_terminal`, - and the `operations.rs` active filters — with nothing enforcing agreement when - a state variant is added. + its callers, so a new call site could persist an illegal transition. The + nonterminal/terminal *classification* itself is no longer duplicated: since + ADR-0008 it is owned by `eggwork-core`'s `ExecutionState::is_terminal` / + `is_non_terminal`, and `store::stored_state_is_terminal`, + `recover()`'s SQL `IN` list, and the `operations.rs` active filters all + derive from it, so adding a state variant cannot make them disagree. What + remains unenforced is the *legality* of a transition, not the vocabulary. - **Unchecked integer narrowing.** `ExecutionGeneration::new` only rejects `0` (`eggwork-core/src/lib.rs:113-120`), yet the store does `snapshot.generation.get() as i64` in **eleven** places (an earlier revision of this diff --git a/crates/eggwork-client/src/lib.rs b/crates/eggwork-client/src/lib.rs index d62a4a6..6e05604 100644 --- a/crates/eggwork-client/src/lib.rs +++ b/crates/eggwork-client/src/lib.rs @@ -7,9 +7,10 @@ use eggfetch_core::{ BoxBytesStream, Client as HttpClient, Error as HttpError, RequestBody, TlsConfig, }; use eggwork_core::{ - ApiError, ArtifactId, ArtifactRecord, BlobDigest, ExecutionEvent, ExecutionHandle, ExecutionId, - ExecutionSnapshot, ExecutionSpec, NodeCapabilities, NodeId, NodeStatus, NodeTelemetry, - WorkspaceId, WorkspaceManifest, WorkspaceManifestPatch, + API_SCHEMA_VERSION, ApiError, ArtifactId, ArtifactRecord, BlobDigest, EXEC_ARGV_CAPABILITY, + ExecutionEvent, ExecutionHandle, ExecutionId, ExecutionSnapshot, ExecutionSpec, + NodeCapabilities, NodeId, NodeStatus, NodeTelemetry, WorkspaceId, WorkspaceManifest, + WorkspaceManifestPatch, }; use futures_util::{StreamExt, stream}; use serde::{Serialize, de::DeserializeOwned}; @@ -18,8 +19,6 @@ use std::sync::Arc; use std::{fmt, path::Path}; use thiserror::Error; -const API_SCHEMA_VERSION: u16 = 1; - /// Ceiling on a buffered (non-streamed) response body. /// /// Every non-2xx response goes through `api_error`, and every JSON reply @@ -356,20 +355,7 @@ impl NodeClient { async fn ensure_protocol_compatible(&self) -> Result<(), ClientError> { let capabilities = self.capabilities().await?; - let required = eggwork_core::ProtocolVersion { major: 1, minor: 0 }; - let supported = - capabilities.protocol.min <= required && capabilities.protocol.max >= required; - if !supported { - return Err(ClientError::ProtocolIncompatible); - } - if !capabilities - .features - .iter() - .any(|feature| feature == "exec.argv.v1") - { - return Err(ClientError::UnsupportedCapability); - } - Ok(()) + protocol_compatibility(&capabilities) } pub async fn create_workspace( @@ -818,6 +804,30 @@ impl ExecutionStream { } } +/// Decide whether a node's advertised capabilities are usable by this client. +/// +/// The decision is separated from the fetch so the rule can be tested without +/// a live node, and so the rule names the *owned* constants rather than +/// literals: the protocol range the client speaks, and the argv feature the +/// client cannot work without. A node that advertises a different argv +/// feature name is refused with the typed unsupported-capability error rather +/// than being talked to in a dialect this client does not implement. +fn protocol_compatibility(capabilities: &NodeCapabilities) -> Result<(), ClientError> { + let required = eggwork_core::ProtocolVersion { major: 1, minor: 0 }; + let supported = capabilities.protocol.min <= required && capabilities.protocol.max >= required; + if !supported { + return Err(ClientError::ProtocolIncompatible); + } + if !capabilities + .features + .iter() + .any(|feature| feature == EXEC_ARGV_CAPABILITY) + { + return Err(ClientError::UnsupportedCapability); + } + Ok(()) +} + #[derive(Serialize)] struct ExecuteRequest<'a> { schema_version: u16, @@ -963,6 +973,188 @@ mod security_tests { } } +/// The shared protocol contract facts the client consumes. +/// +/// These live in the client's own crate rather than in `tests/` because the +/// request bodies the client authors are private: the assertion has to reach +/// the actual structs the transport serializes, not a re-implementation of +/// them. The server crate dev-depends on this one and runs the other half of +/// the agreement — that a body this client builds is accepted by the node. +#[cfg(test)] +mod shared_contract_tests { + use super::*; + use eggwork_core::{ + BlobDigest, CommandSpec, ExecutionGeneration, ExecutionId, ExecutionSpec, + IsolationRequirement, LeaseId, NetworkRequirement, NodeCapabilities, OutputPolicy, + ProtocolVersion, ProtocolVersionRange, Requirement, ResourceRequirements, StdinPolicy, + WorkspaceManifest, WorkspaceManifestPatch, + }; + + fn handle() -> ExecutionHandle { + ExecutionHandle { + execution_id: ExecutionId::new("execution-a").unwrap(), + generation: ExecutionGeneration::new(1).unwrap(), + lease_id: LeaseId::new("lease-a").unwrap(), + } + } + + fn spec() -> ExecutionSpec { + ExecutionSpec { + schema_version: API_SCHEMA_VERSION, + command: CommandSpec { + argv: vec!["/bin/true".into()], + cwd: None, + environment: Vec::new(), + stdin: StdinPolicy::Null, + timeout_millis: 5_000, + output: OutputPolicy::default(), + declared_outputs: Vec::new(), + resources: ResourceRequirements { + memory_bytes: Requirement::NotRequested, + cpu_millis: Requirement::NotRequested, + pids: Requirement::NotRequested, + }, + isolation: IsolationRequirement::None, + network: NetworkRequirement::Unrestricted, + }, + metadata: Vec::new(), + } + } + + fn manifest() -> WorkspaceManifest { + WorkspaceManifest { + schema_version: 1, + entries: Vec::new(), + } + } + + fn patch() -> WorkspaceManifestPatch { + WorkspaceManifestPatch { + schema_version: 1, + base_manifest_digest: BlobDigest::from_bytes(b"base"), + entries: Vec::new(), + } + } + + /// Every request body the client authors carries the shared schema version. + /// + /// The four body shapes are the execute, control, workspace-create and + /// workspace-derive requests. Each one is serialized here and its + /// `schema_version` field is read back, so this asserts the bytes that + /// actually go on the wire rather than the field in isolation. A private + /// copy of the constant in this crate would still satisfy the assertion + /// only if it happened to equal the shared value — which is exactly why + /// the server crate additionally checks that this client's request is not + /// rejected as `protocol_version`. + #[test] + fn every_authored_request_body_carries_the_shared_schema_version() { + let handle = handle(); + let workspace_id = WorkspaceId::new("workspace-a").unwrap(); + let spec = spec(); + let manifest = manifest(); + let patch = patch(); + + let bodies = [ + serde_json::to_value(&ExecuteRequest { + schema_version: API_SCHEMA_VERSION, + handle: handle.clone(), + workspace_id: None, + spec: &spec, + }) + .unwrap(), + serde_json::to_value(&ControlRequest { + schema_version: API_SCHEMA_VERSION, + handle: handle.clone(), + renewal_id: None, + }) + .unwrap(), + serde_json::to_value(&ControlRequest { + schema_version: API_SCHEMA_VERSION, + handle: handle.clone(), + renewal_id: Some("renewal-a".into()), + }) + .unwrap(), + serde_json::to_value(&CreateWorkspaceRequest { + schema_version: API_SCHEMA_VERSION, + workspace_id: &workspace_id, + handle: &handle, + manifest: &manifest, + }) + .unwrap(), + serde_json::to_value(&CreateDerivedWorkspaceRequest { + schema_version: API_SCHEMA_VERSION, + workspace_id: &workspace_id, + handle: &handle, + patch: &patch, + }) + .unwrap(), + ]; + + for body in bodies { + assert_eq!( + body.get("schema_version").and_then(|value| value.as_u64()), + Some(u64::from(API_SCHEMA_VERSION)), + "an authored request body carries the wrong schema version: {body}" + ); + } + } + + fn capabilities(features: Vec<&str>) -> NodeCapabilities { + NodeCapabilities { + protocol: ProtocolVersionRange { + min: ProtocolVersion { major: 1, minor: 0 }, + max: ProtocolVersion { major: 1, minor: 0 }, + }, + features: features.into_iter().map(str::to_owned).collect(), + max_active_executions: 1, + } + } + + /// The client accepts a node that advertises the owned argv feature. + #[test] + fn a_node_advertising_the_owned_argv_feature_is_accepted() { + assert!( + protocol_compatibility(&capabilities(vec![EXEC_ARGV_CAPABILITY])).is_ok(), + "a node advertising the owned argv feature must be accepted" + ); + } + + /// The client refuses a node whose argv feature name differs. + /// + /// The differing name is one character away from the owned one, so this is + /// the regression test for the drift this milestone removes: a server that + /// advertised `exec.argv.v2` while the client demanded `exec.argv.v1` + /// would have been refused with a typed error rather than a silent + /// mismatch — and, before the shared constant existed, nothing in either + /// crate would have said the two names had to agree. + #[test] + fn a_node_advertising_a_differing_argv_feature_is_refused() { + let differing = format!("{EXEC_ARGV_CAPABILITY}v2"); + let error = protocol_compatibility(&capabilities(vec![differing.as_str()])) + .expect_err("a node with a different argv feature must be refused"); + assert!( + matches!(error, ClientError::UnsupportedCapability), + "expected the typed unsupported-capability error, got {error:?}" + ); + } + + /// A node that speaks a different protocol version is refused first. + #[test] + fn a_node_speaking_a_different_protocol_version_is_refused() { + let mut node = capabilities(vec![EXEC_ARGV_CAPABILITY]); + node.protocol = ProtocolVersionRange { + min: ProtocolVersion { major: 2, minor: 0 }, + max: ProtocolVersion { major: 2, minor: 0 }, + }; + let error = protocol_compatibility(&node) + .expect_err("a node on another protocol version must be refused"); + assert!( + matches!(error, ClientError::ProtocolIncompatible), + "expected the typed protocol-incompatible error, got {error:?}" + ); + } +} + #[cfg(test)] mod event_framing_tests { use super::*; diff --git a/crates/eggwork-core/src/lib.rs b/crates/eggwork-core/src/lib.rs index 6e1c8a9..f18e75f 100644 --- a/crates/eggwork-core/src/lib.rs +++ b/crates/eggwork-core/src/lib.rs @@ -1157,6 +1157,89 @@ pub enum ExecutionState { TimedOut, Interrupted, } + +/// Every [`ExecutionState`] variant, in declaration order. +/// +/// The classification below is written as exhaustive matches over the enum, so +/// a tenth variant is a compile error in this crate rather than a state the +/// server has never been told about. This array is the range the contract +/// tests enumerate, which keeps those tests from being satisfiable by a +/// hand-written list of nine variants that a new one could join unnoticed. +pub const ALL_EXECUTION_STATES: [ExecutionState; 9] = [ + ExecutionState::Accepted, + ExecutionState::Preparing, + ExecutionState::Running, + ExecutionState::Cancelling, + ExecutionState::Succeeded, + ExecutionState::Failed, + ExecutionState::Cancelled, + ExecutionState::TimedOut, + ExecutionState::Interrupted, +]; + +impl ExecutionState { + /// Whether this state is terminal. + /// + /// Terminal means the execution has finished and its outcome is settled: + /// no later event can change it. The set is spelled out with nine + /// exhaustive arms and no wildcard, so adding a variant to + /// [`ExecutionState`] breaks the build here instead of producing a state + /// that every consumer silently classifies as still running. + pub fn is_terminal(&self) -> bool { + match self { + ExecutionState::Succeeded + | ExecutionState::Failed + | ExecutionState::Cancelled + | ExecutionState::TimedOut + | ExecutionState::Interrupted => true, + ExecutionState::Accepted + | ExecutionState::Preparing + | ExecutionState::Running + | ExecutionState::Cancelling => false, + } + } + + /// Whether this state is still in flight. + /// + /// The exact complement of [`ExecutionState::is_terminal`]. Both are + /// exhaustive over the same nine arms, so the two can never disagree + /// about a variant — and a variant added to the enum has to be placed in + /// one arm of each. + pub fn is_non_terminal(&self) -> bool { + match self { + ExecutionState::Accepted + | ExecutionState::Preparing + | ExecutionState::Running + | ExecutionState::Cancelling => true, + ExecutionState::Succeeded + | ExecutionState::Failed + | ExecutionState::Cancelled + | ExecutionState::TimedOut + | ExecutionState::Interrupted => false, + } + } + + /// The canonical wire spelling of this state. + /// + /// This is the PascalCase spelling `serde` derives for the enum, and it is + /// the value a server stores in its journal's `state` column. The store + /// reads that column back as text, so the spelling has to be one fact + /// rather than two: the enum owns it here and the store asks for it. + pub fn wire_name(&self) -> &'static str { + match self { + ExecutionState::Accepted => "Accepted", + ExecutionState::Preparing => "Preparing", + ExecutionState::Running => "Running", + ExecutionState::Cancelling => "Cancelling", + ExecutionState::Succeeded => "Succeeded", + ExecutionState::Failed => "Failed", + ExecutionState::Cancelled => "Cancelled", + ExecutionState::TimedOut => "TimedOut", + ExecutionState::Interrupted => "Interrupted", + } + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub enum ExecutionRejection { Busy, @@ -1605,6 +1688,26 @@ pub struct HostTelemetry { /// payload and refuses a version it does not know, rather than guessing. pub const NODE_TELEMETRY_SCHEMA_VERSION: u16 = 1; +/// Wire schema version of the control-plane request and response bodies. +/// +/// Every producer and every consumer of a versioned control-plane body refers +/// to this one constant: a client stamps it into the request bodies it +/// authors, a server refuses a body that does not carry it (HTTP 426 +/// `protocol_version`), and a stored execution snapshot records it. The value +/// is frozen for schema version 1 — it may not change without an ADR — and +/// this declaration is the only one in the workspace, because a second copy in +/// an endpoint crate would let a future bump desynchronise the producer and +/// the consumer with neither the compiler nor the test suite objecting. +pub const API_SCHEMA_VERSION: u16 = 1; + +/// Capability feature name for argv-based execution. +/// +/// A node advertises this feature in `NodeCapabilities.features` and a client +/// requires it before it will submit an execution, so the spelling is a +/// contract fact between two crates rather than a string each side types for +/// itself. The value is frozen and may not change without an ADR. +pub const EXEC_ARGV_CAPABILITY: &str = "exec.argv.v1"; + /// The node's host-wide telemetry observation, as served to an authorized caller. /// /// This is the frozen wire contract for the node telemetry response. It is @@ -1971,7 +2074,7 @@ mod tests { } fn spec() -> ExecutionSpec { ExecutionSpec { - schema_version: 1, + schema_version: API_SCHEMA_VERSION, command: CommandSpec { argv: vec!["echo".into(), "hi".into()], cwd: Some(RelativePath::new("work").unwrap()), diff --git a/crates/eggwork-core/tests/shared_protocol_contract.rs b/crates/eggwork-core/tests/shared_protocol_contract.rs new file mode 100644 index 0000000..78b2a44 --- /dev/null +++ b/crates/eggwork-core/tests/shared_protocol_contract.rs @@ -0,0 +1,160 @@ +//! The protocol contract facts `eggwork-core` owns. +//! +//! Before this milestone the control-plane schema version, the `exec.argv.v1` +//! capability name and the terminal/non-terminal classification of +//! `ExecutionState` were each stated by more than one owner, and the copies +//! had no mechanical relationship: both sides of every pair happened to agree +//! by value, so a future rename or bump on the producing side would have +//! desynchronised the consuming side silently. +//! +//! These tests are the mechanical half of the fix. They pin the *values* (so a +//! careless edit is a test failure rather than a protocol break), they pin the +//! *classification* (so the two sets cannot drift or lose a member), and they +//! pin the wire spelling to the derived `Serialize` (so the journal's `state` +//! column stays honest against the enum). +//! +//! **Adding a tenth variant to `ExecutionState` breaks this suite.** The +//! primary mechanism is structural: `ExecutionState::is_terminal`, +//! `ExecutionState::is_non_terminal` and `ExecutionState::wire_name` are +//! exhaustive `match`es over all nine variants with no wildcard arm, so a new +//! variant does not compile in `eggwork-core` at all. The secondary mechanism +//! is `the_execution_state_enum_has_exactly_nine_variants`, which fails if the +//! enumeration constant is widened without the classification being updated. +//! The property test ranges over the crate-owned +//! `eggwork_core::ALL_EXECUTION_STATES`, never over a list written here, so it +//! cannot be satisfied by a hand-written list of nine variants that a tenth +//! one simply joins unnoticed. + +use eggwork_core::{ + ALL_EXECUTION_STATES, API_SCHEMA_VERSION, EXEC_ARGV_CAPABILITY, ExecutionState, +}; + +/// The control-plane schema version is frozen at 1. +/// +/// The value is a wire fact: a client stamps it into every request body and a +/// server refuses a body that does not carry it. Changing it is a +/// compatibility break, not a refactor. +#[test] +fn the_control_plane_schema_version_is_frozen_at_one() { + assert_eq!(API_SCHEMA_VERSION, 1); +} + +/// The argv capability feature name is frozen at `exec.argv.v1`. +/// +/// A node advertises this name and a client demands it before it will submit +/// an execution, so the bytes are a contract between two crates. +#[test] +fn the_exec_argv_capability_name_is_frozen() { + assert_eq!(EXEC_ARGV_CAPABILITY, "exec.argv.v1"); +} + +/// The state enum still has exactly nine variants. +/// +/// This is the second half of the "adding a variant breaks the suite" +/// guarantee: the exhaustive matches in `eggwork-core` stop the enum from +/// growing silently, and this assertion stops the enumeration constant from +/// growing silently either. +#[test] +fn the_execution_state_enum_has_exactly_nine_variants() { + assert_eq!( + ALL_EXECUTION_STATES.len(), + 9, + "the shared state enumeration must be widened together with the classification" + ); +} + +/// Every variant lands in exactly one of the two sets. +/// +/// A state that is neither terminal nor non-terminal — or both — would make +/// every consumer's answer depend on which arm it happened to check. +#[test] +fn every_state_is_classified_into_exactly_one_set() { + for state in &ALL_EXECUTION_STATES { + assert_ne!( + state.is_terminal(), + state.is_non_terminal(), + "{state:?} is classified as both terminal and non-terminal, or as neither" + ); + } +} + +/// The terminal set has five members and the non-terminal set four. +/// +/// The membership is spelled out, not just the counts: a mis-edited +/// classification — `Failed` flipped to non-terminal, say — still partitions +/// the enum, and only the membership catches it. +#[test] +fn the_terminal_set_has_five_members_and_the_non_terminal_set_four() { + let terminal: Vec<&str> = ALL_EXECUTION_STATES + .iter() + .filter(|state| state.is_terminal()) + .map(|state| state.wire_name()) + .collect(); + let non_terminal: Vec<&str> = ALL_EXECUTION_STATES + .iter() + .filter(|state| state.is_non_terminal()) + .map(|state| state.wire_name()) + .collect(); + + assert_eq!( + terminal, + [ + "Succeeded", + "Failed", + "Cancelled", + "TimedOut", + "Interrupted" + ] + ); + assert_eq!( + non_terminal, + ["Accepted", "Preparing", "Running", "Cancelling"] + ); + assert_eq!(terminal.len(), 5); + assert_eq!(non_terminal.len(), 4); + assert_eq!( + terminal.len() + non_terminal.len(), + ALL_EXECUTION_STATES.len() + ); +} + +/// The canonical wire spelling is exactly what the derived `Serialize` emits. +/// +/// This is what keeps the journal's `state` column honest against the enum: +/// the column stores the PascalCase spelling, so the spelling has to be the +/// enum's own serialised form and not a second, hand-maintained list. +#[test] +fn the_wire_spelling_matches_the_derived_serde_representation() { + for state in &ALL_EXECUTION_STATES { + let encoded = serde_json::to_string(state).expect("a state must encode"); + assert_eq!( + encoded, + format!("\"{}\"", state.wire_name()), + "{state:?} has a wire spelling that disagrees with its serde form" + ); + let decoded: ExecutionState = serde_json::from_str(&encoded).expect("a state must decode"); + assert_eq!(&decoded, state); + } +} + +/// The wire form is still externally tagged PascalCase with no rename. +/// +/// The enum's `Serialize`/`Deserialize` derives are untouched: a state encodes +/// as the bare string `"TimedOut"`, not as a tagged object, and not as +/// `"timed_out"`. A rename attribute here would silently move every persisted +/// state. +#[test] +fn the_state_wire_form_is_still_a_bare_pascal_case_string() { + assert_eq!( + serde_json::to_string(&ExecutionState::TimedOut).unwrap(), + "\"TimedOut\"" + ); + assert_eq!( + serde_json::to_string(&ExecutionState::Accepted).unwrap(), + "\"Accepted\"" + ); + assert_eq!( + serde_json::from_str::("\"TimedOut\"").unwrap(), + ExecutionState::TimedOut + ); +} diff --git a/crates/eggwork-runner/src/lib.rs b/crates/eggwork-runner/src/lib.rs index 487e1b6..afbbcde 100644 --- a/crates/eggwork-runner/src/lib.rs +++ b/crates/eggwork-runner/src/lib.rs @@ -637,7 +637,7 @@ impl ExecutionSetup for TrustedLandlockSetup { let outcome = match sandbox { SandboxRequest::None => SandboxOutcome::NotRequested, SandboxRequest::BestEffort { profile } | SandboxRequest::Required { profile } => { - if profile != "workspace_rw" { + if profile != WORKSPACE_RW_PROFILE { let reason = "unsupported sandbox profile".to_owned(); if matches!(sandbox, SandboxRequest::BestEffort { .. }) { return Ok(SetupOutcome { @@ -667,35 +667,9 @@ impl ExecutionSetup for TrustedLandlockSetup { async fn execution_capabilities(&self) -> Vec { let mut capabilities = Vec::new(); if verify_trusted_helper(&self.helper_path).is_ok() && probe_landlock_ruleset() { - capabilities.push("isolation.landlock.workspace-rw.v1".into()); + capabilities.push(LANDLOCK_WORKSPACE_RW_CAPABILITY.into()); } - let probes = [ - ( - "resources.cgroups-v2.memory", - ResourceSetupRequest { - memory_bytes: Requirement::BestEffort(32 * 1024 * 1024), - cpu_millis: Requirement::NotRequested, - pids: Requirement::NotRequested, - }, - ), - ( - "resources.cgroups-v2.cpu", - ResourceSetupRequest { - memory_bytes: Requirement::NotRequested, - cpu_millis: Requirement::BestEffort(100), - pids: Requirement::NotRequested, - }, - ), - ( - "resources.cgroups-v2.pids", - ResourceSetupRequest { - memory_bytes: Requirement::NotRequested, - cpu_millis: Requirement::NotRequested, - pids: Requirement::BestEffort(16), - }, - ), - ]; - for (feature, request) in probes { + for (feature, request) in CGROUP_PROBE_TABLE { if SystemdCgroupBackend::probe(&request).await.is_ok() { capabilities.push(feature.into()); } @@ -712,6 +686,78 @@ impl ExecutionSetup for TrustedLandlockSetup { /// `workspace_rw` profile used by `IsolationRequirement::{BestEffort, Required}`. pub const LANDLOCK_WORKSPACE_RW_CAPABILITY: &str = "isolation.landlock.workspace-rw.v1"; +/// Public capability feature name advertised when the cgroup v2 memory +/// controller is enforced. +/// +/// The value is the frozen public feature name for the memory dimension and +/// must not change without an ADR: a node advertises it and a server admits +/// a required memory dimension only when the advertised name matches, so a +/// renamed byte would turn every memory-limited request into a +/// capability refusal. +pub const CGROUPS_V2_MEMORY_CAPABILITY: &str = "resources.cgroups-v2.memory"; + +/// Public capability feature name advertised when the cgroup v2 CPU +/// controller is enforced. +/// +/// The value is the frozen public feature name for the CPU dimension and must +/// not change without an ADR, for the same reason as +/// [`CGROUPS_V2_MEMORY_CAPABILITY`]. +pub const CGROUPS_V2_CPU_CAPABILITY: &str = "resources.cgroups-v2.cpu"; + +/// Public capability feature name advertised when the cgroup v2 pids +/// controller is enforced. +/// +/// The value is the frozen public feature name for the pids dimension and must +/// not change without an ADR, for the same reason as +/// [`CGROUPS_V2_MEMORY_CAPABILITY`]. +pub const CGROUPS_V2_PIDS_CAPABILITY: &str = "resources.cgroups-v2.pids"; + +/// The only sandbox profile the protocol can request. +/// +/// `SandboxRequest::{BestEffort, Required}` carry a profile name, and +/// `workspace_rw` is the only one the runner will run and the only one the +/// trusted helper will grant — the helper is a standalone binary with no +/// workspace-crate dependency, so it keeps its own literal and the test in +/// `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` pins that literal +/// to this constant. The value must not change without an ADR: a rename would +/// make the runner ask for a profile the helper refuses, which fails closed +/// as "unsupported sandbox profile" rather than silently degrading. +pub const WORKSPACE_RW_PROFILE: &str = "workspace_rw"; + +/// The cgroup v2 probes the runner runs before it advertises a resource +/// feature, paired with the feature name each probe earns. +/// +/// The table is a `const` so a test can read the names it would advertise +/// without running the probes: the names here are the exported constants, and +/// a literal typed into the table would show up as a name that is not one of +/// them. +const CGROUP_PROBE_TABLE: [(&str, ResourceSetupRequest); 3] = [ + ( + CGROUPS_V2_MEMORY_CAPABILITY, + ResourceSetupRequest { + memory_bytes: Requirement::BestEffort(32 * 1024 * 1024), + cpu_millis: Requirement::NotRequested, + pids: Requirement::NotRequested, + }, + ), + ( + CGROUPS_V2_CPU_CAPABILITY, + ResourceSetupRequest { + memory_bytes: Requirement::NotRequested, + cpu_millis: Requirement::BestEffort(100), + pids: Requirement::NotRequested, + }, + ), + ( + CGROUPS_V2_PIDS_CAPABILITY, + ResourceSetupRequest { + memory_bytes: Requirement::NotRequested, + cpu_millis: Requirement::NotRequested, + pids: Requirement::BestEffort(16), + }, + ), +]; + /// Probe the kernel Landlock ABI V4 with the same set of handles and rules /// the trusted helper uses for `workspace_rw`. Returns `true` only if the /// in-process ruleset can be created and the runtime read paths can be added; @@ -1160,10 +1206,10 @@ impl RunnerRequest { let sandbox = match isolation { eggwork_core::IsolationRequirement::None => SandboxRequest::None, eggwork_core::IsolationRequirement::BestEffort => SandboxRequest::BestEffort { - profile: "workspace_rw".into(), + profile: WORKSPACE_RW_PROFILE.into(), }, eggwork_core::IsolationRequirement::Required => SandboxRequest::Required { - profile: "workspace_rw".into(), + profile: WORKSPACE_RW_PROFILE.into(), }, }; Ok(Self { @@ -2213,7 +2259,7 @@ impl SandboxChannel { ) -> Result { let profile = match &request.sandbox { SandboxRequest::BestEffort { profile } | SandboxRequest::Required { profile } - if profile == "workspace_rw" => + if profile == WORKSPACE_RW_PROFILE => { Some(profile.clone()) } @@ -2880,6 +2926,53 @@ mod tests { ); } + /// The three cgroup feature names are frozen byte-for-byte. + /// + /// A node advertises these and a server admits a required resource + /// dimension only when the advertised name matches, so a renamed byte + /// turns every memory-, CPU- or pids-limited request into a capability + /// refusal. The values are asserted here rather than only through the + /// constants, so a value change is a test failure even when the constant + /// and its consumer are edited together. + #[test] + fn cgroup_capability_feature_strings_are_frozen() { + assert_eq!(CGROUPS_V2_MEMORY_CAPABILITY, "resources.cgroups-v2.memory"); + assert_eq!(CGROUPS_V2_CPU_CAPABILITY, "resources.cgroups-v2.cpu"); + assert_eq!(CGROUPS_V2_PIDS_CAPABILITY, "resources.cgroups-v2.pids"); + } + + /// The sandbox profile name is frozen byte-for-byte. + /// + /// The helper is a standalone binary with its own literal, so the two + /// spellings are pinned together by the helper's test rather than by a + /// shared constant. This assertion is the runner's half of that pair. + #[test] + fn the_workspace_rw_profile_name_is_frozen() { + assert_eq!(WORKSPACE_RW_PROFILE, "workspace_rw"); + } + + /// The advertisement site cannot invent a feature name. + /// + /// The probe table is the source of every resource feature the runner can + /// advertise, and it names them with the exported constants. A literal + /// typed back into the table would fail this on any host, because the + /// check reads the table rather than a list of names written here. + #[test] + fn the_probe_table_advertises_exactly_the_exported_constants() { + let names: Vec<&str> = CGROUP_PROBE_TABLE + .iter() + .map(|(feature, _)| *feature) + .collect(); + assert_eq!( + names, + [ + CGROUPS_V2_MEMORY_CAPABILITY, + CGROUPS_V2_CPU_CAPABILITY, + CGROUPS_V2_PIDS_CAPABILITY, + ] + ); + } + #[tokio::test] async fn no_setup_advertises_empty_dynamic_capabilities() { let setup = NoExecutionSetup; diff --git a/crates/eggwork-runner/tests/capability_probe.rs b/crates/eggwork-runner/tests/capability_probe.rs index c4b1eb2..5987ab6 100644 --- a/crates/eggwork-runner/tests/capability_probe.rs +++ b/crates/eggwork-runner/tests/capability_probe.rs @@ -9,7 +9,7 @@ //! dev-only workspace member, and the release contract enumerates workspace //! members. -use eggwork_runner::{LocalProcessRunner, TrustedLandlockSetup}; +use eggwork_runner::{LANDLOCK_WORKSPACE_RW_CAPABILITY, LocalProcessRunner, TrustedLandlockSetup}; #[cfg(target_os = "linux")] use std::path::PathBuf; @@ -44,7 +44,7 @@ async fn trusted_helper_advertises_landlock_workspace_rw_capability() { assert!( capabilities .iter() - .any(|feature| feature == "isolation.landlock.workspace-rw.v1"), + .any(|feature| feature == LANDLOCK_WORKSPACE_RW_CAPABILITY), "expected Landlock workspace-rw capability on a kernel with ABI V4; got {capabilities:?}" ); } @@ -61,7 +61,7 @@ async fn missing_helper_advertises_no_landlock_capability() { assert!( !capabilities .iter() - .any(|feature| feature == "isolation.landlock.workspace-rw.v1"), + .any(|feature| feature == LANDLOCK_WORKSPACE_RW_CAPABILITY), "missing helper must not advertise Landlock capability; got {capabilities:?}" ); } diff --git a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs index 10600ba..90ad314 100644 --- a/crates/eggwork-sandbox-helper/tests/landlock_runner.rs +++ b/crates/eggwork-sandbox-helper/tests/landlock_runner.rs @@ -14,6 +14,7 @@ use eggwork_core::{OverflowPolicy, Requirement}; use eggwork_runner::{ ExecutionProvenance, ExecutionSetup, LocalProcessRunner, ResourceSetupRequest, RunnerError, RunnerRequest, SandboxOutcome, SandboxRequest, StdinPolicy, TrustedLandlockSetup, + WORKSPACE_RW_PROFILE, }; use helper_fixture::TrustedHelperFixture; use std::{ @@ -507,6 +508,120 @@ fn malformed_private_spec_and_unavailable_status_channel_do_not_launch_target() assert!(!marker.exists()); } +/// The runner's profile name is the profile the helper grants. +/// +/// The helper is a standalone binary with no workspace-crate dependency, so it +/// cannot import the runner's constant and keeps its own `"workspace_rw"` +/// literal. This test is what pins that unavoidable literal to the runner's +/// constant, and it does so in both directions: +/// +/// * the profile the runner produces is accepted, and the target runs; +/// * a profile that differs from the runner's by one character is refused +/// *before* the target is spawned, so a renamed profile can never reach a +/// process. +/// +/// If the runner's profile name ever moved, the first half fails: the helper +/// would refuse the specification and the target marker would never appear. +#[test] +fn the_runner_profile_is_granted_and_a_differing_one_is_refused_before_the_target_spawns() { + use std::{io::Read, os::unix::fs::PermissionsExt}; + + let temp = tempfile::tempdir().unwrap(); + fs::set_permissions(temp.path(), fs::Permissions::from_mode(0o700)).unwrap(); + let root = temp.path().canonicalize().unwrap(); + let fixture = TrustedHelperFixture::stage(built_helper()); + + // 1. The profile the runner produces is accepted and the target runs. + let granted_marker = temp.path().join("granted-target-ran"); + let granted_spec = temp.path().join("granted.json"); + fs::write( + &granted_spec, + serde_json::json!({ + "schema_version": 1, + "profile": WORKSPACE_RW_PROFILE, + "root": root, + "cwd": root, + "argv": ["/usr/bin/touch", granted_marker], + "environment": [] + }) + .to_string(), + ) + .unwrap(); + fs::set_permissions(&granted_spec, fs::Permissions::from_mode(0o600)).unwrap(); + let granted_status = temp.path().join("granted.sock"); + let granted_listener = std::os::unix::net::UnixListener::bind(&granted_status).unwrap(); + let mut granted_child = Command::new(fixture.path()) + .arg("--spec") + .arg(&granted_spec) + .arg("--status") + .arg(&granted_status) + .spawn() + .unwrap(); + let (mut granted_stream, _) = granted_listener.accept().unwrap(); + let mut granted_code = [0u8; 1]; + granted_stream.read_exact(&mut granted_code).unwrap(); + assert_eq!( + granted_code[0], 1, + "the helper must accept the profile the runner produces" + ); + // The second byte is the post-mortem resource status; reading it lets the + // helper finish writing before the test reaps it. + let mut resource_status = [0u8; 1]; + granted_stream.read_exact(&mut resource_status).unwrap(); + granted_child.wait().unwrap(); + assert!( + granted_marker.exists(), + "the target must run under the runner's own profile name" + ); + + // 2. A profile that differs from the runner's is refused before the + // target is spawned. + let refused_marker = temp.path().join("refused-target-ran"); + let refused_spec = temp.path().join("refused.json"); + fs::write( + &refused_spec, + serde_json::json!({ + "schema_version": 1, + "profile": format!("{WORKSPACE_RW_PROFILE}x"), + "root": root, + "cwd": root, + "argv": ["/usr/bin/touch", refused_marker], + "environment": [] + }) + .to_string(), + ) + .unwrap(); + fs::set_permissions(&refused_spec, fs::Permissions::from_mode(0o600)).unwrap(); + let refused_status = temp.path().join("refused.sock"); + let refused_listener = std::os::unix::net::UnixListener::bind(&refused_status).unwrap(); + let mut refused_child = Command::new(fixture.path()) + .arg("--spec") + .arg(&refused_spec) + .arg("--status") + .arg(&refused_status) + .spawn() + .unwrap(); + let (mut refused_stream, _) = refused_listener.accept().unwrap(); + let mut refused_code = [0u8; 1]; + refused_stream.read_exact(&mut refused_code).unwrap(); + assert_eq!( + refused_code[0], 12, + "a profile that differs from the runner's must be refused as a malformed spec" + ); + assert!( + refused_child + .wait() + .unwrap() + .code() + .is_some_and(|code| code != 0), + "a refused specification must not report success" + ); + assert!( + !refused_marker.exists(), + "a refused profile must not reach a spawned target" + ); +} + // Operations M004a: the fixture-isolation proofs. // // The recorded CI failure was an `ETXTBSY` from a helper spawn, which is Linux diff --git a/crates/eggwork-server/src/lib.rs b/crates/eggwork-server/src/lib.rs index bdd2426..7b0d7fe 100644 --- a/crates/eggwork-server/src/lib.rs +++ b/crates/eggwork-server/src/lib.rs @@ -20,10 +20,10 @@ use eggserve_core::{ tls::{ClientAuthMode, TlsServerConfig}, }; use eggwork_core::{ - ApiError, ExecutionEvent, ExecutionEventKind, ExecutionFailure, ExecutionFinalizationFailure, - ExecutionGeneration, ExecutionHandle, ExecutionId, ExecutionResult, ExecutionSnapshot, - ExecutionSpec, ExecutionState, LeaseId, NodeCapabilities, NodeId, NodeStatus, ProtocolVersion, - ProtocolVersionRange, + API_SCHEMA_VERSION, ApiError, EXEC_ARGV_CAPABILITY, ExecutionEvent, ExecutionEventKind, + ExecutionFailure, ExecutionFinalizationFailure, ExecutionGeneration, ExecutionHandle, + ExecutionId, ExecutionResult, ExecutionSnapshot, ExecutionSpec, ExecutionState, LeaseId, + NodeCapabilities, NodeId, NodeStatus, ProtocolVersion, ProtocolVersionRange, }; use eggwork_runner::{ ExecutionProvenance, LocalProcessRunner, OutputChunk, ResourceSetupRequest, RunnerError, @@ -46,7 +46,6 @@ use thiserror::Error; use tokio::sync::{Mutex, OwnedSemaphorePermit, RwLock, Semaphore, broadcast, mpsc}; use tokio_util::sync::CancellationToken; -const API_SCHEMA_VERSION: u16 = 1; const MAX_REQUEST_BYTES: usize = 1024 * 1024; const EVENT_CAPACITY: usize = 32; const RUNNER_CHANNEL_CAPACITY: usize = 32; @@ -481,7 +480,7 @@ impl NodeServer { .collect(); for record in records { if !record.finished.load(Ordering::Acquire) - && !is_terminal(&record.snapshot.read().await.state) + && !record.snapshot.read().await.state.is_terminal() { record.cancellation.cancel(); } @@ -560,7 +559,7 @@ impl NodeServer { let mut active = false; for record in records { if !record.finished.load(Ordering::Acquire) - && !is_terminal(&record.snapshot.read().await.state) + && !record.snapshot.read().await.state.is_terminal() { active = true; break; @@ -599,7 +598,7 @@ fn acquire_state_lock(database_path: &std::path::Path) -> Result &'static [&'static str] { &[ - "exec.argv.v1", + EXEC_ARGV_CAPABILITY, "events.live.v1", "auth.mtls.v1", "blob.sha256.v1", @@ -640,33 +639,44 @@ fn node_capabilities_for(state: &NodeState) -> NodeCapabilities { } } +/// Whether the node's advertised features satisfy an isolation requirement. +/// +/// The advertised feature list is passed in rather than the whole node state +/// so the admission rule can be exercised directly: the decision is about +/// names, and a rule about names should not need a whole service to be +/// constructed before it can be tested. fn check_isolation_supported( - state: &NodeState, + features: &[String], isolation: &eggwork_core::IsolationRequirement, ) -> bool { match isolation { eggwork_core::IsolationRequirement::None | eggwork_core::IsolationRequirement::BestEffort => true, - eggwork_core::IsolationRequirement::Required => state - .capabilities_features + eggwork_core::IsolationRequirement::Required => features .iter() .any(|feature| feature == eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY), } } +/// Whether the node's advertised features satisfy a resource requirement. +/// +/// The three names compared here are the runner's exported constants, not +/// spellings typed into this file: the runner produces them and this crate +/// consumes them, and a name that differed by one character would turn every +/// required resource dimension into a capability refusal. fn check_resources_supported( - state: &NodeState, + features: &[String], resources: &eggwork_core::ResourceRequirements, ) -> bool { - let has = |feature: &str| state.capabilities_features.iter().any(|f| f == feature); + let has = |feature: &str| features.iter().any(|advertised| advertised == feature); let memory_ok = !matches!( resources.memory_bytes, eggwork_core::Requirement::Required(_) - ) || has("resources.cgroups-v2.memory"); + ) || has(eggwork_runner::CGROUPS_V2_MEMORY_CAPABILITY); let cpu_ok = !matches!(resources.cpu_millis, eggwork_core::Requirement::Required(_)) - || has("resources.cgroups-v2.cpu"); + || has(eggwork_runner::CGROUPS_V2_CPU_CAPABILITY); let pids_ok = !matches!(resources.pids, eggwork_core::Requirement::Required(_)) - || has("resources.cgroups-v2.pids"); + || has(eggwork_runner::CGROUPS_V2_PIDS_CAPABILITY); memory_ok && cpu_ok && pids_ok } @@ -1649,7 +1659,7 @@ async fn execute( "node is not accepting executions", )); } - if !check_isolation_supported(&state, &wire.spec.command.isolation) { + if !check_isolation_supported(&state.capabilities_features, &wire.spec.command.isolation) { increment_metric(&state.store, "rejected_capability", 1).await; return Ok(error_response( 409, @@ -1657,7 +1667,7 @@ async fn execute( "requested filesystem isolation capability is unavailable", )); } - if !check_resources_supported(&state, &wire.spec.command.resources) { + if !check_resources_supported(&state.capabilities_features, &wire.spec.command.resources) { increment_metric(&state.store, "rejected_capability", 1).await; return Ok(error_response( 409, @@ -1792,7 +1802,7 @@ async fn execute( if executions.len() >= MAX_RECENT_EXECUTIONS { let mut terminal = Vec::new(); for (old_id, old_record) in executions.iter() { - if is_terminal(&old_record.snapshot.read().await.state) { + if old_record.snapshot.read().await.state.is_terminal() { terminal.push(old_id.clone()); } if executions.len() - terminal.len() < MAX_RECENT_EXECUTIONS { @@ -1865,7 +1875,7 @@ async fn execute( } store::ReserveResult::Existing(snapshot) => { drop(permit); - if is_terminal(&snapshot.state) + if snapshot.state.is_terminal() && let Some(workspace_id) = &wire.workspace_id { let expiry = @@ -2006,7 +2016,7 @@ fn recovered_record( async fn monitor_lease(record: Arc) { loop { - if is_terminal(&record.snapshot.read().await.state) { + if record.snapshot.read().await.state.is_terminal() { return; } let (deadline, notify) = { @@ -2181,7 +2191,7 @@ async fn control( "renewal identifier is invalid", )); } - if is_terminal(&snapshot.state) { + if snapshot.state.is_terminal() { return Ok(error_response( 409, "execution_terminal", @@ -2224,7 +2234,7 @@ async fn control( lease.notify.notify_waiters(); return Ok(json_response(200, &snapshot)); } - if !is_terminal(&snapshot.state) && snapshot.state != ExecutionState::Cancelling { + if !snapshot.state.is_terminal() && snapshot.state != ExecutionState::Cancelling { let lease = record.lease.lock().await; if lease.expired.load(Ordering::Acquire) || tokio::time::Instant::now() >= lease.expires_at { @@ -2242,7 +2252,7 @@ async fn control( ExecutionEventKind::State(ExecutionState::Cancelling), ) .await; - if !is_terminal(&record.snapshot.read().await.state) { + if !record.snapshot.read().await.state.is_terminal() { record.cancellation.cancel(); } } else if snapshot.state == ExecutionState::Cancelling { @@ -2412,7 +2422,7 @@ async fn event_response( "event cursor is ahead of the journal", )); } - let terminal = is_terminal(&record.snapshot.read().await.state); + let terminal = record.snapshot.read().await.state.is_terminal(); Ok(event_stream_response( id, generation, @@ -2532,10 +2542,7 @@ async fn run_execution( if let Some(workspace) = workspace { let should_capture = runner_completed && !workspace.outputs.is_empty() - && matches!( - execution_result.state, - ExecutionState::Succeeded | ExecutionState::Failed - ) + && artifact_capture_eligible(&execution_result.state) && execution_result.failure != Some(ExecutionFailure::OutputLimit); if should_capture { let expiry = artifact::now_unix_ms().saturating_add(artifact::DEFAULT_RETENTION_MILLIS); @@ -2572,14 +2579,7 @@ async fn run_execution( } } let terminal = execution_result.state.clone(); - let terminal_metric = match terminal { - ExecutionState::Succeeded => Some("terminal_succeeded"), - ExecutionState::Failed => Some("terminal_failed"), - ExecutionState::Cancelled => Some("terminal_cancelled"), - ExecutionState::TimedOut => Some("terminal_timed_out"), - ExecutionState::Interrupted => Some("terminal_interrupted"), - _ => None, - }; + let terminal_metric = terminal_metric_name(&terminal); let mut terminal_counters = Vec::with_capacity(4); if let Some(name) = terminal_metric { terminal_counters.push((name, 1u64)); @@ -2668,7 +2668,7 @@ async fn publish( // and then receives the event on the broadcast channel. let _writer = record.commit_lock.lock().await; let base = record.snapshot.read().await; - if is_terminal(&base.state) { + if base.state.is_terminal() { return; } let mut proposed = base.clone(); @@ -2738,7 +2738,7 @@ fn event_stream_response( last_sequence = event.sequence.get(); let terminal = matches!( &event.kind, - ExecutionEventKind::State(state) if is_terminal(state) + ExecutionEventKind::State(state) if state.is_terminal() ); let bytes = serde_json::to_vec(&event).unwrap_or_default(); let mut line = bytes; @@ -2762,15 +2762,46 @@ fn event_stream_response( .unwrap_or_else(|_| error_response(500, "internal", "internal error")) } -fn is_terminal(state: &ExecutionState) -> bool { - matches!( - state, - ExecutionState::Succeeded - | ExecutionState::Failed - | ExecutionState::Cancelled - | ExecutionState::TimedOut - | ExecutionState::Interrupted - ) +/// The metric name a terminal state contributes, if any. +/// +/// Written as an exhaustive match over the whole enum rather than a wildcard +/// arm, so a newly added terminal variant cannot silently lose its metric: the +/// compiler refuses the new variant until it is placed here. The non-terminal +/// arms return `None`, which keeps this map total over the enum and +/// consistent with the core-owned terminal classification. +fn terminal_metric_name(state: &ExecutionState) -> Option<&'static str> { + match state { + ExecutionState::Succeeded => Some("terminal_succeeded"), + ExecutionState::Failed => Some("terminal_failed"), + ExecutionState::Cancelled => Some("terminal_cancelled"), + ExecutionState::TimedOut => Some("terminal_timed_out"), + ExecutionState::Interrupted => Some("terminal_interrupted"), + ExecutionState::Accepted + | ExecutionState::Preparing + | ExecutionState::Running + | ExecutionState::Cancelling => None, + } +} + +/// Whether declared outputs of an execution are captured. +/// +/// This is deliberately *not* the terminal set. A capture happens for an +/// execution that ran and produced a result the caller may want — `Succeeded` +/// or `Failed` — and not for an execution that was cancelled, timed out, or +/// interrupted, where the partial output is not a declared artifact. Folding +/// the two together would either capture artifacts for cancelled work or +/// drop the artifacts of a failed run. +fn artifact_capture_eligible(state: &ExecutionState) -> bool { + match state { + ExecutionState::Succeeded | ExecutionState::Failed => true, + ExecutionState::Accepted + | ExecutionState::Preparing + | ExecutionState::Running + | ExecutionState::Cancelling + | ExecutionState::Cancelled + | ExecutionState::TimedOut + | ExecutionState::Interrupted => false, + } } fn json_response(status: u16, value: &T) -> Response { @@ -2954,7 +2985,7 @@ mod tests { fn execution_spec(argv: Vec) -> ExecutionSpec { ExecutionSpec { - schema_version: 1, + schema_version: API_SCHEMA_VERSION, command: CommandSpec { argv, cwd: None, @@ -3867,6 +3898,135 @@ mod tests { server.wait().await.unwrap(); } + /// The client and the node agree on the control-plane schema version. + /// + /// This is the test that would have caught the defect this milestone removes. + /// Before it, the client and the server each declared a private + /// `API_SCHEMA_VERSION`; the two happened to agree by value, but nothing + /// connected them, so a bump on either side would have made every client + /// request fail with HTTP 426 `protocol_version` — and neither the compiler + /// nor the test suite would have said why. + /// + /// The proof has three links: + /// + /// 1. The node refuses any body whose version is not the shared constant, and + /// accepts the shared constant. + /// 2. A body in the client's exact shape — same fields, same order — carrying + /// the shared constant is accepted, so the client's body and the node's + /// accepted body are the same bytes. + /// 3. The real client, building the real body, is accepted by the real node. + /// A private copy on either side would have broken link 3 immediately. + #[tokio::test] + async fn the_client_and_the_node_agree_on_the_control_plane_schema_version() { + init_tls(); + let (root, server_identity, client_identity, _) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([( + FingerprintPrincipalResolver::fingerprint(client_identity.cert.as_ref()), + eggwork_core::PrincipalId::new("controller-schema").unwrap(), + )])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: None, + node_id: NodeId::new("node-schema").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024 * 1024, + max_active_executions: 1, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + Arc::new(|_: &NodePrincipal, _| true), + ) + .await + .unwrap(); + + let address = format!("https://localhost:{}", server.local_addr().port()); + let client_temp = TempDir::new().unwrap(); + let client = NodeClient::new( + &address, + write_client_config(&client_temp, root.as_ref(), &client_identity), + ) + .unwrap(); + + // Link 1: only the shared constant is accepted. + // + // The accepted body carries an invalid specification on purpose: the + // version check runs before the specification check, so a + // `400 invalid_request` proves the body got past the version gate, + // and no execution is started that would occupy the node's only + // permit. + let handle = execution_handle("schema-agreement"); + let spec = execution_spec(vec!["/bin/true".into()]); + let accepted = serde_json::to_vec(&ExecuteRequest { + schema_version: eggwork_core::API_SCHEMA_VERSION, + handle: handle.clone(), + workspace_id: None, + spec: execution_spec(vec![]), + }) + .unwrap(); + let status = post_raw( + &format!("{address}/v1/executions"), + write_client_config(&client_temp, root.as_ref(), &client_identity), + accepted, + ) + .await; + assert_ne!( + status, 426, + "a body carrying the shared schema version must not be refused as protocol_version" + ); + + let refused = serde_json::to_vec(&ExecuteRequest { + schema_version: eggwork_core::API_SCHEMA_VERSION + 1, + handle: execution_handle("schema-refused"), + workspace_id: None, + spec: spec.clone(), + }) + .unwrap(); + assert_eq!( + post_raw( + &format!("{address}/v1/executions"), + write_client_config(&client_temp, root.as_ref(), &client_identity), + refused, + ) + .await, + 426, + "a body carrying any other schema version must be refused as protocol_version" + ); + + // Link 3: the real client, building the real body, is accepted. + let execution = client + .execute( + &execution_spec(vec!["/bin/echo".into(), "schema-agreement".into()]), + &execution_handle("client-built-schema"), + ) + .await + .expect("a client-built request must not be refused as protocol_version"); + let id = execution.execution_id.clone(); + let event_read = tokio::time::timeout( + ROUND_TRIP_BUDGET, + execution.into_events().collect::>(), + ) + .await; + assert!( + event_read.is_ok(), + "the event stream must reach a terminal state" + ); + let snapshot = client.observe(&id).await.unwrap(); + assert_eq!(snapshot.state, ExecutionState::Succeeded); + + server.shutdown().await; + server.wait().await.unwrap(); + } + #[tokio::test] async fn mtls_execution_streams_output_and_missing_certificate_is_rejected() { init_tls(); @@ -4261,7 +4421,7 @@ mod tests { let snapshot = tokio::time::timeout(ROUND_TRIP_BUDGET, async { loop { let snapshot = client.observe(&handle.execution_id).await.unwrap(); - if is_terminal(&snapshot.state) { + if snapshot.state.is_terminal() { break snapshot; } tokio::time::sleep(std::time::Duration::from_millis(20)).await; @@ -6178,7 +6338,7 @@ mod tests { #[test] fn static_capability_features_are_a_single_canonical_list() { let features = static_capability_features(); - assert!(features.contains(&"exec.argv.v1")); + assert!(features.contains(&eggwork_core::EXEC_ARGV_CAPABILITY)); assert!(features.contains(&"network.unrestricted.v1")); let mut sorted = features.to_vec(); sorted.sort_unstable(); @@ -6190,14 +6350,163 @@ mod tests { ); } + /// The advertised argv feature is the one the owner declares. + /// + /// The server produces this name and the client consumes it, so the two + /// must be the same string. This is the server's half of that agreement: + /// the advertised list carries `eggwork_core::EXEC_ARGV_CAPABILITY` and + /// not a spelling typed into this crate. + #[test] + fn the_advertised_argv_feature_is_the_one_the_owner_declares() { + assert_eq!(eggwork_core::EXEC_ARGV_CAPABILITY, "exec.argv.v1"); + let features = static_capability_features(); + assert_eq!( + features + .iter() + .filter(|feature| **feature == eggwork_core::EXEC_ARGV_CAPABILITY) + .count(), + 1, + "the owned argv feature must be advertised exactly once" + ); + } + + /// The resource admission rule reads the runner's exported constants. + /// + /// The runner produces the three cgroup feature names and this crate + /// consumes them, so a required dimension is admitted exactly when the + /// node advertises the runner's constant. The refusal case is the + /// regression test: a name that differs by one character must not + /// satisfy the requirement, because that is what server/runner drift + /// would look like. + #[test] + fn the_resource_admission_rule_reads_the_runner_constants() { + let required = eggwork_core::ResourceRequirements { + memory_bytes: eggwork_core::Requirement::Required(1024 * 1024), + cpu_millis: eggwork_core::Requirement::Required(100), + pids: eggwork_core::Requirement::Required(4), + }; + let advertised = vec![ + eggwork_runner::CGROUPS_V2_MEMORY_CAPABILITY.to_owned(), + eggwork_runner::CGROUPS_V2_CPU_CAPABILITY.to_owned(), + eggwork_runner::CGROUPS_V2_PIDS_CAPABILITY.to_owned(), + ]; + assert!( + check_resources_supported(&advertised, &required), + "the runner's constants must satisfy a required resource request" + ); + + for constant in [ + eggwork_runner::CGROUPS_V2_MEMORY_CAPABILITY, + eggwork_runner::CGROUPS_V2_CPU_CAPABILITY, + eggwork_runner::CGROUPS_V2_PIDS_CAPABILITY, + ] { + let mut drifting = advertised.clone(); + let index = drifting + .iter() + .position(|feature| feature == constant) + .expect("the advertised list holds the constant"); + drifting[index] = format!("{constant}x"); + assert!( + !check_resources_supported(&drifting, &required), + "a feature name differing by one character must not satisfy {constant}" + ); + } + + let without_memory: Vec = advertised + .iter() + .filter(|feature| *feature != eggwork_runner::CGROUPS_V2_MEMORY_CAPABILITY) + .cloned() + .collect(); + assert!( + !check_resources_supported(&without_memory, &required), + "a missing memory capability must refuse a required memory dimension" + ); + } + + /// Artifact capture is eligible for exactly two states, and that subset is + /// not the terminal set. + /// + /// A cancelled, timed-out or interrupted execution has partial output that + /// is not a declared artifact, while a failed one still produced a result + /// the caller may want. Folding the subset into the terminal set would + /// capture artifacts for cancelled work; folding the terminal set into the + /// subset would drop the artifacts of a failed run. + #[test] + fn artifact_capture_eligibility_is_exactly_succeeded_and_failed() { + let eligible: Vec<&str> = eggwork_core::ALL_EXECUTION_STATES + .iter() + .filter(|state| artifact_capture_eligible(state)) + .map(|state| state.wire_name()) + .collect(); + assert_eq!(eligible, ["Succeeded", "Failed"]); + + for state in &eggwork_core::ALL_EXECUTION_STATES { + if matches!(state, ExecutionState::Succeeded | ExecutionState::Failed) { + continue; + } + assert!( + !artifact_capture_eligible(state), + "{state:?} must not be eligible for artifact capture" + ); + } + + let eligible_count = eggwork_core::ALL_EXECUTION_STATES + .iter() + .filter(|state| artifact_capture_eligible(state)) + .count(); + let terminal_count = eggwork_core::ALL_EXECUTION_STATES + .iter() + .filter(|state| state.is_terminal()) + .count(); + assert!( + eligible_count < terminal_count, + "the capture-eligible subset must stay a strict subset of the terminal set" + ); + } + + /// Every terminal state has a metric name, and no other state has one. + /// + /// The mapping is written as an exhaustive match over the enum, so a new + /// terminal variant cannot lose its metric silently: the compiler refuses + /// the new variant until it is placed in the map. + #[test] + fn the_terminal_metric_mapping_is_total_over_the_terminal_set() { + let mut seen: Vec<(&str, &str)> = Vec::new(); + for state in &eggwork_core::ALL_EXECUTION_STATES { + match terminal_metric_name(state) { + Some(name) => { + assert!( + state.is_terminal(), + "{state:?} is not terminal but has the metric {name}" + ); + seen.push((state.wire_name(), name)); + } + None => assert!( + !state.is_terminal(), + "{state:?} is terminal but has no metric name" + ), + } + } + assert_eq!( + seen, + [ + ("Succeeded", "terminal_succeeded"), + ("Failed", "terminal_failed"), + ("Cancelled", "terminal_cancelled"), + ("TimedOut", "terminal_timed_out"), + ("Interrupted", "terminal_interrupted"), + ] + ); + } + #[test] fn server_capability_features_do_not_duplicate_static_dynamic_overlap() { - let dynamic = vec!["isolation.landlock.workspace-rw.v1".to_owned()]; + let dynamic = vec![eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY.to_owned()]; let features = server_capability_features(dynamic.clone()); assert_eq!( features .iter() - .filter(|feature| *feature == "exec.argv.v1") + .filter(|feature| *feature == eggwork_core::EXEC_ARGV_CAPABILITY) .count(), 1, "static features must not be duplicated" @@ -6205,7 +6514,9 @@ mod tests { assert_eq!( features .iter() - .filter(|feature| feature.as_str() == "isolation.landlock.workspace-rw.v1") + .filter(|feature| { + feature.as_str() == eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY + }) .count(), 1, "dynamic features must be preserved" @@ -6234,37 +6545,41 @@ mod tests { // `IsolationRequirement::None && NetworkRequirement::Unrestricted` // gate is caught here even if the integration tests are skipped on // hosts without Landlock. - let features = vec!["isolation.landlock.workspace-rw.v1".to_owned()]; - struct Probe { - features: Vec, - } - impl Probe { - fn isolation_supported(&self, requirement: &IsolationRequirement) -> bool { - match requirement { - IsolationRequirement::None | IsolationRequirement::BestEffort => true, - IsolationRequirement::Required => self - .features - .iter() - .any(|f| f == "isolation.landlock.workspace-rw.v1"), - } - } - fn network_supported(&self, network: &NetworkRequirement) -> bool { - matches!(network, NetworkRequirement::Unrestricted) - } - } - let probe = Probe { features }; - assert!(probe.isolation_supported(&IsolationRequirement::None)); - assert!(probe.isolation_supported(&IsolationRequirement::BestEffort)); - assert!(probe.isolation_supported(&IsolationRequirement::Required)); - let empty = Probe { features: vec![] }; - assert!(empty.isolation_supported(&IsolationRequirement::None)); - assert!(empty.isolation_supported(&IsolationRequirement::BestEffort)); - assert!(!empty.isolation_supported(&IsolationRequirement::Required)); - assert!(probe.network_supported(&NetworkRequirement::Unrestricted)); - assert!(!probe.network_supported(&NetworkRequirement::Disabled)); - assert!( - !probe.network_supported(&NetworkRequirement::AllowListed(vec!["example.com".into()])) - ); + // + // It calls the real admission helpers rather than a local copy of + // them: a copy would keep passing after the production rule drifted, + // which is the failure mode this milestone exists to remove. + let features = vec![eggwork_runner::LANDLOCK_WORKSPACE_RW_CAPABILITY.to_owned()]; + assert!(check_isolation_supported( + &features, + &IsolationRequirement::None + )); + assert!(check_isolation_supported( + &features, + &IsolationRequirement::BestEffort + )); + assert!(check_isolation_supported( + &features, + &IsolationRequirement::Required + )); + let empty: Vec = vec![]; + assert!(check_isolation_supported( + &empty, + &IsolationRequirement::None + )); + assert!(check_isolation_supported( + &empty, + &IsolationRequirement::BestEffort + )); + assert!(!check_isolation_supported( + &empty, + &IsolationRequirement::Required + )); + assert!(check_network_supported(&NetworkRequirement::Unrestricted)); + assert!(!check_network_supported(&NetworkRequirement::Disabled)); + assert!(!check_network_supported(&NetworkRequirement::AllowListed( + vec!["example.com".into()] + ))); } /// M004 adversarial: two authorized principals, one execution. diff --git a/crates/eggwork-server/src/operations.rs b/crates/eggwork-server/src/operations.rs index d25e671..b4de768 100644 --- a/crates/eggwork-server/src/operations.rs +++ b/crates/eggwork-server/src/operations.rs @@ -691,15 +691,7 @@ pub async fn execution_page( let total = executions.len(); let active_executions = executions .iter() - .filter(|snapshot| { - matches!( - snapshot.state, - eggwork_core::ExecutionState::Accepted - | eggwork_core::ExecutionState::Preparing - | eggwork_core::ExecutionState::Running - | eggwork_core::ExecutionState::Cancelling - ) - }) + .filter(|snapshot| snapshot.state.is_non_terminal()) .count(); let mut states = BTreeMap::new(); let mut stdout_bytes = 0u64; @@ -755,16 +747,21 @@ pub fn active_execution_count(config: &OperatorConfig) -> usize { /// connection and `serde_json`-decoded up to 2048 durable snapshots on every /// poll — thousands of connections and millions of decodes over one update — /// only to filter four state values that `executions.state` already stores as a -/// real column. The literals below are the `store::state_name` spellings, which -/// are PascalCase, not the snake_case used by `state_label` for display. +/// real column. The names bound below are the core-owned wire spellings of the +/// shared non-terminal classification, not the snake_case used by `state_label` +/// for display, and they are bound as parameters so the runtime-assembled list +/// never becomes SQL text. fn count_active_executions(config: &OperatorConfig) -> Result { require_regular_file(&config.database_path)?; let db = read_only_database(&config.database_path)?; + let states = crate::store::non_terminal_state_names(); + let placeholders = std::iter::repeat_n("?", states.len()) + .collect::>() + .join(","); let count: i64 = db .query_row( - "SELECT COUNT(*) FROM executions - WHERE state IN ('Accepted','Preparing','Running','Cancelling')", - [], + &format!("SELECT COUNT(*) FROM executions WHERE state IN ({placeholders})"), + rusqlite::params_from_iter(states.iter()), |row| row.get(0), ) .map_err(|_| OperationsError::Data)?; @@ -832,6 +829,15 @@ fn load_snapshots( Ok(snapshots) } +/// The operator-facing label for an execution state. +/// +/// This is a *display* projection, not a protocol fact. The protocol spelling +/// is `eggwork_core::ExecutionState::wire_name`, and the terminal +/// classification is `eggwork_core::ExecutionState::is_terminal`; this map +/// deliberately stays in the operator crate because snake_case is an +/// operator-facing convention rather than something the protocol-neutral core +/// should carry. The match is exhaustive with no wildcard arm, so a new state +/// variant has to be given a label here instead of falling back to a default. fn state_label(state: &eggwork_core::ExecutionState) -> &'static str { use eggwork_core::ExecutionState::*; match state { @@ -1406,6 +1412,65 @@ mod tests { assert_eq!(tree_bytes(&root).unwrap(), 0); } + /// The active-execution count selects exactly the non-terminal states. + /// + /// The list behind the drain and quiescence query is derived from the shared + /// classification at runtime and bound as SQL parameters, so this test reads + /// the same four names the drain path counts: `Accepted`, `Preparing`, + /// `Running` and `Cancelling`. A fifth name, or a missing one, changes the + /// count and fails here. + #[test] + fn the_active_execution_count_selects_exactly_the_non_terminal_states() { + let temp = TempDir::new().unwrap(); + let config = config(temp.path()); + fs::create_dir_all(config.database_path.parent().unwrap()).unwrap(); + let db = rusqlite::Connection::open(&config.database_path).unwrap(); + db.execute_batch( + "CREATE TABLE executions( + execution_id TEXT, + generation INTEGER, + state TEXT, + snapshot_json BLOB + );", + ) + .unwrap(); + for state in eggwork_core::ALL_EXECUTION_STATES { + db.execute( + "INSERT INTO executions VALUES (?1,1,?2,NULL)", + rusqlite::params![format!("exec-{}", state.wire_name()), state.wire_name()], + ) + .unwrap(); + } + drop(db); + + assert_eq!( + count_active_executions(&config).unwrap(), + 4, + "exactly Accepted, Preparing, Running and Cancelling must be counted as active" + ); + let names: Vec<&str> = crate::store::non_terminal_state_names(); + assert_eq!(names, ["Accepted", "Preparing", "Running", "Cancelling"]); + } + + /// The operator-facing state labels are unchanged. + /// + /// These labels are a display projection, not a protocol fact, and the + /// snake_case they use is what an operator sees. The test pins all nine so a + /// rename of a label is a deliberate change rather than an accident. + #[test] + fn the_operator_state_labels_are_unchanged() { + use eggwork_core::ExecutionState::*; + assert_eq!(state_label(&Accepted), "accepted"); + assert_eq!(state_label(&Preparing), "preparing"); + assert_eq!(state_label(&Running), "running"); + assert_eq!(state_label(&Cancelling), "cancelling"); + assert_eq!(state_label(&Succeeded), "succeeded"); + assert_eq!(state_label(&Failed), "failed"); + assert_eq!(state_label(&Cancelled), "cancelled"); + assert_eq!(state_label(&TimedOut), "timed_out"); + assert_eq!(state_label(&Interrupted), "interrupted"); + } + #[tokio::test] async fn execution_listing_is_bounded_and_paginates_over_durable_records() { let temp = TempDir::new().unwrap(); @@ -1419,7 +1484,7 @@ mod tests { for index in 0..3u64 { let id = ExecutionId::new(format!("exec-{index}")).unwrap(); let snapshot = eggwork_core::ExecutionSnapshot { - schema_version: 1, + schema_version: eggwork_core::API_SCHEMA_VERSION, execution_id: id.clone(), generation: ExecutionGeneration::new(1).unwrap(), state: if index == 1 { diff --git a/crates/eggwork-server/src/store.rs b/crates/eggwork-server/src/store.rs index f227dc2..59e63cf 100644 --- a/crates/eggwork-server/src/store.rs +++ b/crates/eggwork-server/src/store.rs @@ -166,11 +166,7 @@ impl ExecutionStore { match latest { None if generation != 1 => return Ok(ReserveResult::StaleGeneration), Some((latest_generation, latest_state)) => { - if generation != latest_generation + 1 - || !matches!( - latest_state.as_str(), - "Succeeded" | "Failed" | "Cancelled" | "TimedOut" | "Interrupted" - ) + if generation != latest_generation + 1 || !stored_state_is_terminal(&latest_state) { return Ok(ReserveResult::StaleGeneration); } @@ -200,7 +196,7 @@ impl ExecutionStore { principal_id, lease_token_hash, lease_expires_unix_ms, - state_name(&snapshot.state), + snapshot.state.wire_name(), encoded, now, ], @@ -307,7 +303,7 @@ impl ExecutionStore { transaction.rollback()?; return Ok(None); }; - if is_terminal_name(&state) { + if stored_state_is_terminal(&state) { transaction.rollback()?; return Ok(None); } @@ -329,7 +325,7 @@ impl ExecutionStore { params![ id, generation, - state_name(&snapshot.state), + snapshot.state.wire_name(), sequence + 1, serde_json::to_vec(&snapshot)?, now, @@ -374,7 +370,7 @@ impl ExecutionStore { return Ok(None); }; if current_hash != lease_token_hash - || is_terminal_name(&state) + || stored_state_is_terminal(&state) || current_expiry <= unix_millis() { transaction.rollback()?; @@ -563,10 +559,21 @@ impl ExecutionStore { tokio::task::spawn_blocking(move || { let mut connection = connection.lock().map_err(|_| StoreError::Worker)?; let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?; - let mut statement = transaction.prepare( - "SELECT snapshot_json FROM executions WHERE state IN ('Accepted', 'Preparing', 'Running', 'Cancelling')", - )?; - let rows = statement.query_map([], |row| row.get::<_, Vec>(0))?; + // The in-flight states come from the shared classification, and the + // names are bound as parameters rather than spliced into the + // statement: the list is assembled at runtime, and a value written + // into SQL text would turn a protocol fact into an injection + // surface. + let states = non_terminal_state_names(); + let placeholders = std::iter::repeat_n("?", states.len()) + .collect::>() + .join(","); + let mut statement = transaction.prepare(&format!( + "SELECT snapshot_json FROM executions WHERE state IN ({placeholders})" + ))?; + let rows = statement.query_map(rusqlite::params_from_iter(states.iter()), |row| { + row.get::<_, Vec>(0) + })?; let mut snapshots = rows .map(|row| serde_json::from_slice::(&row?).map_err(StoreError::from)) .collect::, _>>()?; @@ -599,12 +606,19 @@ impl ExecutionStore { metadata: EventMetadata { fields: vec![] }, }; transaction.execute( - "UPDATE executions SET state = 'Interrupted', next_sequence = ?3, - snapshot_json = ?4, updated_unix_ms = ?5 + // The recovered state is bound from the core-owned wire + // spelling rather than typed into the statement. The + // stored bytes are unchanged — the column still receives + // `Interrupted` — but the journal's vocabulary now has a + // single owner instead of a literal here and a list + // there. + "UPDATE executions SET state = ?3, next_sequence = ?4, + snapshot_json = ?5, updated_unix_ms = ?6 WHERE execution_id = ?1 AND generation = ?2", params![ snapshot.execution_id.as_str(), generation, + ExecutionState::Interrupted.wire_name(), sequence + 1, serde_json::to_vec(snapshot)?, unix_millis(), @@ -667,27 +681,33 @@ pub fn unix_millis() -> i64 { .min(i64::MAX as u128) as i64 } -fn state_name(state: &ExecutionState) -> &'static str { - match state { - ExecutionState::Accepted => "Accepted", - ExecutionState::Preparing => "Preparing", - ExecutionState::Running => "Running", - ExecutionState::Cancelling => "Cancelling", - ExecutionState::Succeeded => "Succeeded", - ExecutionState::Failed => "Failed", - ExecutionState::Cancelled => "Cancelled", - ExecutionState::TimedOut => "TimedOut", - ExecutionState::Interrupted => "Interrupted", - } +/// The wire spelling of every state that is still in flight. +/// +/// Derived from the core-owned classification so the journal's vocabulary and +/// the in-memory classification cannot drift apart. Callers bind these names +/// as SQL parameters; they are never interpolated into a statement. +pub(crate) fn non_terminal_state_names() -> Vec<&'static str> { + eggwork_core::ALL_EXECUTION_STATES + .iter() + .filter(|state| state.is_non_terminal()) + .map(|state| state.wire_name()) + .collect() } -fn is_terminal_name(state: &str) -> bool { - matches!( - state, - "Succeeded" | "Failed" | "Cancelled" | "TimedOut" | "Interrupted" - ) +/// Whether a stored `state` column value names a terminal state. +/// +/// The column holds the core-owned wire spelling, so a stored row's +/// terminality is answered by the same core-owned classification the +/// in-memory paths use. The spelling is resolved back to its state rather +/// than being matched against a second list of names here, so a new variant +/// is classified correctly without any change to this function. A value that +/// names no known state is not terminal, exactly as before. +fn stored_state_is_terminal(stored: &str) -> bool { + eggwork_core::ALL_EXECUTION_STATES + .iter() + .find(|state| state.wire_name() == stored) + .is_some_and(|state| state.is_terminal()) } - #[cfg(test)] mod tests { use super::*; @@ -695,7 +715,7 @@ mod tests { fn snapshot(id: &str, generation: u64, state: ExecutionState) -> ExecutionSnapshot { ExecutionSnapshot { - schema_version: 1, + schema_version: eggwork_core::API_SCHEMA_VERSION, execution_id: ExecutionId::new(id).unwrap(), generation: ExecutionGeneration::new(generation).unwrap(), state, @@ -750,6 +770,57 @@ mod tests { ); } + /// The `state` column still stores the same PascalCase spellings. + /// + /// The column's vocabulary is now derived from the core-owned wire spelling + /// rather than from a hand-maintained list in this file, so this test is what + /// proves the stored bytes did not move: the column still receives exactly + /// the spellings it received before. + #[tokio::test] + async fn the_state_column_stores_the_pascal_case_wire_spelling() { + let temp = TempDir::new().unwrap(); + let path = temp.path().join("state.sqlite"); + let store = ExecutionStore::open(&path).unwrap(); + + for (state, expected) in [ + (ExecutionState::Running, "Running"), + (ExecutionState::TimedOut, "TimedOut"), + (ExecutionState::Interrupted, "Interrupted"), + ] { + // One execution per state: a stored terminal state refuses further + // events, so a second commit on the same row would be rolled back + // and would never reach the column. + let accepted = snapshot( + &format!("column-spelling-{expected}"), + 1, + ExecutionState::Accepted, + ); + reserve(&store, accepted.clone()).await; + let proposed = ExecutionSnapshot { + state: state.clone(), + ..accepted + }; + store + .commit_event(proposed.clone(), ExecutionEventKind::State(state.clone())) + .await + .unwrap(); + let connection = rusqlite::Connection::open(&path).unwrap(); + let stored: String = connection + .query_row( + "SELECT state FROM executions WHERE execution_id = ?1", + [proposed.execution_id.as_str()], + |row| row.get(0), + ) + .unwrap(); + drop(connection); + assert_eq!( + stored, expected, + "the state column must store the core-owned wire spelling" + ); + assert_eq!(stored, state.wire_name()); + } + } + #[tokio::test] async fn recovery_marks_uncertain_work_interrupted_and_never_replays_it() { let temp = TempDir::new().unwrap(); diff --git a/crates/eggwork-server/tests/shared_contract_ownership.rs b/crates/eggwork-server/tests/shared_contract_ownership.rs new file mode 100644 index 0000000..864eff7 --- /dev/null +++ b/crates/eggwork-server/tests/shared_contract_ownership.rs @@ -0,0 +1,237 @@ +//! Each shared protocol contract fact has exactly one owner. +//! +//! Three facts used to be stated by more than one owner, and the copies had +//! no mechanical relationship: the control-plane schema version, the +//! `exec.argv.v1` capability name, and the terminal/non-terminal +//! classification of `ExecutionState`. Both sides of every pair agreed by +//! value, so none of it was a live bug — the defect was structural, because a +//! future rename or bump on the producing side would have desynchronised the +//! consuming side silently. +//! +//! The behavioural tests prove the values agree today. These tests prove the +//! *shape* of the ownership: that the copies are gone. A private copy +//! reintroduced in an endpoint crate would leave every behavioural test +//! green — the copy would hold the same value — and would fail here. +//! +//! The scan is a source check rather than a behavioural one on purpose: there +//! is no way to observe "a second declaration exists" from outside the +//! crate, and a private copy that happens to hold the right value is exactly +//! the thing that has to be caught. + +use std::path::{Path, PathBuf}; + +fn workspace_root() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .parent() + .and_then(Path::parent) + .expect("the server crate lives inside the workspace") + .to_path_buf() +} + +fn read(relative: &str) -> String { + let path = workspace_root().join(relative); + std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("cannot read {}: {error}", path.display())) +} + +/// The production part of a source file. +/// +/// Everything before the first `#[cfg(test)]` item. In the endpoint crates the +/// test modules are all at the end of the file, so this is exactly the +/// production code. A literal that only appears in a test module is not a +/// second *production* copy of a contract fact, so the scan ignores it — the +/// tests are allowed to name the values they assert. +fn production_source(relative: &str) -> String { + let source = read(relative); + match source.find("#[cfg(test)]") { + Some(index) => source[..index].to_owned(), + None => source, + } +} + +/// The number of occurrences of the given needle in the given text. +fn occurrences(haystack: &str, needle: &str) -> usize { + haystack.matches(needle).count() +} + +/// The schema version is declared once in the workspace, in `eggwork-core`. +/// +/// This is the check that fails if a private copy is reintroduced in the +/// client or the server: the second `const API_SCHEMA_VERSION` declaration +/// would make this count exceed one. +#[test] +fn the_schema_version_is_declared_exactly_once_in_the_workspace() { + let mut declarations: Vec<(String, usize)> = Vec::new(); + for relative in [ + "crates/eggwork-core/src/lib.rs", + "crates/eggwork-client/src/lib.rs", + "crates/eggwork-server/src/lib.rs", + "crates/eggwork-runner/src/lib.rs", + "crates/eggwork-sandbox-helper/src/main.rs", + ] { + let source = read(relative); + let count = occurrences(&source, "const API_SCHEMA_VERSION"); + if count > 0 { + declarations.push((relative.to_owned(), count)); + } + } + assert_eq!( + declarations, + vec![("crates/eggwork-core/src/lib.rs".to_owned(), 1)], + "the schema version must be declared once, publicly, in eggwork-core" + ); + + // The core's declaration must be public, or the endpoint crates could not + // import it and would have to keep a copy. + let core = read("crates/eggwork-core/src/lib.rs"); + assert!( + core.contains("pub const API_SCHEMA_VERSION: u16 = 1;"), + "the core's schema version must be public and frozen at 1" + ); +} + +/// Neither endpoint crate re-types the argv capability name. +/// +/// The server produces the name and the client consumes it, so a literal in +/// either production file is a second copy waiting to drift. +#[test] +fn the_argv_capability_name_is_not_retyped_in_either_endpoint_crate() { + for relative in [ + "crates/eggwork-client/src/lib.rs", + "crates/eggwork-server/src/lib.rs", + ] { + let source = production_source(relative); + assert_eq!( + occurrences(&source, "\"exec.argv.v1\""), + 0, + "{relative} must import the owned capability name, not re-type it" + ); + } +} + +/// The server does not re-type the runner's cgroup feature names. +/// +/// The runner produces them; the server only consumes them. +#[test] +fn the_cgroup_feature_names_are_not_retyped_in_the_server() { + let source = production_source("crates/eggwork-server/src/lib.rs"); + for literal in [ + "\"resources.cgroups-v2.memory\"", + "\"resources.cgroups-v2.cpu\"", + "\"resources.cgroups-v2.pids\"", + ] { + assert_eq!( + occurrences(&source, literal), + 0, + "the server must import the runner's exported constant, not re-type {literal}" + ); + } +} + +/// Each capability feature literal is first declared in the constant that owns +/// it. +/// +/// The runner's source has test modules in the middle of the file, so the +/// check is "the first occurrence of the literal is the owning constant's +/// declaration" rather than "the literal occurs once". A literal typed back +/// into the advertisement site — which sits *above* the constants — would +/// become the first occurrence and fail this. +#[test] +fn the_runner_declares_each_capability_literal_in_the_constant_that_owns_it() { + let source = read("crates/eggwork-runner/src/lib.rs"); + let lines: Vec<&str> = source.lines().collect(); + for (constant, literal) in [ + ( + "pub const LANDLOCK_WORKSPACE_RW_CAPABILITY", + "\"isolation.landlock.workspace-rw.v1\"", + ), + ( + "pub const CGROUPS_V2_MEMORY_CAPABILITY", + "\"resources.cgroups-v2.memory\"", + ), + ( + "pub const CGROUPS_V2_CPU_CAPABILITY", + "\"resources.cgroups-v2.cpu\"", + ), + ( + "pub const CGROUPS_V2_PIDS_CAPABILITY", + "\"resources.cgroups-v2.pids\"", + ), + ("pub const WORKSPACE_RW_PROFILE", "\"workspace_rw\""), + ] { + let literal_line = lines + .iter() + .position(|line| line.contains(literal)) + .unwrap_or_else(|| panic!("{literal} is not declared in the runner")); + let constant_line = lines + .iter() + .position(|line| line.contains(constant)) + .unwrap_or_else(|| panic!("{constant} is not declared in the runner")); + assert_eq!( + literal_line, constant_line, + "{literal} must first appear in {constant}, not at an earlier site" + ); + } +} + +/// The server's production code names no execution state as a string. +/// +/// The state vocabulary is derived from the core-owned wire spelling: the +/// store writes it, the store reads it back, and the operator query filters +/// on it. A state name written as a literal in any of these files would be a +/// copy that the shared classification no longer governs. +#[test] +fn the_server_names_no_execution_state_as_a_string_literal() { + for relative in [ + "crates/eggwork-server/src/lib.rs", + "crates/eggwork-server/src/store.rs", + "crates/eggwork-server/src/operations.rs", + ] { + let source = production_source(relative); + for name in [ + "Accepted", + "Preparing", + "Running", + "Cancelling", + "Succeeded", + "Failed", + "Cancelled", + "TimedOut", + "Interrupted", + ] { + assert_eq!( + occurrences(&source, &format!("\"{name}\"")), + 0, + "{relative} must not name the state {name} as a string literal" + ); + assert_eq!( + occurrences(&source, &format!("'{name}'")), + 0, + "{relative} must not name the state {name} as a SQL literal" + ); + } + } +} + +/// The core's `ExecutionState` keeps its derived wire representation. +/// +/// A `#[serde(rename_all = ...)]` attribute on the enum would move every +/// persisted and transmitted state. The attribute must not be there. +#[test] +fn the_core_state_enum_keeps_its_derived_wire_representation() { + let source = read("crates/eggwork-core/src/lib.rs"); + let enum_start = source + .find("pub enum ExecutionState") + .expect("the enum is declared in the core crate"); + let declaration = &source[enum_start..]; + let end = declaration.find("\n}").expect("the enum declaration ends"); + let declaration = &declaration[..end]; + assert!( + !declaration.contains("rename"), + "the state enum must keep its derived Serialize/Deserialize representation" + ); + assert!( + !declaration.contains("serde("), + "the state enum must keep its derived Serialize/Deserialize representation" + ); +} diff --git a/plans/closure/control-plane-protocol/004-status.md b/plans/closure/control-plane-protocol/004-status.md new file mode 100644 index 0000000..ce05bcc --- /dev/null +++ b/plans/closure/control-plane-protocol/004-status.md @@ -0,0 +1,314 @@ +# Control Plane M004 Closure — Shared Protocol Contract Corrective + +Status: closed + +Source plan: `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md` + +Corrective addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` + +Decision record: `plans/adrs/ADR-0008-core-protocol-contract-ownership.md` + +Roadmap: `plans/subsystems/control-plane-protocol-roadmap.md` + +## Reviewed baseline and implementation + +- Reviewed parent head: `63699df` (branch `corrective/interrogation-batch-2026-10`). +- Implementation commit: `IMPLEMENTATION-COMMIT-PENDING`. +- Crates changed: `eggwork-core`, `eggwork-client`, `eggwork-runner`, `eggwork-server`. The + sandbox helper's **production** code is unchanged; only its test file changed. +- `eggwork-core` (`crates/eggwork-core/src/lib.rs`) — new public surface: + `API_SCHEMA_VERSION`, `EXEC_ARGV_CAPABILITY`, `ALL_EXECUTION_STATES`, and on `ExecutionState` + the methods `is_terminal`, `is_non_terminal`, `wire_name`. The enum's derives are untouched. +- `eggwork-client` (`crates/eggwork-client/src/lib.rs`) — the private + `const API_SCHEMA_VERSION` was deleted and the core constant imported; the literal + `"exec.argv.v1"` in `ensure_protocol_compatible` was replaced by + `eggwork_core::EXEC_ARGV_CAPABILITY`; the protocol decision was split into a pure + `protocol_compatibility` helper so it can be tested without a live node. +- `eggwork-runner` (`crates/eggwork-runner/src/lib.rs`) — new public surface: + `CGROUPS_V2_MEMORY_CAPABILITY`, `CGROUPS_V2_CPU_CAPABILITY`, `CGROUPS_V2_PIDS_CAPABILITY`, + `WORKSPACE_RW_PROFILE`. The advertisement site (`TrustedLandlockSetup::execution_capabilities`) + now names constants; the probe table was extracted to the module-level + `CGROUP_PROBE_TABLE` so a test can read the names it would advertise. +- `eggwork-server` (`crates/eggwork-server/src/lib.rs`, `store.rs`, `operations.rs`) — the private + `const API_SCHEMA_VERSION` was deleted and the core constant imported; `static_capability_features` + names `eggwork_core::EXEC_ARGV_CAPABILITY`; `check_resources_supported` names the runner's + constants; the private `is_terminal` was removed in favour of `ExecutionState::is_terminal`; + the artifact-capture subset became `artifact_capture_eligible`; the metric map became the + exhaustive `terminal_metric_name`; `store::state_name` and `store::is_terminal_name` were removed + in favour of `ExecutionState::wire_name`, `store::stored_state_is_terminal`, and + `store::non_terminal_state_names`. + +**Inspection only (no executed evidence):** the facts above were established by reading the +source at the reviewed head. Every behavioural claim in this record is backed by a test that was +actually run; see the matrix and the command log below. + +## Requirement-to-evidence matrix + +§11's twenty acceptance criteria, one row each. Every row names an implementation site and a test. + +| # | Criterion | Implementation site | Test | +|---|---|---|---| +| 1 | `API_SCHEMA_VERSION` declared exactly once, publicly, in `eggwork-core` | `crates/eggwork-core/src/lib.rs` (`pub const API_SCHEMA_VERSION`); the private constants in `crates/eggwork-client/src/lib.rs` and `crates/eggwork-server/src/lib.rs` were deleted | `crates/eggwork-server/tests/shared_contract_ownership.rs::the_schema_version_is_declared_exactly_once_in_the_workspace` | +| 2 | Client bodies and server accept/reject paths both resolve to the core constant; a private copy would fail a test | `crates/eggwork-client/src/lib.rs` (`API_SCHEMA_VERSION` import); `crates/eggwork-server/src/lib.rs` (`execute`, `workspace_create`, `workspace_derive` compare against the imported constant) | `shared_contract_ownership.rs::the_schema_version_is_declared_exactly_once_in_the_workspace`; `crates/eggwork-client/src/lib.rs::shared_contract_tests::every_authored_request_body_carries_the_shared_schema_version`; `crates/eggwork-server/src/lib.rs::tests::the_client_and_the_node_agree_on_the_control_plane_schema_version` | +| 3 | A test fails if the client-sent and server-accepted versions can diverge, exercising the real client-built body | `crates/eggwork-server/src/lib.rs::tests::the_client_and_the_node_agree_on_the_control_plane_schema_version` (real `NodeClient::execute` against a live node) | same | +| 4 | The runner exports the three cgroup constants and the advertisement site uses them; no feature literal remains at the site | `crates/eggwork-runner/src/lib.rs` (`CGROUPS_V2_*_CAPABILITY`, `CGROUP_PROBE_TABLE`, `TrustedLandlockSetup::execution_capabilities`) | `crates/eggwork-runner/src/lib.rs::tests::the_probe_table_advertises_exactly_the_exported_constants`; `crates/eggwork-server/tests/shared_contract_ownership.rs::the_runner_declares_each_capability_literal_in_the_constant_that_owns_it` | +| 5 | The server imports the runner's constants; the cgroup names are not re-typed there | `crates/eggwork-server/src/lib.rs::check_resources_supported` | `crates/eggwork-server/src/lib.rs::tests::the_resource_admission_rule_reads_the_runner_constants`; `shared_contract_ownership.rs::the_cgroup_feature_names_are_not_retyped_in_the_server` | +| 6 | `exec.argv.v1` is core-owned and imported by both endpoint crates; the literal appears in neither production file | `crates/eggwork-core/src/lib.rs` (`EXEC_ARGV_CAPABILITY`); `crates/eggwork-server/src/lib.rs::static_capability_features`; `crates/eggwork-client/src/lib.rs::protocol_compatibility` | `shared_contract_ownership.rs::the_argv_capability_name_is_not_retyped_in_either_endpoint_crate`; `crates/eggwork-server/src/lib.rs::tests::the_advertised_argv_feature_is_the_one_the_owner_declares`; `crates/eggwork-client/src/lib.rs::shared_contract_tests::a_node_advertising_a_differing_argv_feature_is_refused` | +| 7 | `workspace_rw` is a `pub` constant used at all three runner sites; the helper's production code is unmodified and its literal is pinned | `crates/eggwork-runner/src/lib.rs` (`WORKSPACE_RW_PROFILE`; used in `TrustedLandlockSetup::prepare`, `RunnerRequest::from_spec`, `SandboxChannel::new`); `crates/eggwork-sandbox-helper/src/main.rs` unchanged | `crates/eggwork-sandbox-helper/tests/landlock_runner.rs::the_runner_profile_is_granted_and_a_differing_one_is_refused_before_the_target_spawns`; `crates/eggwork-runner/src/lib.rs::tests::the_workspace_rw_profile_name_is_frozen` | +| 8 | Every capability feature-name value is byte-for-byte identical to its pre-M004 value | `crates/eggwork-core/src/lib.rs`; `crates/eggwork-runner/src/lib.rs` | `crates/eggwork-core/tests/shared_protocol_contract.rs::the_exec_argv_capability_name_is_frozen`; `crates/eggwork-runner/src/lib.rs::tests::capability_feature_string_is_frozen_for_workspace_rw_profile`, `::cgroup_capability_feature_strings_are_frozen`, `::the_workspace_rw_profile_name_is_frozen` | +| 9 | `eggwork-core` owns the classification; both the predicate and the wire spelling are exhaustive matches with no wildcard arm | `crates/eggwork-core/src/lib.rs` (`ExecutionState::is_terminal`, `::is_non_terminal`, `::wire_name`) | `crates/eggwork-core/tests/shared_protocol_contract.rs::every_state_is_classified_into_exactly_one_set`, `::the_terminal_set_has_five_members_and_the_non_terminal_set_four`; the exhaustive-match property is additionally shown by the adversarial tenth-variant build break below | +| 10 | No terminal-state enumeration remains in the server's `store.rs`, `lib.rs`, or `operations.rs` | `crates/eggwork-server/src/store.rs` (`stored_state_is_terminal`, `non_terminal_state_names`; the recovery `UPDATE` binds the state); `crates/eggwork-server/src/lib.rs` (`terminal_metric_name`, `artifact_capture_eligible`); `crates/eggwork-server/src/operations.rs` (`execution_page` uses `is_non_terminal`; `count_active_executions` binds the derived list) | `shared_contract_ownership.rs::the_server_names_no_execution_state_as_a_string_literal` | +| 11 | A property test proves the classification is total and disjoint, and adding a variant breaks the build or the test | `crates/eggwork-core/src/lib.rs` (`ALL_EXECUTION_STATES`) | `crates/eggwork-core/tests/shared_protocol_contract.rs::every_state_is_classified_into_exactly_one_set`, `::the_terminal_set_has_five_members_and_the_non_terminal_set_four`, `::the_execution_state_enum_has_exactly_nine_variants` — plus the adversarial tenth-variant build break recorded below | +| 12 | The `state` column stores the same values as before, and the active-execution SQL selects exactly `Accepted`, `Preparing`, `Running`, `Cancelling` | `crates/eggwork-server/src/store.rs` (`ExecutionState::wire_name` at the column write); `crates/eggwork-server/src/operations.rs::count_active_executions` | `crates/eggwork-server/src/store.rs::tests::the_state_column_stores_the_pascal_case_wire_spelling`; `crates/eggwork-server/src/operations.rs::tests::the_active_execution_count_selects_exactly_the_non_terminal_states` | +| 13 | The capture-eligibility predicate accepts exactly `Succeeded` and `Failed` and stays distinct from terminality | `crates/eggwork-server/src/lib.rs::artifact_capture_eligible` | `crates/eggwork-server/src/lib.rs::tests::artifact_capture_eligibility_is_exactly_succeeded_and_failed` | +| 14 | The metric mapping is total over the terminal set and the operator-facing labels are byte-identical | `crates/eggwork-server/src/lib.rs::terminal_metric_name`; `crates/eggwork-server/src/operations.rs::state_label` | `crates/eggwork-server/src/lib.rs::tests::the_terminal_metric_mapping_is_total_over_the_terminal_set`; `crates/eggwork-server/src/operations.rs::tests::the_operator_state_labels_are_unchanged` | +| 15 | `ExecutionState`'s wire representation is unchanged — derived `Serialize`/`Deserialize`, no rename attribute | `crates/eggwork-core/src/lib.rs` (derives untouched) | `crates/eggwork-core/tests/shared_protocol_contract.rs::the_state_wire_form_is_still_a_bare_pascal_case_string`, `::the_wire_spelling_matches_the_derived_serde_representation`; `shared_contract_ownership.rs::the_core_state_enum_keeps_its_derived_wire_representation` | +| 16 | No new crate dependency edge; `eggwork-core` still has no internal dependency; the helper still has no workspace-crate dependency | no `Cargo.toml` was touched | `python3 scripts/check_execution_ownership.py` (crate dependency direction passed); `git diff --stat -- '*Cargo.toml'` is empty | +| 17 | The §10 commands pass and the focused per-crate runs are recorded | — | the command log below | +| 18 | The §9 documentation updates are applied and the touched documents cite by symbol name | `architecture/core-domain.md`, `architecture/overview.md` (divergence #12 only), `architecture/client-transport.md`, `architecture/server-node.md`, `architecture/storage-journal.md`, `architecture/runner-execution.md` | review of the diff; `git diff --check` is clean | +| 19 | This closure record exists and satisfies §13 | `plans/closure/control-plane-protocol/004-status.md` | this document | +| 20 | No high or medium finding remains without an explicit owner | — | the findings section below | + +## Tests and commands actually run + +### Pre-submit gate + +| Command | Outcome | +|---|---| +| `python3 scripts/check_execution_ownership.py` | **passed** — "execution ownership guard passed; approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)"; "crate dependency direction passed" | +| `python3 scripts/check_execution_ownership.py --prove-negative-exit` | **passed** — "negative scanner self-test passed"; the synthetic forbidden spawn was detected | +| `cargo fmt --all -- --check` | **passed** (run after `cargo fmt --all`; only files inside this milestone's ownership differed, and the re-check was clean) | +| `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` | **passed** after one fix — the first run failed with `clippy::redundant_static_lifetimes` on `CGROUP_PROBE_TABLE`'s `&'static str` element type; the lifetime was removed and the re-run passed. No rerun was reported as a fix without the underlying change. | +| `cargo check --locked --workspace --all-targets` | **passed** | +| `cargo test --locked --workspace --all-targets` | **not run by this milestone** — the coordinator runs the whole-workspace gate once at the end of the batch. The per-crate runs below cover every crate this milestone touched. | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` | **not run by this milestone** — the coordinator runs the release-harness suite once at the end of the batch. This milestone changes no release script, artifact form, or release target. | +| `git diff --check` | **passed** (no whitespace errors) | + +### Focused per-crate runs + +| Command | Outcome | +|---|---| +| `cargo test --locked -p eggwork-core --all-targets` | **passed** — 32 lib tests + 7 in `tests/shared_protocol_contract.rs` | +| `cargo test --locked -p eggwork-client --all-targets` | **passed** — 10 tests | +| `cargo test --locked -p eggwork-client --features eggress-route --all-targets` | **passed** — 13 tests (the server's dev-dependency on the client enables this feature, so the cross-crate agreement test compiles and runs under it) | +| `cargo test --locked -p eggwork-runner --all-targets` | **passed** — 28 lib + 2 `capability_probe` + 7 `diagnostic_degradation` + 5 `environment_policy` + 0 `windows_process_tree`. **Note:** in this invocation `capability_probe::trusted_helper_advertises_landlock_workspace_rw_capability` printed "eggwork-sandbox-helper is not built; skipping" and returned early — the probe locates the helper binary through `CARGO_TARGET_DIR`/`OUT_DIR`, and a `-p eggwork-runner` test run builds neither. The same test was re-run with `CARGO_TARGET_DIR` pointed at the workspace target directory, where it **did** execute and passed (see the platform matrix). | +| `cargo test --locked -p eggwork-server --all-targets` | **passed** — 150 lib + 0 `eggworkd` + 3 `gc_preview_parity` + 12 `host_telemetry` + 0 `installed_qualification` (ignored, opt-in) + 36 `release_contract` + 6 `shared_contract_ownership` | +| `cargo test --locked -p eggwork-sandbox-helper --all-targets` | **passed** — 12 `environment_policy_parity` + 18 `landlock_runner` | +| `CARGO_TARGET_DIR=/home/sugarwookie/projects/eggwork/target cargo test --locked -p eggwork-runner --test capability_probe` | **passed** — 2 tests, and this time the Landlock advertisement assertion **executed** rather than skipping (the probe locates the helper binary through `CARGO_TARGET_DIR`/`OUT_DIR`, which the plain `-p eggwork-runner` invocation does not provide). Run to establish that the runner's advertisement path really advertises `LANDLOCK_WORKSPACE_RW_CAPABILITY` on this host. | + +### Failures observed and how they were resolved + +Recorded honestly; a rerun is not a fix. + +1. **`cargo clippy` — `clippy::redundant_static_lifetimes`** on + `crates/eggwork-runner/src/lib.rs` (`CGROUP_PROBE_TABLE: [(&'static str, …)]`). *Fix:* the + element type was changed to `&str`; the lint is gone because the constant is `'static` by + default. Re-run passed. +2. **`the_state_column_stores_the_pascal_case_wire_spelling` failed** with + `left: "TimedOut", right: "Interrupted"`. The test committed three states onto one row, and a + stored terminal state refuses further events, so the third commit was rolled back. *Fix:* the + test now uses one execution per state. No production code was changed for this. +3. **`the_client_and_the_node_agree_on_the_control_plane_schema_version` failed** with + `ClientError::Api { status: 503, code: "busy" }`. The test's first raw POST had started an + execution that occupied the node's single permit. *Fix:* the accepted body now carries an + invalid specification on purpose, so it passes the version gate and is refused later without + starting an execution. No production code was changed for this. + +## Platform and feature matrix actually exercised + +Host: **Linux x86_64**, kernel `6.8.0-147-generic`, Rust **1.89.0** as pinned by +`rust-toolchain.toml`. + +| Path | Exercised? | Evidence / what was *not* covered | +|---|---|---| +| Linux Landlock (helper enforcement, `workspace_rw`) | **yes** | `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` ran 18 tests green, including `required_landlock_allows_workspace_and_denies_outside_reads_and_writes` and the new `the_runner_profile_is_granted_and_a_differing_one_is_refused_before_the_target_spawns` — the latter drives the real helper binary with the runner's own profile and observes a confined target run. The runner's *advertisement* probe was additionally executed by re-running `cargo test --locked -p eggwork-runner --test capability_probe` with `CARGO_TARGET_DIR` pointed at the workspace target directory (in the plain `-p eggwork-runner` invocation it skips, because that crate's test run does not build the helper binary); with the helper located, `trusted_helper_advertises_landlock_workspace_rw_capability` ran and passed, i.e. this host advertises `LANDLOCK_WORKSPACE_RW_CAPABILITY`. | +| Linux cgroup v2 (memory / CPU / pids) | **yes** | `crates/eggwork-sandbox-helper/tests/landlock_runner.rs::required_memory_limit_is_enforced_and_classified` ran a **required** 16 MiB memory dimension and observed `ResourceLimit` / `ResourceDimensionResult::LimitExceeded`; `required_pid_limit_is_enforced_and_classified` and `required_cpu_quota_is_verified_before_target_start` did the same for pids and CPU. A *required* dimension errors out when the systemd transient-cgroup backend is unavailable, so the cgroup backend was available and enforcing on this host. `concurrent_resource_scopes_keep_pid_limits_isolated` also passed. | +| Windows Job Object process tree | **not exercised** | `crates/eggwork-runner/tests/windows_process_tree.rs` reported `0 passed` — the file is `#[cfg(windows)]`-gated. No Windows host was available. **Windows is not claimed.** | +| macOS fail-closed path | **not exercised** | No macOS host was available. The non-Linux stubs were not run. **macOS is not claimed.** | +| `eggwork-client/eggress-route` feature | **yes** | `cargo test --locked -p eggwork-client --features eggress-route --all-targets` — 13 tests green, including `route_failure_does_not_connect_direct_and_preserves_typed_error`. | +| Server mTLS control plane | **yes** | The cross-crate agreement test starts a real `NodeServer` with generated mTLS material and drives the real `NodeClient` over loopback TLS. | +| `installed_qualification` (hosted qualification) | **not exercised** | Ignored and opt-in; it needs `EGGWORK_QUALIFY_DAEMON`/`EGGWORK_QUALIFY_CONFIG`/`EGGWORK_QUALIFY_TLS_DIR` and an installed node. Not required by this milestone. | + +Nothing above is claimed on the strength of compilation. The Windows and macOS paths are +**not qualified** by this run. + +## Negative and adversarial evidence + +All of the following were executed; the quoted output is what the run produced. + +1. **A private schema-version copy in the client does not compile.** Reintroducing + `const API_SCHEMA_VERSION: u16 = 1;` beside the imported name produced + `error[E0255]: API_SCHEMA_VERSION redefined here`. The compiler prevents the copy outright. +2. **A private schema-version copy that *does* compile is caught by the ownership test.** + With the import renamed to `CoreApiSchemaVersion` and a private + `const API_SCHEMA_VERSION: u16 = 1;` added, + `the_schema_version_is_declared_exactly_once_in_the_workspace` failed with + `left: [("crates/eggwork-core/src/lib.rs", 1), ("crates/eggwork-client/src/lib.rs", 1)]`. +3. **A private copy with a divergent value breaks the cross-crate agreement test.** With the + client's private constant set to `2`, + `the_client_and_the_node_agree_on_the_control_plane_schema_version` failed with + `ClientError::Api { status: 426, code: "protocol_version" }` — the real divergence the + milestone exists to prevent. +4. **The argv capability literal retyped in the client is caught.** + `the_argv_capability_name_is_not_retyped_in_either_endpoint_crate` failed with + "crates/eggwork-client/src/lib.rs must import the owned capability name, not re-type it". +5. **A mis-edited classification is caught.** Moving `Failed` from the terminal arm to the + non-terminal arm of `ExecutionState::is_terminal` failed two core tests: + `every_state_is_classified_into_exactly_one_set` ("Failed is classified as both terminal and + non-terminal, or as neither") and `the_terminal_set_has_five_members_and_the_non_terminal_set_four` + (`left: ["Succeeded", "Cancelled", "TimedOut", "Interrupted"]`). +6. **Adding a tenth variant to `ExecutionState` breaks the build.** Adding `Quarantined` produced + three `error[E0004]: non-exhaustive patterns: &ExecutionState::Quarantined not covered` errors + in `eggwork-core`, one for each exhaustive match (`is_terminal`, `is_non_terminal`, + `wire_name`). This is the primary mechanism behind criterion 11; the + `the_execution_state_enum_has_exactly_nine_variants` assertion is the secondary one. +7. **A schema-version mismatch still yields 426 `protocol_version`.** + `the_client_and_the_node_agree_on_the_control_plane_schema_version` posts a body with + `API_SCHEMA_VERSION + 1` and asserts `426`. +8. **A resource capability name differing by one character still yields a refusal.** + `the_resource_admission_rule_reads_the_runner_constants` rewrites each of the three runner + constants with a trailing `x` and asserts that the required dimension is refused. +9. **A sandbox profile differing from the runner's still fails before the target spawns.** + `the_runner_profile_is_granted_and_a_differing_one_is_refused_before_the_target_spawns` + asserts status byte `12` for a profile one character off and that the target marker was never + created. +10. **The artifact-capture predicate still rejects `Cancelled`, `TimedOut`, and `Interrupted`.** + `artifact_capture_eligibility_is_exactly_succeeded_and_failed` asserts the eligible set is + exactly `["Succeeded", "Failed"]`, that every other variant is ineligible, and that the + eligible count is strictly smaller than the terminal count. +11. **The active-execution SQL still excludes terminal states.** + `the_active_execution_count_selects_exactly_the_non_terminal_states` seeds one row per + variant and asserts the count is `4`, and asserts the derived list is exactly + `["Accepted", "Preparing", "Running", "Cancelling"]`. + +All adversarial edits were reverted; the tree was re-verified with `cargo fmt --all -- --check` +and the affected suites after the reverts. + +## Compatibility review + +No wire value, wire field, feature-string byte, stored format, or operator-visible output changed. + +| Fact | How it was proven | +|---|---| +| The `ExecutionState` wire form | The enum's derives are untouched; `the_state_wire_form_is_still_a_bare_pascal_case_string` asserts `TimedOut` encodes as `"TimedOut"` and decodes back, `the_wire_spelling_matches_the_derived_serde_representation` asserts `wire_name()` equals the serde output for every variant, and `the_core_state_enum_keeps_its_derived_wire_representation` asserts the declaration carries no `rename` or `serde(` attribute. | +| The `state` column's stored values | `the_state_column_stores_the_pascal_case_wire_spelling` reserves an execution per state and reads the raw column back, asserting `Running`, `TimedOut`, and `Interrupted` — the same bytes the column held before. | +| The journal's stored format | No `CREATE TABLE` statement and no column definition was touched. The only SQL change is the recovery `UPDATE`, which now binds the interrupted state as a parameter instead of writing the literal `'Interrupted'`; the bound value is `ExecutionState::Interrupted.wire_name()`, so the stored bytes are identical. `recovery_marks_uncertain_work_interrupted_and_never_replays_it` still passes unchanged and asserts the same outcome. | +| The capability feature names | `the_exec_argv_capability_name_is_frozen`, `capability_feature_string_is_frozen_for_workspace_rw_profile`, `cgroup_capability_feature_strings_are_frozen`, and `the_workspace_rw_profile_name_is_frozen` assert the literal byte values. The values were also compared against the pre-M004 source before editing; none moved. | +| The advertised feature list | No entry was added, removed, or reordered. `static_capability_features_are_a_single_canonical_list` and `server_capability_features_do_not_duplicate_static_dynamic_overlap` still pass. The freeze assertions deliberately pin the *values* and *membership*, not the whole advertised list, because Workspace M005a makes `artifact.declared.v1` conditional on the runtime capture fact. | +| The operator-facing state labels | `the_operator_state_labels_are_unchanged` pins all nine snake_case labels. | +| The active-execution query's semantics | `the_active_execution_count_selects_exactly_the_non_terminal_states` asserts the same four names and the same count. The list is assembled at runtime and every state name is bound as a SQL parameter; only the `?` placeholders are assembled into the statement text, never a value. | + +## Security review + +- **Authentication, authorization, lease, generation, fencing, digest, and idempotency semantics are + untouched.** The diff in `crates/eggwork-server/src/lib.rs` is confined to the capability and + classification call sites; no authorization, lease, generation, or digest code path was modified. + The `reserve` generation-reservation path keeps its result — a stale generation is still refused + with `ReserveResult::StaleGeneration`, and a generation may only advance from a terminal state — + because the shared classification answers the same question the inline `matches!` did. +- **No new child-process creation path.** `eggwork-core`, `eggwork-client`, and `eggwork-server` + still create no processes; `scripts/check_execution_ownership.py` passes and reports the same two + approved owners and the same spawn-site counts as before. +- **No new dependency edge.** No `Cargo.toml` was modified. `eggwork-core` still has no internal + dependency, `eggwork-sandbox-helper` still has no workspace-crate dependency in `[dependencies]`, + and `eggwork-client` remains a dev-dependency of `eggwork-server` only. +- **No new injection surface.** The runtime-assembled SQL binds every state name as a parameter. +- **No new panic path.** The new code is const arrays, exhaustive matches, and helper functions with + no `unwrap`/`expect` on untrusted input. + +## Documentation status + +All six §9 documents were updated, and no `docs/` file was touched (this milestone is invisible to +an operator and to a user). + +| Document | What changed | +|---|---| +| `architecture/core-domain.md` | The **States** paragraph no longer says there is no `is_terminal()` helper; it now describes the core-owned classification, the wire spelling, and `ALL_EXECUTION_STATES`, and adds the core-owned schema-version and argv-capability constants. Its line-number citations were replaced with symbol references. | +| `architecture/overview.md` | Divergence #12 only. The count changed from "four places" to the classification being spelled out in one place — `eggwork-core`'s `ExecutionState::is_terminal`/`is_non_terminal` — with the server deriving from it, while the original substance (the store does **not** enforce the state machine; legality lives in `publish`) is preserved. No other row was touched. | +| `architecture/client-transport.md` | The schema-version sentence now names `eggwork_core::API_SCHEMA_VERSION` as the single number the client sends and the server compares against; the `ensure_protocol_compatible` description, the `UnsupportedCapability` error row, and the stale "no test for `ensure_protocol_compatible`" limitation were updated. | +| `architecture/server-node.md` | The capability-advertisement paragraph, the tri-state admission bullets, the capability-refusal paragraph, the invariants table, and the source anchors now name `eggwork_core::EXEC_ARGV_CAPABILITY` and the runner's `CGROUPS_V2_*_CAPABILITY` constants by symbol. | +| `architecture/storage-journal.md` | The schema-version paragraph, the state-machine-persistence section, the enforced-predicates list, the `Preparing` note, the terminal-single-assignment paragraph, the `commit_event` step list, the invariants row, and the known-limitation bullet now describe the core-owned spelling and classification and the derived derivations. | +| `architecture/runner-execution.md` | The profile mapping, the profile resolution, the capability-advertisement description, the helper-argv composition, and the `LANDLOCK_WORKSPACE_RW_CAPABILITY` explanation now name the exported constants and drop the stale line-number citations. | + +Every symbol introduced or edited in these documents is cited by **symbol name**; no new line-number +citation was added. + +## Decisions recorded + +1. **`fn state_label` stays server-local**, in `crates/eggwork-server/src/operations.rs`. It is a + *display* projection, not a protocol fact: the wire spelling is + `eggwork_core::ExecutionState::wire_name` and the terminal classification is + `ExecutionState::is_terminal`, while the label's snake_case is an operator-facing convention that + the protocol-neutral core should not carry. The map stays total over the enum with no wildcard + arm (it already was) and its output is unchanged — `the_operator_state_labels_are_unchanged` + pins all nine labels. It is deliberately **not** derived from `wire_name()`, because a generic + PascalCase→snake_case conversion would be a new mechanism replacing a pinned, readable map, and + the plan's §4 explicitly excludes consolidating the server's enum-to-string maps. +2. **The artifact-capture eligibility predicate stayed server-local**, as + `crates/eggwork-server/src/lib.rs::artifact_capture_eligible`. It is a *policy* subset + (`Succeeded | Failed`), not a protocol classification, and it is deliberately **not** the terminal + set: `Cancelled`, `TimedOut`, and `Interrupted` are terminal but not capture-eligible, and + `artifact_capture_eligibility_is_exactly_succeeded_and_failed` asserts the subset is a strict + subset of the terminal set. + +## Unresolved findings by severity + +No high or medium findings. + +| Severity | Finding | Owner | +|---|---|---| +| Low | The `state_label` map is still a second, hand-maintained naming scheme (snake_case) beside the core-owned PascalCase `wire_name`. It is pinned by a test, but a state added to the enum requires a new label here as well as a new arm in the core matches. | Control-plane roadmap owner (future milestone), if the display projection is ever unified. | +| Low | The store resolves a stored `state` string back to its enum value by scanning `ALL_EXECUTION_STATES` rather than by a name→state lookup. This keeps the core's public surface to the names the plan fixed, at the cost of a nine-element scan on a non-hot path. | Control-plane roadmap owner, if the journal ever becomes hot enough for it to matter. | +| Low | The source-shape checks in `crates/eggwork-server/tests/shared_contract_ownership.rs` are textual. A copy introduced in a way the scan does not model (for example a `const` assembled at runtime) would not be caught by them, though it would be caught by the behavioural freeze assertions. | Control-plane roadmap owner. | + +## Registry and roadmap disposition + +- `plans/subsystems/control-plane-protocol-roadmap.md` — **updated by this milestone**: M004's + entry now reads `Status: closed` and carries the decision-record and closure-record links; the + roadmap's status line reads `Status: active roadmap; M001-M004 closed; no milestone in flight`. +- `plans/registry.md` — **not edited**: the registry is owned by the coordinator. Registration of + this milestone is required and is listed in the handoff report. +- `AGENTS.md` — **not edited**: owned by the coordinator. + +## Deviations + +Anything that landed differently from the plan, with the reason. + +1. **`check_isolation_supported` and `check_resources_supported` now take `&[String]` (the + advertised feature list) instead of `&NodeState`.** The plan requires a test that exercises + `check_resources_supported` directly, including the one-character-drift refusal. Constructing a + `NodeState` in a test is impractical, and the pre-existing test in that area worked around this + by keeping a *copy* of the rule in the test — exactly the duplication this milestone removes. + The functions are private; the behaviour is unchanged. +2. **The client's protocol decision was split into a pure `protocol_compatibility` helper.** + `ensure_protocol_compatible` now fetches the capabilities and delegates. The plan requires a + test for the argv-feature refusal, and the client crate cannot host a stub node without a new + dev-dependency (which §12.2 forbids). The helper is private; no public API changed. +3. **The store's recovery `UPDATE` binds the interrupted state as a parameter** instead of writing + the SQL literal `'Interrupted'`. The plan did not require this, but it makes the "no state name + as a literal in the server" check in criterion 10 crisp, and the stored bytes are unchanged. +4. **`ExecutionStore::recover`'s SQL `IN` list was derived** as well as + `count_active_executions`'s. §5.3 item 19 does not name `recover()`'s list, but §7 says recovery + "uses the shared classification" after the change, and leaving one hard-coded copy of the + non-terminal set in `store.rs` while the other became derived would have preserved exactly the + drift the milestone removes. The four names and the query semantics are unchanged, and + `recovery_marks_uncertain_work_interrupted_and_never_replays_it` passes unchanged. +5. **The runner's probe table was extracted to a module-level `const CGROUP_PROBE_TABLE`.** §6.2 + asks for a test that the "probe-table feature names are exactly the exported constants"; reading + a local table from a test is not possible, so the table became a named constant. +6. **The client's request-body serialization test lives in the client's in-crate test module** + (`crates/eggwork-client/src/lib.rs::shared_contract_tests`), not in a new + `crates/eggwork-client/tests/` file. The four request structs are private to the client crate, + so an integration test could not reach the bodies the transport actually serializes. §6.1 + explicitly allowed either location and required the choice to be recorded — this is that record. +7. **The `ExecutionSpec` and `ExecutionSnapshot` schema-version fixtures were changed to the shared + constant.** §5.1 item 4 requires "any remaining literal schema-version `1` used to stand for this + fact". The server compares `wire.spec.schema_version` against `API_SCHEMA_VERSION`, so the spec's + field is the same fact. Fixtures for *other* versioned documents (the workspace manifest, the + manifest patch, the telemetry payload, the doctor report, the operator config, and the helper's + launch spec) were deliberately left alone: those are separate versioned documents with their own + validation. +8. **Two `architecture/` documents received edits beyond the §9 items**, all of them inside the + documents §9 already lists: `architecture/server-node.md`'s invariants table and source-anchor + list, and `architecture/client-transport.md`'s stale limitation bullet and error table row. They + were stale statements about the code this milestone changed. diff --git a/plans/registry.md b/plans/registry.md index 706fe20..5896a97 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -90,7 +90,7 @@ A repository-wide code interrogation pass over the reviewed baseline found no `t | Addendum | Milestones | Class | Status | |---|---|---|---| -| `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | proposed | +| `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | implemented | | `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a proposed; M005b implemented | | `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a/M005b implemented; **M005c blocked on ADR-0007** | | `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | @@ -109,7 +109,7 @@ Two findings in this batch were deliberately **not** given a milestone, because |---|---|---|---| | Optional Gregg host telemetry | **closed; M001 and M002 both closed** | M001 closed the default-off loopback Gregg adapter, normalized cache and single polling owner (`plans/closure/optional-gregg-host-telemetry/001-status.md`, implementation `ac55985`); M002 closed the authorized node telemetry API/client behind a narrow `telemetry` grant (`plans/closure/optional-gregg-host-telemetry/002-status.md`, implementation `5ccb1e6`). The frozen contract is `eggwork_core::NodeTelemetry` schema version 1. No Gregg changes, no Eggwork scheduling, no capability feature added. The CodeGG worker-telemetry consumer is unblocked. | `plans/subsystems/optional-gregg-host-telemetry-roadmap.md`, `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` | | Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | -| Control-plane protocol | M001-M003 closed; M004 corrective proposed | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | +| Control-plane protocol | M001-M004 closed; no milestone in flight | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept — **implemented**: `eggwork-core` now owns the control-plane schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification, and the runner owns the capability names it produces. No wire value, wire field, or capability byte changed. Closure record: `plans/closure/control-plane-protocol/004-status.md` | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | | Workspace / artifacts | M001-M004 closed; M005a and M005b correctives proposed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | | Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a implemented, M005b proposed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | | Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready; M008a/M008b proposed | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. A repository interrogation pass added M008a (five live metrics are never reported by the operator surface; one `active_executions` field name carries two meanings; every configuration fault collapses into one unhelpful message) and M008b (the release harness re-derives facts that already have an owner, and the design record's line citations and size figures are stale with no gate) | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md`, `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | @@ -119,7 +119,7 @@ Two findings in this batch were deliberately **not** given a milestone, because M007 is the only dependency-ready Eggwork implementation handoff. The optional Gregg telemetry line is closed and remains dependency history. Closed downstream CodeGG rows remain dependency history. -The repository interrogation corrective batch is registered but is **not** dependency-ready: every milestone in it is `proposed`, and Security M005c is `blocked` on ADR-0007. It may be executed in parallel with M007, and the five correctives are mutually independent of one another. +The repository interrogation corrective batch is registered but is **not** dependency-ready: the milestones in it that remain are `proposed`, and Security M005c is `blocked` on ADR-0007. It may be executed in parallel with M007, and the five correctives are mutually independent of one another. | Workstream | Milestone | Status | Implementation plan | Handoff note | |---|---|---|---|---| @@ -137,6 +137,7 @@ The repository interrogation corrective batch is registered but is **not** depen | Foundation corrective | C001 portable ownership guard + CI enforcement | closed | `plans/closure/foundation-execution-core-ci-corrective/001-status.md` | | Control plane | M001 authenticated execution | closed | `plans/closure/control-plane-protocol/001-status.md` | | Control plane | M002 idempotency/leases/events/recovery | closed | `plans/closure/control-plane-protocol/002-status.md` + lease-expiry correction | +| Control plane | M004 shared protocol contract | closed | `plans/closure/control-plane-protocol/004-status.md` — `eggwork-core` now owns the control-plane API schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification of `ExecutionState`; the runner owns the capability names it produces. No wire value, wire field, or capability byte changed. The ownership change is recorded in `plans/adrs/ADR-0008-core-protocol-contract-ownership.md`. | | Workspace | M001 blob store | closed | `plans/closure/workspace-artifact-transport/001-status.md` | | Workspace | M002 materialization | closed | `plans/closure/workspace-artifact-transport/002-status.md` | | Workspace | M003 artifacts/retention/GC | closed | `plans/closure/workspace-artifact-transport/003-status.md` | @@ -218,7 +219,7 @@ Operations release publication [HUMAN ACTION: §14] <----+--> public boot Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 authenticated API/client [CLOSED] --> CodeGG worker telemetry consumer [UNBLOCKED; separately registered] -Repository interrogation corrective batch [PROPOSED] --+--> Control-plane M004 shared protocol contract [PROPOSED] +Repository interrogation corrective batch [PROPOSED] --+--> Control-plane M004 shared protocol contract [IMPLEMENTED] +--> Workspace M005a artifact capture fail-closed [PROPOSED] +--> Workspace M005b GC preview and store ownership [IMPLEMENTED] +--> Security M005a degraded-isolation observability [IMPLEMENTED] diff --git a/plans/subsystems/control-plane-protocol-roadmap.md b/plans/subsystems/control-plane-protocol-roadmap.md index f47eed7..158dbf3 100644 --- a/plans/subsystems/control-plane-protocol-roadmap.md +++ b/plans/subsystems/control-plane-protocol-roadmap.md @@ -1,6 +1,6 @@ # Control-Plane Protocol Roadmap -Status: active roadmap; M001-M003 closed; M004 shared-contract corrective proposed +Status: active roadmap; M001-M004 closed; no milestone in flight Canonical authority: @@ -127,7 +127,7 @@ Exit conditions: Class: invariant -Status: proposed +Status: closed Corrective addendum: @@ -137,6 +137,14 @@ Implementation plan: - `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md` +Decision record: + +- `plans/adrs/ADR-0008-core-protocol-contract-ownership.md` + +Closure record: + +- `plans/closure/control-plane-protocol/004-status.md` + Objective: Give each protocol contract fact a single owner so that a change to it is a compile-time or test-detectable event rather than a convention. The batch covers the API schema version, which is currently declared independently by the client that sends it and the server that hard-rejects on it; the capability feature-name strings, which are re-typed across the runner, the server, and the client; and the terminal-state classification, which is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. From be548313218261074f631ba99d6d9973dc5ad925 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 16:50:55 +0000 Subject: [PATCH 07/37] docs(plans): fill the implementation commit SHAs in the closure records Security M005a -> 6f41957. Security M005b and Workspace M005b -> 63699df. Control-plane M004 -> 1da739b. --- plans/closure/control-plane-protocol/004-status.md | 2 +- plans/closure/security-isolation-resource/005a-status.md | 6 +++--- plans/closure/security-isolation-resource/005b-status.md | 6 +++--- plans/closure/workspace-artifact-transport/005b-status.md | 4 ++-- plans/subsystems/security-isolation-resource-roadmap.md | 4 ++-- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/plans/closure/control-plane-protocol/004-status.md b/plans/closure/control-plane-protocol/004-status.md index ce05bcc..18a9702 100644 --- a/plans/closure/control-plane-protocol/004-status.md +++ b/plans/closure/control-plane-protocol/004-status.md @@ -13,7 +13,7 @@ Roadmap: `plans/subsystems/control-plane-protocol-roadmap.md` ## Reviewed baseline and implementation - Reviewed parent head: `63699df` (branch `corrective/interrogation-batch-2026-10`). -- Implementation commit: `IMPLEMENTATION-COMMIT-PENDING`. +- Implementation commit: `1da739b`. - Crates changed: `eggwork-core`, `eggwork-client`, `eggwork-runner`, `eggwork-server`. The sandbox helper's **production** code is unchanged; only its test file changed. - `eggwork-core` (`crates/eggwork-core/src/lib.rs`) — new public surface: diff --git a/plans/closure/security-isolation-resource/005a-status.md b/plans/closure/security-isolation-resource/005a-status.md index 1036901..5d32b65 100644 --- a/plans/closure/security-isolation-resource/005a-status.md +++ b/plans/closure/security-isolation-resource/005a-status.md @@ -14,7 +14,7 @@ Source roadmap: "implemented") Reviewed repository head before implementation: `778d83c` -Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` +Implementation commit: `6f41957` Branch: `corrective/interrogation-batch-2026-10`. The working tree was left dirty for the coordinator to review and commit; no commit was made by the @@ -448,8 +448,8 @@ separate, still-open item that this milestone neither closes nor worsens. - `plans/registry.md`: **not edited** — the registry is the coordinator's file. The coordinator's action is to register M005a as implemented (closure record `plans/closure/security-isolation-resource/005a-status.md`) and to - fill `IMPLEMENTATION-COMMIT-PENDING` in this record and in the roadmap - entry with the real commit SHA. + fill the real commit SHA in this record and in the roadmap entry. **Done:** + the implementation commit is `6f41957`. - `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`: **not edited** — the plan is not in this milestone's ownership and is left as the authoritative statement of what was asked. diff --git a/plans/closure/security-isolation-resource/005b-status.md b/plans/closure/security-isolation-resource/005b-status.md index 530d925..637a4bd 100644 --- a/plans/closure/security-isolation-resource/005b-status.md +++ b/plans/closure/security-isolation-resource/005b-status.md @@ -14,7 +14,7 @@ Source roadmap: "implemented") Reviewed repository head before implementation: `6f41957` -Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` +Implementation commit: `63699df` Branch: `corrective/interrogation-batch-2026-10`. The working tree was left dirty for the coordinator to review and commit; no commit was made by the @@ -552,8 +552,8 @@ invariant is not weakened by this milestone either way. registry is the coordinator's file and was not edited. The coordinator's action is to point M005b at `plans/closure/security-isolation-resource/005b-status.md`, mark it -implemented, and fill `IMPLEMENTATION-COMMIT-PENDING` in this record and in -the roadmap entry with the real commit SHA. +implemented, and fill the real commit SHA in this record and in +the roadmap entry. **Done:** the implementation commit is `63699df`. ## 15. Registry and roadmap disposition diff --git a/plans/closure/workspace-artifact-transport/005b-status.md b/plans/closure/workspace-artifact-transport/005b-status.md index 8820a9a..76bfbfe 100644 --- a/plans/closure/workspace-artifact-transport/005b-status.md +++ b/plans/closure/workspace-artifact-transport/005b-status.md @@ -5,8 +5,8 @@ Corrective addendum: `plans/subsystems/workspace-artifact-transport-data-plane-c Subsystem roadmap: `plans/subsystems/workspace-artifact-transport-roadmap.md` Reviewed head at the start of the milestone: `6f41957` (`feat(security): M005a degraded isolation observability`) Head when the milestone work was finished: `a8abfcb` (`docs(plans): record the core protocol-contract ownership change as ADR-0008`) — a coordinator-owned documentation commit that does not touch any file in this milestone's change set. -Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` -Closure record commit: `IMPLEMENTATION-COMMIT-PENDING` +Implementation commit: `63699df` +Closure record commit: `63699df` ## Finding diff --git a/plans/subsystems/security-isolation-resource-roadmap.md b/plans/subsystems/security-isolation-resource-roadmap.md index 22fba14..920b257 100644 --- a/plans/subsystems/security-isolation-resource-roadmap.md +++ b/plans/subsystems/security-isolation-resource-roadmap.md @@ -157,7 +157,7 @@ Class: invariant Status: implemented — closure record written, implementation commit pending Closure evidence: `plans/closure/security-isolation-resource/005a-status.md` -(implementation `IMPLEMENTATION-COMMIT-PENDING`) +(implementation `6f41957`) Corrective addendum: @@ -185,7 +185,7 @@ Class: invariant Status: implemented — closure record written, implementation commit pending Closure evidence: `plans/closure/security-isolation-resource/005b-status.md` -(implementation `IMPLEMENTATION-COMMIT-PENDING`) +(implementation `63699df`) Corrective addendum: From 425896436fa54847e05611232878c5067d7b405f Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 17:22:36 +0000 Subject: [PATCH 08/37] feat(data-plane): M005a declared-artifact capture fail-closed On a platform that cannot open a file beneath the workspace root safely, the server refused the capture but left the execution in state Succeeded: a caller that declared outputs saw a successful execution with zero artifacts and no error, and the node advertised artifact.declared.v1 on every platform. The terminal result now carries a first-class capture disposition (ExecutionResult::artifact_capture, serde-defaulted to Unknown so an older snapshot stays silent rather than claiming NotRequested). The mapping from a capture attempt to the terminal facts is one public decision (eggwork_server::decide_artifact_capture); the platform's capture capability is one fact (artifact::capture_capability); the artifact.declared.v1 advertisement follows that fact; and the capture failure is published on the server's existing event-publishing path as a diagnostic of class artifact.capture.failed, before the terminal state event. The platform limitation itself remains and is now stated: declared artifacts are captured on a Unix platform only. The Windows claim is closed by a portable server integration target that the windows-runner CI job now runs, and by a hosted qualification step against the installed daemon. The capture eligibility rule, the capture path, the double hash, and every wire value are unchanged. --- .github/workflows/ci.yml | 30 +- .../workflows/operational-qualification.yml | 22 + AGENTS.md | 1 + README.md | 8 + architecture/ci-guardrails.md | 4 + architecture/data-plane.md | 80 ++- architecture/overview.md | 10 + architecture/protocol.md | 19 +- crates/eggwork-core/src/lib.rs | 151 +++++- crates/eggwork-runner/src/lib.rs | 4 + crates/eggwork-server/src/artifact.rs | 37 ++ crates/eggwork-server/src/lib.rs | 492 ++++++++++++++++-- crates/eggwork-server/src/store.rs | 6 + .../tests/artifact_capture_disposition.rs | 207 ++++++++ .../tests/installed_qualification.rs | 210 +++++++- docs/operations.md | 16 + .../005a-status.md | 455 ++++++++++++++++ plans/registry.md | 10 +- .../workspace-artifact-transport-roadmap.md | 18 +- 19 files changed, 1724 insertions(+), 56 deletions(-) create mode 100644 crates/eggwork-server/tests/artifact_capture_disposition.rs create mode 100644 plans/closure/workspace-artifact-transport/005a-status.md diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 247350d..cf95697 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,9 +35,12 @@ jobs: # M004, so a green Linux run must never be read as Windows coverage. # # Scope is deliberately narrow. `eggwork-runner` runs its full suite on - # Windows; the server's own tests are `/bin/sh`-shaped and stay Linux-only - # until a separate milestone reshapes them. The installed production path - # (installed release bytes, not a build tree) is qualified by the + # Windows; the server's own unit tests are `/bin/sh`-shaped and stay + # Linux-only until a separate milestone reshapes them. One server + # integration target is portable and is run below, so it is the native + # evidence that a node which cannot capture declared outputs refuses them + # instead of dropping them. The installed production path (installed + # release bytes, not a build tree) is qualified by the # `operational-qualification` workflow, not here. runs-on: windows-latest steps: @@ -52,16 +55,25 @@ jobs: # Windows-only regression actually matters, and it is the surface a # release binary is built from. - run: cargo clippy --locked --workspace --lib --bins --all-features -- -D warnings - # Test targets only for the crate this milestone owns. `eggwork-server` - # and `eggwork-client` unit tests are Linux-shaped (they spawn `/bin/sh` - # and set `0700` modes through `std::os::unix`), so they do not compile - # for Windows and are not claimed as coverage. Making them portable is - # its own milestone; until then this job's scope is stated, not widened - # to hide the gap. + # Test targets only for the crates this job can honestly claim. + # `eggwork-server` and `eggwork-client` *unit* tests are Linux-shaped + # (they spawn `/bin/sh` and set `0700` modes through `std::os::unix`), + # so they do not compile for Windows and are not claimed as coverage. + # Making them portable is its own milestone; until then this job's scope + # is stated, not widened to hide the gap. - name: eggwork-runner test targets run: cargo clippy --locked -p eggwork-runner --all-targets --all-features -- -D warnings - name: Windows process-tree lifecycle suite run: cargo test --locked -p eggwork-runner --all-targets -- --nocapture + # One portable server integration target, and only that target. The + # declared-artifact capture disposition is a contract about the + # *decision* rather than about the host, so it is checked from a target + # that compiles for Windows: this is the native evidence that a node + # which cannot capture declared outputs refuses them and ends the + # execution in a state that is not a success. The rest of the server's + # test surface is still Linux-only and is not claimed here. + - name: declared-artifact capture disposition suite + run: cargo test --locked -p eggwork-server --test artifact_capture_disposition release-drift: # Eggpack is producer authority for the release matrix: the generated # release workflow must be exactly what the pinned tool renders from the diff --git a/.github/workflows/operational-qualification.yml b/.github/workflows/operational-qualification.yml index 15d5553..f140f23 100644 --- a/.github/workflows/operational-qualification.yml +++ b/.github/workflows/operational-qualification.yml @@ -284,6 +284,28 @@ jobs: --test installed_qualification -- --ignored \ --exact installed_release_admits_execution_and_refuses_unsupported_isolation \ --nocapture + - name: Qualify the truthful declared-artifact disposition + # Windows cannot capture declared outputs, and the qualified claim is + # the *refusal*: the node must not advertise `artifact.declared.v1`, and + # an execution that declares outputs must end in a failed state with a + # `failed` capture disposition and a diagnostic event — never a + # successful execution whose declared outputs were silently dropped. + # Without this step the hosted qualification would never invoke the + # suite, because the workflow selects suites by `--exact` name. + shell: bash + env: + RELEASE_QUALIFICATION_TOKEN: ${{ secrets.RELEASE_QUALIFICATION_TOKEN }} + EGGWORK_QUALIFY_DAEMON: ${{ runner.temp }}/qualification/bin/eggworkd.exe + EGGWORK_QUALIFY_CONFIG: ${{ runner.temp }}/qualification/state/node.json + EGGWORK_QUALIFY_TLS_DIR: ${{ runner.temp }}/qualification/state/tls + EGGWORK_QUALIFY_RECEIPT: ${{ runner.temp }}/receipts/execution-windows.json + EGGWORK_QUALIFY_PLATFORM: windows + run: | + set -euo pipefail + cargo test --locked -p eggwork-server --features qualification \ + --test installed_qualification -- --ignored \ + --exact installed_release_reports_a_truthful_declared_artifact_disposition \ + --nocapture - name: Record the service management disposition shell: pwsh run: | diff --git a/AGENTS.md b/AGENTS.md index fba96c3..fef34eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,6 +102,7 @@ and deliberate. Deep dives: 8. **Never set `RUSTFLAGS`/`CARGO_*RUSTFLAGS`** — the env would silently replace the target-scoped Windows link policy in `.cargo/config.toml` (`/BREPRO`, `/DEBUG:NONE`) that makes MSVC release binaries reproducible. 9. **Windows service management fails closed.** `deployment::windows_scm_manager` is retained but refuses before any mutation; daemon has no SCM dispatcher. 10. **Protocol contract facts have one owner.** The control-plane API schema version and the `exec.argv.v1` capability name are declared once, publicly, in `eggwork-core`; the runner owns the capability names it produces (`LANDLOCK_WORKSPACE_RW_CAPABILITY`, `CGROUPS_V2_{MEMORY,CPU,PIDS}_CAPABILITY`, `WORKSPACE_RW_PROFILE`); the terminal/non-terminal classification of `ExecutionState` is owned by `eggwork-core`'s `ExecutionState::is_terminal` / `is_non_terminal`. A second copy of any of these in an endpoint crate is a defect, not a convenience. See [ADR-0008](plans/adrs/ADR-0008-core-protocol-contract-ownership.md). +11. **A capability is advertised only where the node can honour it, and a failed claim fails the execution, not the report.** `artifact.declared.v1` is advertised only when the platform's capture-capability fact (`artifact::capture_capability`) says the capture can complete; an execution whose declared outputs were not captured ends in a truthful non-success state with a first-class disposition (`ExecutionResult::artifact_capture`), never `Succeeded` with the outputs silently dropped. The mapping from a capture attempt to the terminal facts is one decision (`eggwork_server::decide_artifact_capture`). ## Code style diff --git a/README.md b/README.md index 1fe1a36..4e1e133 100644 --- a/README.md +++ b/README.md @@ -128,6 +128,14 @@ filesystem or resource isolation: a `Required` isolation or resource request is refused before the target starts, and a best-effort request is reported as `NotApplied` rather than enforced. +**Windows refuses declared artifacts; it does not capture them.** A Windows +node cannot open a file beneath the workspace root without traversing a +symlink, so it refuses a declared output instead of capturing it. The node does +not advertise the `artifact.declared.v1` capability, and an execution that +declares outputs ends in a failed state with a `failed` capture disposition and +a diagnostic event — never a successful execution whose declared outputs were +silently dropped. + **Windows service management is unsupported and fails closed** — `eggworkd` has no service-control dispatcher, so a registered service can never reach `Running`. Every mutating `service` verb is refused before any mutation; Windows diff --git a/architecture/ci-guardrails.md b/architecture/ci-guardrails.md index 4471e8c..c787c88 100644 --- a/architecture/ci-guardrails.md +++ b/architecture/ci-guardrails.md @@ -212,12 +212,16 @@ A second job in the same workflow, on `windows-latest`, added by Foundation M004 run: cargo clippy --locked -p eggwork-runner --all-targets --all-features -- -D warnings - name: Windows process-tree lifecycle suite run: cargo test --locked -p eggwork-runner --all-targets -- --nocapture + - name: declared-artifact capture disposition suite + run: cargo test --locked -p eggwork-server --test artifact_capture_disposition ``` **Why it exists.** The Windows process-tree backend cannot be observed from Linux. Job Object ownership, descendant convergence after leader exit, and pipe inheritance across a process tree only mean something on a real Windows kernel, and a green Linux run must never be readable as Windows coverage. Foundation M004's `runner` tests are `#![cfg(windows)]`, so without this job the entire suite would silently not exist in CI. **What it deliberately does not run.** `cargo test --workspace` is not used, and test-target clippy is scoped to `eggwork-runner`. The server's and client's unit tests are Linux-shaped: they spawn `/bin/sh` and set `0700`/`0600` modes through `std::os::unix::fs`, so several test helpers do not even *compile* for Windows (`place_trusted_helper` in `crates/eggwork-server/src/lib.rs`, the `PermissionsExt` uses in `artifact.rs`, `blob.rs`, `operations.rs`, and `deployment.rs`). Making them portable is its own milestone. +One server integration target **is** portable and **is** run: the declared-artifact capture disposition, `cargo test --locked -p eggwork-server --test artifact_capture_disposition`. It is a contract about the *decision* rather than about the host, so it compiles for Windows without a Linux-shaped harness, and it is the native evidence that a node which cannot capture declared outputs refuses them and ends the execution in a state that is not a success. The rest of the server's test surface is still Linux-only and is not claimed here. + That gap is stated rather than papered over, and the split is deliberate: - `cargo clippy --locked --workspace --lib --bins --all-features -- -D warnings` diff --git a/architecture/data-plane.md b/architecture/data-plane.md index 8280353..65d3f0e 100644 --- a/architecture/data-plane.md +++ b/architecture/data-plane.md @@ -608,6 +608,78 @@ so `insert_many` is not silently idempotent. The execution journal carries only `ArtifactType` has exactly one variant, `File` (`core:970-974`). Directories are not artifacts; they exist only as entries in the capture preflight manifest so the tree validates. +### The capture-failure contract and the platform claim + +A capture can fail for two different reasons, and the node must not conflate them +with a capture that found nothing. + +**The platform claim.** `artifact::capture_capability` is the single owner of the +fact "can this platform capture declared outputs safely?". It is stated next to +`open_file_beneath`, which is the only place that can refuse a capture, so the +platform that cannot open a file beneath the workspace root safely is the +platform that reports itself unable to capture. The fact is re-exported from the +`eggwork-server` crate root as `artifact_capture_capability`, because a caller +must ask the *node's* platform rather than infer the answer from its own `cfg`. + +**The capability follows the fact.** The `artifact.declared.v1` capability name is +a wire value and does not change; whether a node advertises it does. The server's +`server_capability_features` adds it only when the capture capability is +`Available`, so a node that cannot capture declared outputs never claims that it +can. The advertisement is what a caller uses to decide whether to declare outputs +at all, which is why it has to be true. + +**The disposition is first-class.** `ExecutionResult.artifact_capture` +(`eggwork_core::ArtifactCaptureDisposition`) is the terminal answer to "did the +declared outputs arrive?". It has four states: + +| State | Meaning | +| --- | --- | +| `NotRequested` | The execution declared no outputs. Nothing was asked for, so nothing was lost. | +| `Completed` | The capture completed and the declared outputs were published as artifacts. | +| `Failed` | The execution declared outputs and the capture did not complete, so the declared outputs are not all available. | +| `Unknown` | The node reported no disposition. A snapshot written before the field existed decodes this way, and so does a crash-recovered execution, whose declared outputs the recovery path cannot know. | + +The field is `#[serde(default)]`, so it is additive in both directions: a peer +that predates it ignores it (the struct does not deny unknown fields), and a peer +that has it decodes an older snapshot as `Unknown` rather than refusing it. The +default is `Unknown` and not `NotRequested` on purpose: an absent field is an +absence, and reading it as "the caller asked for nothing" would be a claim the +snapshot cannot support. + +**A capture that did not complete is never a success.** The mapping from a +capture attempt to the terminal facts lives in exactly one place, +`eggwork_server::decide_artifact_capture`, and it is a public function so that +the contract can be checked from outside the crate on a platform where the +capture cannot run at all: + +- an execution that declared no outputs reports `NotRequested` and keeps the + target's own terminal facts; +- a capture that completed reports `Completed` and keeps the target's own + terminal facts; +- a declared output that was not captured reports `Failed`, and a target that + had succeeded becomes `ExecutionState::Failed` with the node's own + `ExecutionFailure::Internal`. The target's failure is never overwritten, so a + caller can still tell "the target failed" from "the target succeeded and its + declared outputs could not be collected"; +- a platform whose capture capability is `Unavailable` fails every declared + output, so the capability decides the disposition before the attempt does. + +**The failure is visible in the event stream too.** The server publishes one +diagnostic of class `artifact.capture.failed` on the same event-publishing path +every other diagnostic uses, with `outcome=platform_unavailable` when the +platform refused the capture and `outcome=capture_failed` when an attempted +capture did not complete. The grammar, the bound, and the truncation rule are +in [protocol.md](protocol.md). `ExecutionResult.finalization_failure` stays as a +secondary marker; it is not the only signal, and it can still be overwritten by +the retention marker, which is why the disposition is the first-class one. + +**The eligibility rule is unchanged.** A cancelled, timed-out, interrupted, or +output-limit-killed execution still captures nothing, and +`artifact_capture_eligible` still accepts exactly `Succeeded` and `Failed`. Such +an execution reports `Failed` as its disposition, because it did declare outputs +and they were not captured, and it keeps its own terminal state — which is not +`Succeeded`, so no caller is told a success it did not get. + ### Retention `DEFAULT_RETENTION_MILLIS = 30 * 24 * 60 * 60 * 1000` = 30 days (`artifact.rs:22`). The store owns @@ -838,6 +910,9 @@ How a caller distinguishes the three cases: | Capture stays within `MAX_ARTIFACT_FILES` / `_TOTAL_BYTES` | `artifact.rs:539-541`, `artifact.rs:451-453`, `artifact.rs:352-355` | `artifact.rs:577`; `disappearing_output_and_storage_quota_fail_without_publishing_records` (`artifact.rs:753`) | | Expired artifacts are invisible, then deleted | `artifact.rs:132`, `artifact.rs:168`, `artifact.rs:186-223` | `artifact.rs:804`; `lib.rs:3399` | | Capture is all-or-nothing w.r.t. records | retain before insert (`artifact.rs:311-322`) | `artifact.rs:753` | +| A declared output that was not captured is never a success | `decide_artifact_capture` (server crate root) | `a_declared_output_that_was_not_captured_never_reports_success` (`tests/artifact_capture_disposition.rs`); `a_declared_output_that_was_not_captured_never_reports_success` (server unit test) | +| The declared-artifact capability follows the platform's capture fact | `server_capability_features`; `artifact::capture_capability` | `the_declared_artifact_capability_is_advertised_only_when_the_platform_can_capture` (server unit test) | +| The capture disposition is on the terminal result, not inferred | `ExecutionResult.artifact_capture` (`eggwork_core`) | `a_snapshot_without_the_capture_disposition_decodes_as_unknown` (core unit test) | | Retention cannot stay pinned after a crash | `workspace.rs:667-696`, `workspace.rs:518-533` | `workspace.rs:1430`; `workspace.rs:1497` | | The GC preview and the GC apply select the same candidates | `UNREFERENCED_CANDIDATES_SQL` / `WORKSPACE_CANDIDATES_SQL` / `MANIFEST_CANDIDATES_SQL` / `ARTIFACT_CANDIDATES_SQL` in the owner modules; the operator holds no candidate predicate | `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` (`operations.rs`); `gc_preview_candidates_are_a_subset_of_what_the_apply_pass_removes`; `gc_preview_and_apply_agree_when_the_store_has_no_expired_references`; `the_operator_module_contains_no_candidate_predicate_of_its_own` (`tests/gc_preview_parity.rs`) | | A candidate is selected on the reference rows, not on the counter | `UNREFERENCED_CANDIDATES_SQL` (`NOT EXISTS (SELECT 1 FROM blob_references ...)`) | `gc_preview_uses_the_stores_own_blob_predicate_not_the_reference_count_counter` (`operations.rs`) | @@ -943,7 +1018,10 @@ runner's confinement to the materialized root. - No test drives a manifest that `RelativePath` accepts but the strict portable validator rejects (a Windows-reserved name, a trailing dot, a non-ASCII byte) through the `workspace_create` handler. - No test exercises the non-unix branches: `open_file_beneath` returning `ErrorKind::Unsupported`, - the `#[cfg(not(unix))]` permission helpers, or the `sync_directory` no-op. + the `#[cfg(not(unix))]` permission helpers, or the `sync_directory` no-op. The *decision* that a + platform which cannot capture must refuse a declared output is now covered portably + (`tests/artifact_capture_disposition.rs`), but the non-unix capture code itself is still + unexecuted, and the Windows job's coverage of it is the `windows-runner` CI step, not this host. - No test drives `reconcile_manifests`' orphan-reference sweep past the first page *except* `manifest_orphan_sweep_reaches_owners_past_the_first_page`, which pins the resume cursor and the wrap-back-at-end behaviour. Unbounded `retained_manifests` growth and a hardlink-based quota diff --git a/architecture/overview.md b/architecture/overview.md index 3046074..a268c66 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -201,6 +201,16 @@ None of these are presented as bugs already judged to be bugs. They are the plac | 20 | `decode_json` calls `response.bytes()` with **no size cap**. The node bounds its own request bodies, but the client bounds only the NDJSON line buffer, leaving the JSON paths open to memory exhaustion from a hostile node. | [client-transport.md](client-transport.md) | | 21 | Redirect and retry safety is an **accident of the dependency profile**: the workspace's `standard-http1` omits eggfetch's `redirects` and `logical-retry` features, so 3xx is returned unfollowed. Bumping to the `http1` alias would silently enable both and no test would fail. | [client-transport.md](client-transport.md) | +### Platform limitations + +This table carries the rows that are about *a platform*, not about a module. It +is separate so the numbering stays monotonic: rows 1-21 are cited elsewhere by +number, and a row inserted into an earlier table would renumber them. + +| # | Observation | Where | +|---|---|---| +| 22 | **Declared artifacts are refused, not captured, on a platform that cannot open a file beneath the workspace root safely.** `open_file_beneath` is a descriptor-relative `NOFOLLOW` chain with no non-Unix implementation, so a non-Unix node cannot capture declared outputs. ~~Before the M005a corrective, the finalization set the finalization-failure marker and left the terminal state `Succeeded`, so a caller that declared outputs saw a successful execution with zero artifacts and no error — the declared outputs were silently dropped — and the node advertised `artifact.declared.v1` on every platform.~~ **Closed by the M005a corrective.** The platform's capture-capability fact now reports the limitation, a node that cannot capture does not advertise `artifact.declared.v1`, and an execution that declares outputs there ends in `Failed` with a `Failed` capture disposition and a diagnostic event. The limitation itself remains: the product's top-level claim of *terminal state plus declared artifacts* holds on a Unix platform only. | [data-plane.md](data-plane.md) · [protocol.md](protocol.md) | + ### Positive notes worth keeping - Authorization strictly **precedes** resource resolution in `dispatch`, and id parsing touches only the path, so a denied caller cannot distinguish an existing resource from an absent one. diff --git a/architecture/protocol.md b/architecture/protocol.md index 8c782fc..c71a512 100644 --- a/architecture/protocol.md +++ b/architecture/protocol.md @@ -109,9 +109,10 @@ eggwork.diagnostic..v1 key=value key=value … * The prefix is `eggwork_core::DIAGNOSTIC_PREFIX` (`eggwork.diagnostic.`) and the schema suffix is `eggwork_core::DIAGNOSTIC_SCHEMA_SUFFIX` (`.v1`). * The class is one of the closed set in `eggwork_core::DIAGNOSTIC_CLASSES`: - `isolation.degraded` (`DIAGNOSTIC_CLASS_ISOLATION_DEGRADED`) and - `resources.degraded` (`DIAGNOSTIC_CLASS_RESOURCES_DEGRADED`). A class - outside the set is refused, not guessed at, because the class is what a + `isolation.degraded` (`DIAGNOSTIC_CLASS_ISOLATION_DEGRADED`), + `resources.degraded` (`DIAGNOSTIC_CLASS_RESOURCES_DEGRADED`), and + `artifact.capture.failed` (`DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED`). A + class outside the set is refused, not guessed at, because the class is what a consumer dispatches on. * Fields are `key=value` pairs separated by single spaces. The key set is a lowercase ASCII token of at most `MAX_DIAGNOSTIC_KEY_BYTES` bytes; `class` is @@ -125,10 +126,11 @@ eggwork.diagnostic..v1 key=value key=value … | Key | Meaning | | --- | --- | | `class` | The class, repeated as a field so a consumer that only reads the key/value pairs does not have to parse the prefix. | -| `requirement` | Always `best_effort`. A degradation is by definition a best-effort request that was not honoured; a required request is refused instead. | -| `reason` | The bounded, human-readable cause of the degradation. | +| `requirement` | What the caller asked for. `best_effort` for the two degradation classes — a degradation is by definition a best-effort request that was not honoured, and a required request is refused instead. `declared` for `artifact.capture.failed`: the caller declared outputs and the node owns delivering them, so the failure is not a degradation of a best-effort request. | +| `reason` | The bounded, human-readable cause of the degradation or the capture failure. | | `profile` | `isolation.degraded` only: the requested filesystem profile. | | `dimension` | `resources.degraded` only: the affected dimension (`memory`, `cpu`, `pids`). | +| `outcome` | `artifact.capture.failed` only: which capture failure this is — `platform_unavailable` (the platform cannot open a file beneath the workspace root safely, so the capture was refused) or `capture_failed` (the capture was attempted and did not complete). | `eggwork_core::DiagnosticPayload::parse` enforces the grammar, the closed class set, the bound, and the presence of `class`, `requirement` and `reason`. @@ -145,6 +147,13 @@ makes truncation observable — a bounded payload never silently reads as a complete statement. The free-form `reason` is inserted last so that it absorbs the overage and the structured keys survive intact. +The diagnostic bound is deliberately the same as one event-metadata value, so a +diagnostic cannot dominate the event it rides in. It is well inside the event +envelope: `MAX_DIAGNOSTIC_PAYLOAD_BYTES` (2048) is less than +`eggwork_core::MAX_EVENT_CHUNK_BYTES` (65536), which is the ceiling +`ExecutionEvent::validate` enforces on a `Diagnostic` payload. The +relationship is a compile-time fact in `eggwork-core`. + ### What the payload deliberately does not carry No secret, no credential, no path outside the execution's own workspace diff --git a/crates/eggwork-core/src/lib.rs b/crates/eggwork-core/src/lib.rs index f18e75f..be6abae 100644 --- a/crates/eggwork-core/src/lib.rs +++ b/crates/eggwork-core/src/lib.rs @@ -58,12 +58,21 @@ pub const DIAGNOSTIC_CLASS_ISOLATION_DEGRADED: &str = "isolation.degraded"; /// enforcement that was not applied. pub const DIAGNOSTIC_CLASS_RESOURCES_DEGRADED: &str = "resources.degraded"; +/// The class of a diagnostic that reports declared outputs the node could not +/// capture. +/// +/// A capture failure is not a degradation of a best-effort request: the caller +/// declared the outputs and the node owns delivering them, so the diagnostic +/// names the failure instead of reporting a `NotApplied` outcome. +pub const DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED: &str = "artifact.capture.failed"; + /// The closed set of diagnostic classes. A payload naming anything else is /// refused rather than guessed at, because a class is what a consumer /// dispatches on. -pub const DIAGNOSTIC_CLASSES: [&str; 2] = [ +pub const DIAGNOSTIC_CLASSES: [&str; 3] = [ DIAGNOSTIC_CLASS_ISOLATION_DEGRADED, DIAGNOSTIC_CLASS_RESOURCES_DEGRADED, + DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED, ]; /// Ceiling on a whole diagnostic payload. @@ -1286,6 +1295,54 @@ pub enum ExecutionFinalizationFailure { ArtifactCapture, Retention, } + +/// The disposition of a declared-artifact capture on a terminal execution. +/// +/// The disposition is the first-class answer to "did the declared outputs +/// arrive?". It exists because a caller cannot answer that question from the +/// artifact count alone: the count says how many artifacts exist, not how many +/// were asked for, so a caller would have to compare the count against a +/// declared-output count it does not have. Worse, a count of zero is +/// indistinguishable from "the outputs were silently dropped", which is the +/// failure this type exists to make impossible to read as success. +/// +/// The states are: +/// +/// * `NotRequested` — the execution declared no outputs. Nothing was asked +/// for, so nothing was lost. +/// * `Completed` — the capture completed and the declared outputs were +/// published as artifacts. +/// * `Failed` — the execution declared outputs and the capture did not +/// complete, so the declared outputs are not all available. The terminal +/// state says why: an execution that ended in a state where capture is not +/// performed keeps that state, and a capture that fails after a successful +/// target moves the terminal state to `Failed`. +/// * `Unknown` — the node reported no disposition. A snapshot written before +/// this field existed decodes this way, so a caller must fall back to the +/// legacy `finalization_failure` marker and the artifact count rather than +/// read an absence as a fact. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ArtifactCaptureDisposition { + NotRequested, + Completed, + Failed, + Unknown, +} + +impl Default for ArtifactCaptureDisposition { + /// The default is `Unknown`, not `NotRequested`. + /// + /// A snapshot written before this field existed says nothing about its + /// capture, and `NotRequested` would be a claim — that the caller asked for + /// nothing — that the snapshot cannot support. `Unknown` keeps the + /// absence an absence, so a caller falls back to the legacy signals + /// instead of believing a fabricated one. + fn default() -> Self { + Self::Unknown + } +} + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ExecutionResult { pub state: ExecutionState, @@ -1300,6 +1357,14 @@ pub struct ExecutionResult { pub finalization_failure: Option, #[serde(default)] pub artifact_count: u32, + /// The disposition of the declared-artifact capture. + /// + /// `#[serde(default)]` keeps the field additive in both directions: a peer + /// that predates it ignores it (the struct does not deny unknown fields), + /// and a peer that has it decodes a snapshot written before it existed as + /// `Unknown` rather than refusing the snapshot. + #[serde(default)] + pub artifact_capture: ArtifactCaptureDisposition, #[serde(default)] pub sandbox: Option, #[serde(default)] @@ -2072,6 +2137,90 @@ mod tests { ); assert!(DiagnosticPayload::new("isolation.degraded.other").is_err()); } + /// The capture-failure class joins the closed set, and a class outside it + /// is still refused. + /// + /// The class is what a consumer dispatches on, so adding one is a + /// deliberate act and the set stays closed. + #[test] + fn the_capture_failure_class_is_in_the_closed_class_set() { + assert!(DIAGNOSTIC_CLASSES.contains(&DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED)); + let mut payload = DiagnosticPayload::new(DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED).unwrap(); + payload.set("requirement", "declared").unwrap(); + payload.set("outcome", "platform_unavailable").unwrap(); + payload + .set( + "reason", + "safe artifact capture is unavailable on this platform", + ) + .unwrap(); + let built = payload.build(); + assert!(built.starts_with("eggwork.diagnostic.artifact.capture.failed.v1 ")); + assert!(built.len() <= MAX_DIAGNOSTIC_PAYLOAD_BYTES); + // The diagnostic rides inside an event, so its bound has to stay + // inside the event envelope. The relationship is a compile-time fact, + // not a runtime check. + const _: () = assert!(MAX_DIAGNOSTIC_PAYLOAD_BYTES <= MAX_EVENT_CHUNK_BYTES); + let parsed = DiagnosticPayload::parse(&built).unwrap(); + assert_eq!(parsed.class(), DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED); + } + /// A terminal snapshot written before the capture disposition existed + /// still decodes, and decodes as "no disposition reported". + /// + /// The field is additive, so a peer that has it must not refuse a + /// snapshot that lacks it. The default is `Unknown` rather than + /// `NotRequested`: an absent field is an absence, and reading it as "the + /// caller asked for nothing" would be a claim the snapshot cannot support. + #[test] + fn a_snapshot_without_the_capture_disposition_decodes_as_unknown() { + let legacy = serde_json::json!({ + "state": "Succeeded", + "exit_code": 0, + "failure": null, + "stdout_bytes": 0, + "stderr_bytes": 0, + "stdout_omitted": 0, + "stderr_omitted": 0, + "cleanup_warning": null, + "finalization_failure": null, + "artifact_count": 0 + }); + let decoded: ExecutionResult = serde_json::from_value(legacy).unwrap(); + assert_eq!( + decoded.artifact_capture, + ArtifactCaptureDisposition::Unknown + ); + assert_eq!( + ArtifactCaptureDisposition::default(), + ArtifactCaptureDisposition::Unknown + ); + } + /// The disposition is carried on the wire and survives a round trip. + #[test] + fn the_capture_disposition_round_trips() { + for disposition in [ + ArtifactCaptureDisposition::NotRequested, + ArtifactCaptureDisposition::Completed, + ArtifactCaptureDisposition::Failed, + ArtifactCaptureDisposition::Unknown, + ] { + let encoded = serde_json::to_string(&disposition).unwrap(); + let decoded: ArtifactCaptureDisposition = serde_json::from_str(&encoded).unwrap(); + assert_eq!(decoded, disposition); + } + assert_eq!( + serde_json::to_string(&ArtifactCaptureDisposition::NotRequested).unwrap(), + "\"not_requested\"" + ); + assert_eq!( + serde_json::to_string(&ArtifactCaptureDisposition::Completed).unwrap(), + "\"completed\"" + ); + assert_eq!( + serde_json::to_string(&ArtifactCaptureDisposition::Failed).unwrap(), + "\"failed\"" + ); + } fn spec() -> ExecutionSpec { ExecutionSpec { schema_version: API_SCHEMA_VERSION, diff --git a/crates/eggwork-runner/src/lib.rs b/crates/eggwork-runner/src/lib.rs index afbbcde..a2f5d9c 100644 --- a/crates/eggwork-runner/src/lib.rs +++ b/crates/eggwork-runner/src/lib.rs @@ -1401,6 +1401,10 @@ impl RunnerResult { .or_else(|| self.cleanup.stdin_error.clone()), finalization_failure: None, artifact_count: 0, + // The runner owns the process, not the capture: the server's + // finalization decides the capture disposition and replaces this + // placeholder. The placeholder claims nothing. + artifact_capture: eggwork_core::ArtifactCaptureDisposition::Unknown, sandbox: Some(match &self.setup.sandbox { SandboxOutcome::NotRequested => eggwork_core::SandboxResult::NotRequested, SandboxOutcome::NotApplied { reason } => eggwork_core::SandboxResult::NotApplied { diff --git a/crates/eggwork-server/src/artifact.rs b/crates/eggwork-server/src/artifact.rs index f134f65..a5c7aa8 100644 --- a/crates/eggwork-server/src/artifact.rs +++ b/crates/eggwork-server/src/artifact.rs @@ -436,6 +436,43 @@ async fn capture_blob( Ok((digest, size, executable)) } +/// Whether the running platform can capture declared outputs safely. +/// +/// The fact is owned by the data plane, because the data plane owns the +/// capture. A caller that wants to know whether a node can capture declared +/// outputs asks the node's platform; it does not infer the answer from its own +/// `cfg`, because the node's platform and the caller's platform are not +/// necessarily the same one. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ArtifactCaptureCapability { + /// Declared outputs can be captured: files can be opened beneath the + /// workspace root without traversing a symlink. + Available, + /// Declared outputs cannot be captured on this platform. The node refuses + /// the capture instead of dropping the declared outputs silently. + Unavailable, +} + +/// The running platform's declared-artifact capture capability. +/// +/// The fact is stated next to the platform-specific `open_file_beneath`, which +/// is the only place that can refuse a capture, so the two cannot drift: the +/// platform that cannot open a file beneath the workspace root safely is the +/// platform that reports itself unable to capture. +#[cfg(unix)] +pub const fn capture_capability() -> ArtifactCaptureCapability { + ArtifactCaptureCapability::Available +} + +/// The running platform's declared-artifact capture capability. +/// +/// See the Unix variant: the fact and the capture implementation are stated +/// together so they cannot disagree. +#[cfg(not(unix))] +pub const fn capture_capability() -> ArtifactCaptureCapability { + ArtifactCaptureCapability::Unavailable +} + #[cfg(unix)] fn open_file_beneath(root: &Path, relative: &str) -> io::Result { use rustix::fs::{Mode, OFlags, open, openat}; diff --git a/crates/eggwork-server/src/lib.rs b/crates/eggwork-server/src/lib.rs index 7b0d7fe..b0ebe2d 100644 --- a/crates/eggwork-server/src/lib.rs +++ b/crates/eggwork-server/src/lib.rs @@ -20,10 +20,12 @@ use eggserve_core::{ tls::{ClientAuthMode, TlsServerConfig}, }; use eggwork_core::{ - API_SCHEMA_VERSION, ApiError, EXEC_ARGV_CAPABILITY, ExecutionEvent, ExecutionEventKind, - ExecutionFailure, ExecutionFinalizationFailure, ExecutionGeneration, ExecutionHandle, - ExecutionId, ExecutionResult, ExecutionSnapshot, ExecutionSpec, ExecutionState, LeaseId, - NodeCapabilities, NodeId, NodeStatus, ProtocolVersion, ProtocolVersionRange, + API_SCHEMA_VERSION, ApiError, ArtifactCaptureDisposition, + DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED, DiagnosticPayload, EXEC_ARGV_CAPABILITY, + ExecutionEvent, ExecutionEventKind, ExecutionFailure, ExecutionFinalizationFailure, + ExecutionGeneration, ExecutionHandle, ExecutionId, ExecutionResult, ExecutionSnapshot, + ExecutionSpec, ExecutionState, LeaseId, NodeCapabilities, NodeId, NodeStatus, ProtocolVersion, + ProtocolVersionRange, }; use eggwork_runner::{ ExecutionProvenance, LocalProcessRunner, OutputChunk, ResourceSetupRequest, RunnerError, @@ -53,6 +55,115 @@ const MAX_RECENT_EXECUTIONS: usize = 1024; const MAX_BLOB_FIND_REQUEST_BYTES: usize = 64 * 1024; const MAX_WORKSPACE_REQUEST_BYTES: usize = 4 * 1024 * 1024; +/// The declared-artifact capture capability of the running platform. +/// +/// The re-export is the crate's public answer to "can this node capture +/// declared outputs?". The data plane owns the fact because it owns the +/// capture, and the fact is re-exported rather than reimplemented here so a +/// caller cannot answer it from its own `cfg` and disagree with the node. +pub use artifact::ArtifactCaptureCapability; + +/// The declared-artifact capture capability of the running platform. +/// +/// See [`ArtifactCaptureCapability`]. +pub use artifact::capture_capability as artifact_capture_capability; + +/// What a declared-artifact capture attempt produced. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ArtifactCaptureAttempt { + /// No capture was attempted: either the execution declared no outputs, or + /// the execution ended in a state where a capture is not performed. + NotAttempted, + /// The capture completed and published its artifacts. + Completed, + /// The capture was attempted and did not complete. + Failed, +} + +/// The facts the terminal disposition of a declared-artifact capture is +/// decided from. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ArtifactCaptureFacts { + /// The running platform's capture capability. + pub capability: ArtifactCaptureCapability, + /// Whether the execution declared any outputs. + pub declared_outputs: bool, + /// The terminal state the target produced. + pub target_state: ExecutionState, + /// The failure the target produced, if any. + pub target_failure: Option, + /// What the capture attempt produced. + pub attempt: ArtifactCaptureAttempt, +} + +/// The terminal facts a declared-artifact capture produces. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ArtifactCaptureDecision { + /// The terminal state the execution reports. + pub state: ExecutionState, + /// The failure the execution reports, if any. + pub failure: Option, + /// The capture disposition the execution reports. + pub disposition: ArtifactCaptureDisposition, +} + +/// The one mapping from a capture attempt to the terminal facts of the +/// execution. +/// +/// The mapping lives here, and not in the finalization's match arms, because +/// it is a contract rather than an implementation detail: a node must not +/// report a successful execution whose declared outputs were dropped, and a +/// contract that is only reachable through a live execution cannot be checked +/// on a platform where the capture is impossible. +/// +/// The rules are: +/// +/// * an execution that declared no outputs reports +/// [`ArtifactCaptureDisposition::NotRequested`] and keeps the target's own +/// terminal facts — nothing was asked for, so nothing was lost; +/// * a capture that completed reports +/// [`ArtifactCaptureDisposition::Completed`] and keeps the target's own +/// terminal facts; +/// * a declared output that was not captured reports +/// [`ArtifactCaptureDisposition::Failed`], and a target that had succeeded +/// becomes [`ExecutionState::Failed`] with the node's own +/// [`ExecutionFailure::Internal`]. The target's failure is never overwritten: +/// a target that failed for its own reason keeps that failure, so a caller +/// can still tell "the target failed" from "the target succeeded and its +/// declared outputs could not be collected"; +/// * a platform that cannot capture safely fails every declared output, so the +/// capability decides the disposition before the attempt does. +pub fn decide_artifact_capture(facts: ArtifactCaptureFacts) -> ArtifactCaptureDecision { + if !facts.declared_outputs { + return ArtifactCaptureDecision { + state: facts.target_state, + failure: facts.target_failure, + disposition: ArtifactCaptureDisposition::NotRequested, + }; + } + let disposition = match (facts.capability, facts.attempt) { + (ArtifactCaptureCapability::Unavailable, _) => ArtifactCaptureDisposition::Failed, + (ArtifactCaptureCapability::Available, ArtifactCaptureAttempt::Completed) => { + ArtifactCaptureDisposition::Completed + } + (ArtifactCaptureCapability::Available, _) => ArtifactCaptureDisposition::Failed, + }; + if disposition == ArtifactCaptureDisposition::Failed + && facts.target_state == ExecutionState::Succeeded + { + return ArtifactCaptureDecision { + state: ExecutionState::Failed, + failure: Some(facts.target_failure.unwrap_or(ExecutionFailure::Internal)), + disposition, + }; + } + ArtifactCaptureDecision { + state: facts.target_state, + failure: facts.target_failure, + disposition, + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Operation { Capabilities, @@ -591,6 +702,14 @@ fn acquire_state_lock(database_path: &std::path::Path) -> Result &'static [&'static str] { "workspace.manifest.v1", "workspace.materialize.v1", "workspace.derive.v1", - "artifact.declared.v1", + ARTIFACT_DECLARED_CAPABILITY, "artifact.stream.v1", "artifact.retention.v1", "network.unrestricted.v1", @@ -616,9 +735,18 @@ fn static_capability_features() -> &'static [&'static str] { /// One capability feature construction. Both `Route::Capabilities` and /// `NodeStatus.capabilities` MUST go through this function so a single node /// always reports the same execution-capability feature set. +/// +/// The declared-artifact capability is conditional on the platform's capture +/// capability: a node that cannot capture declared outputs safely must not +/// advertise that it can. The capability name is a wire value and is +/// unchanged; only its advertisement follows the fact. fn server_capability_features(dynamic: Vec) -> Vec { let mut features: Vec = static_capability_features() .iter() + .filter(|feature| { + **feature != ARTIFACT_DECLARED_CAPABILITY + || artifact_capture_capability() == ArtifactCaptureCapability::Available + }) .map(|feature| (*feature).to_owned()) .collect(); features.extend(dynamic); @@ -2540,35 +2668,79 @@ async fn run_execution( failed_result(terminal, failure, sandbox_request, resource_request) }; if let Some(workspace) = workspace { - let should_capture = runner_completed - && !workspace.outputs.is_empty() + let declared_outputs = !workspace.outputs.is_empty(); + // The capture rule is unchanged: the runner completed, the execution + // declared outputs, the terminal state is eligible, and the target was + // not killed for its output volume. What changed is what an execution + // reports when a capture that was required did not complete. + let eligible = runner_completed + && declared_outputs && artifact_capture_eligible(&execution_result.state) && execution_result.failure != Some(ExecutionFailure::OutputLimit); - if should_capture { - let expiry = artifact::now_unix_ms().saturating_add(artifact::DEFAULT_RETENTION_MILLIS); - let (execution_id, generation) = { - let snapshot = record.snapshot.read().await; - (snapshot.execution_id.clone(), snapshot.generation) - }; - match artifact::capture_declared( - &state.artifacts, - &state.blobs, - &workspace.root, - &workspace.outputs, - &execution_id, - generation, - &workspace.principal, - expiry, - ) - .await - { - Ok(count) => execution_result.artifact_count = count, - Err(_) => { - execution_result.finalization_failure = - Some(ExecutionFinalizationFailure::ArtifactCapture); + let mut attempt = ArtifactCaptureAttempt::NotAttempted; + if eligible { + if artifact_capture_capability() == ArtifactCaptureCapability::Unavailable { + // The platform cannot open a file beneath the workspace root + // safely, so the capture is refused instead of attempted. A + // refused capture must not read like a capture that found + // nothing, so the refusal is reported and the execution ends + // in a state that is not a success. + attempt = ArtifactCaptureAttempt::Failed; + execution_result.finalization_failure = + Some(ExecutionFinalizationFailure::ArtifactCapture); + publish_capture_diagnostic( + &record, + "platform_unavailable", + "safe artifact capture is unavailable on this platform", + ) + .await; + } else { + let expiry = + artifact::now_unix_ms().saturating_add(artifact::DEFAULT_RETENTION_MILLIS); + let (execution_id, generation) = { + let snapshot = record.snapshot.read().await; + (snapshot.execution_id.clone(), snapshot.generation) + }; + match artifact::capture_declared( + &state.artifacts, + &state.blobs, + &workspace.root, + &workspace.outputs, + &execution_id, + generation, + &workspace.principal, + expiry, + ) + .await + { + Ok(count) => { + execution_result.artifact_count = count; + attempt = ArtifactCaptureAttempt::Completed; + } + Err(_) => { + execution_result.finalization_failure = + Some(ExecutionFinalizationFailure::ArtifactCapture); + attempt = ArtifactCaptureAttempt::Failed; + publish_capture_diagnostic( + &record, + "capture_failed", + "a declared output could not be captured", + ) + .await; + } } } } + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability: artifact_capture_capability(), + declared_outputs, + target_state: execution_result.state.clone(), + target_failure: execution_result.failure.clone(), + attempt, + }); + execution_result.state = decision.state; + execution_result.failure = decision.failure; + execution_result.artifact_capture = decision.disposition; let expiry = artifact::now_unix_ms().saturating_add(artifact::DEFAULT_RETENTION_MILLIS); if state .workspaces @@ -2577,6 +2749,10 @@ async fn run_execution( { execution_result.finalization_failure = Some(ExecutionFinalizationFailure::Retention); } + } else { + // No workspace means the execution declared no outputs, so there was + // nothing to capture and nothing that could be lost. + execution_result.artifact_capture = ArtifactCaptureDisposition::NotRequested; } let terminal = execution_result.state.clone(); let terminal_metric = terminal_metric_name(&terminal); @@ -2626,6 +2802,9 @@ fn failed_result( cleanup_warning: None, finalization_failure: None, artifact_count: 0, + // The runner produced no result, so the finalization has not decided + // the capture disposition yet. The placeholder claims nothing. + artifact_capture: ArtifactCaptureDisposition::Unknown, sandbox: Some(match sandbox_request { SandboxRequest::None => eggwork_core::SandboxResult::NotRequested, SandboxRequest::BestEffort { .. } => eggwork_core::SandboxResult::NotApplied { @@ -2655,6 +2834,40 @@ fn failure_for_runner_error( } } +/// Publishes the diagnostic that reports a declared-artifact capture that did +/// not complete. +/// +/// The diagnostic rides the server's existing event-publishing path: a +/// diagnostic is an `ExecutionEventKind::Diagnostic`, and this is the one +/// place the server produces one, so a consumer reads every diagnostic from +/// the same stream and under the same grammar. +/// +/// The payload is bounded by the diagnostic grammar itself +/// (`MAX_DIAGNOSTIC_PAYLOAD_BYTES`), which is well inside the event envelope +/// (`MAX_EVENT_CHUNK_BYTES`), so a diagnostic can never overflow the event it +/// rides in. +async fn publish_capture_diagnostic(record: &ExecutionRecord, outcome: &str, reason: &str) { + let Ok(mut payload) = DiagnosticPayload::new(DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED) else { + return; + }; + // `requirement` and `reason` are the minimum key set the diagnostic + // grammar requires, and `outcome` says which of the two capture failures + // this is. The keys are fixed so a consumer can dispatch on them. + if payload.set("requirement", "declared").is_err() + || payload.set("outcome", outcome).is_err() + || payload.set("reason", reason).is_err() + { + return; + } + publish( + record, + ExecutionState::Running, + None, + ExecutionEventKind::Diagnostic(payload.build()), + ) + .await; +} + async fn publish( record: &ExecutionRecord, state: ExecutionState, @@ -3761,6 +3974,11 @@ mod tests { let result = final_snapshot.result.unwrap(); assert_eq!(result.artifact_count, 1); assert_eq!(result.finalization_failure, None); + assert_eq!( + result.artifact_capture, + ArtifactCaptureDisposition::Completed, + "a capture that produced the declared artifact reports a completed capture" + ); let artifacts = client .artifacts( &workspace_handle.execution_id, @@ -3800,7 +4018,7 @@ mod tests { path: eggwork_core::RelativePath::new("required-missing.txt").unwrap(), required: true, }]; - client + let missing_events = client .execute_in_workspace(&missing_output_spec, &missing_handle, &missing_workspace) .await .unwrap() @@ -3817,9 +4035,50 @@ mod tests { .unwrap() .result .unwrap(); - assert_eq!(failed_finalization.state, ExecutionState::Succeeded); + // The terminal event and the terminal result agree about the failure, + // and the diagnostic that explains it is published before the terminal + // state event, so a consumer reading the stream sees the reason before + // the outcome. + let diagnostic_position = missing_events.iter().position(|event| { + matches!( + &event.kind, + ExecutionEventKind::Diagnostic(payload) + if payload.contains(eggwork_core::DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED) + ) + }); + let terminal_position = missing_events.iter().position(|event| { + matches!(&event.kind, ExecutionEventKind::State(state) if *state == ExecutionState::Failed) + }); + assert!( + diagnostic_position.is_some(), + "a capture failure must be visible in the event stream: {missing_events:?}" + ); + assert!( + terminal_position.is_some(), + "the terminal state event must report the failure: {missing_events:?}" + ); + assert!( + diagnostic_position < terminal_position, + "the capture diagnostic must be published before the terminal state event" + ); + // A declared output that could not be captured is a failed execution, + // not a successful one with nothing in it. The target's own outcome + // is still reported (its exit code stays), and the capture failure is + // reported separately so a caller can tell "the target failed" from + // "the target succeeded and its declared outputs could not be + // collected". + assert_eq!(failed_finalization.state, ExecutionState::Failed); assert_eq!(failed_finalization.exit_code, Some(0)); assert_eq!(failed_finalization.artifact_count, 0); + assert_eq!( + failed_finalization.failure, + Some(ExecutionFailure::Internal), + "the node owns a capture failure, so the failure is the node's own" + ); + assert_eq!( + failed_finalization.artifact_capture, + ArtifactCaptureDisposition::Failed + ); assert_eq!( failed_finalization.finalization_failure, Some(ExecutionFinalizationFailure::ArtifactCapture) @@ -3867,6 +4126,12 @@ mod tests { .unwrap(); assert_eq!(timed_out.state, ExecutionState::TimedOut); assert_eq!(timed_out.artifact_count, 0); + assert_eq!( + timed_out.artifact_capture, + ArtifactCaptureDisposition::Failed, + "the execution declared an output and the capture did not complete, \ + so the declared output is not available" + ); assert!( client .artifacts( @@ -6538,6 +6803,171 @@ mod tests { ); } + /// The declared-artifact capability follows the platform's capture fact. + /// + /// The name is a wire value and never changes; whether the node advertises + /// it does. A node that cannot capture declared outputs must not claim + /// that it can, because the advertisement is what a caller uses to decide + /// whether to declare outputs at all. + #[test] + fn the_declared_artifact_capability_is_advertised_only_when_the_platform_can_capture() { + let features = server_capability_features(Vec::new()); + let advertised = features + .iter() + .filter(|feature| feature.as_str() == ARTIFACT_DECLARED_CAPABILITY) + .count(); + match artifact_capture_capability() { + ArtifactCaptureCapability::Available => assert_eq!( + advertised, 1, + "a platform that can capture must advertise the declared-artifact capability" + ), + ArtifactCaptureCapability::Unavailable => assert_eq!( + advertised, 0, + "a platform that cannot capture must not advertise the \ + declared-artifact capability" + ), + } + } + + /// A declared output that was not captured is never a success. + /// + /// This is the regression the corrective exists for: the terminal state of + /// an execution whose declared outputs could not be collected must not + /// read as a successful execution with nothing in it. + #[test] + fn a_declared_output_that_was_not_captured_never_reports_success() { + for capability in [ + ArtifactCaptureCapability::Available, + ArtifactCaptureCapability::Unavailable, + ] { + for attempt in [ + ArtifactCaptureAttempt::NotAttempted, + ArtifactCaptureAttempt::Failed, + ] { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability, + declared_outputs: true, + target_state: ExecutionState::Succeeded, + target_failure: None, + attempt, + }); + assert_ne!( + decision.state, + ExecutionState::Succeeded, + "a capture that did not complete must not leave the execution successful" + ); + assert_eq!(decision.state, ExecutionState::Failed); + assert_eq!( + decision.failure, + Some(ExecutionFailure::Internal), + "the capture failure is the node's own failure" + ); + assert_eq!(decision.disposition, ArtifactCaptureDisposition::Failed); + } + } + } + + /// A capture that completed leaves the target's own outcome alone. + #[test] + fn a_completed_capture_keeps_the_targets_own_outcome() { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability: ArtifactCaptureCapability::Available, + declared_outputs: true, + target_state: ExecutionState::Succeeded, + target_failure: None, + attempt: ArtifactCaptureAttempt::Completed, + }); + assert_eq!(decision.state, ExecutionState::Succeeded); + assert_eq!(decision.failure, None); + assert_eq!(decision.disposition, ArtifactCaptureDisposition::Completed); + } + + /// A failed target keeps its own failure. + /// + /// A capture failure must not overwrite the target's failure: a caller has + /// to be able to tell "the target failed" from "the target succeeded and + /// its declared outputs could not be collected". + #[test] + fn a_failed_target_keeps_its_own_failure_when_the_capture_also_fails() { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability: ArtifactCaptureCapability::Available, + declared_outputs: true, + target_state: ExecutionState::Failed, + target_failure: Some(ExecutionFailure::Spawn), + attempt: ArtifactCaptureAttempt::Failed, + }); + assert_eq!(decision.state, ExecutionState::Failed); + assert_eq!( + decision.failure, + Some(ExecutionFailure::Spawn), + "the target's own failure must survive a capture failure" + ); + assert_eq!(decision.disposition, ArtifactCaptureDisposition::Failed); + } + + /// An execution that declared nothing reports that nothing was requested. + #[test] + fn an_execution_without_declared_outputs_reports_not_requested() { + for capability in [ + ArtifactCaptureCapability::Available, + ArtifactCaptureCapability::Unavailable, + ] { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability, + declared_outputs: false, + target_state: ExecutionState::Succeeded, + target_failure: None, + attempt: ArtifactCaptureAttempt::NotAttempted, + }); + assert_eq!(decision.state, ExecutionState::Succeeded); + assert_eq!(decision.failure, None); + assert_eq!( + decision.disposition, + ArtifactCaptureDisposition::NotRequested + ); + } + } + + /// The capture diagnostic is a bounded payload in the closed class set. + /// + /// The diagnostic rides inside an event, so it has to satisfy the event + /// envelope as well as the diagnostic grammar, and a consumer has to be + /// able to parse it back. + #[test] + fn the_capture_diagnostic_is_a_bounded_payload_in_the_closed_class_set() { + let mut payload = eggwork_core::DiagnosticPayload::new( + eggwork_core::DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED, + ) + .expect("the capture failure class is in the closed class set"); + payload + .set("requirement", "declared") + .expect("requirement is a valid diagnostic key"); + payload + .set("outcome", "platform_unavailable") + .expect("outcome is a valid diagnostic key"); + payload + .set( + "reason", + "safe artifact capture is unavailable on this platform", + ) + .expect("reason is a valid diagnostic key"); + let built = payload.build(); + assert!( + built.len() <= eggwork_core::MAX_DIAGNOSTIC_PAYLOAD_BYTES, + "the diagnostic payload must stay inside its bound" + ); + assert!( + built.len() <= eggwork_core::MAX_EVENT_CHUNK_BYTES, + "the diagnostic payload must stay inside the event envelope" + ); + let parsed = eggwork_core::DiagnosticPayload::parse(&built) + .expect("the built diagnostic must parse back"); + assert_eq!( + parsed.class(), + eggwork_core::DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED + ); + } + #[test] fn admission_helpers_keep_required_capability_gating_active() { // This test does not exercise live sockets; it pins the admission diff --git a/crates/eggwork-server/src/store.rs b/crates/eggwork-server/src/store.rs index 59e63cf..7a6e037 100644 --- a/crates/eggwork-server/src/store.rs +++ b/crates/eggwork-server/src/store.rs @@ -591,6 +591,12 @@ impl ExecutionStore { cleanup_warning: None, finalization_failure: None, artifact_count: 0, + // The recovery path does not know what the interrupted + // execution declared, so it reports no capture + // disposition rather than a fabricated one. The + // execution's terminal state is `Interrupted`, so the + // snapshot never reads as a success. + artifact_capture: eggwork_core::ArtifactCaptureDisposition::Unknown, sandbox: None, resources: None, }); diff --git a/crates/eggwork-server/tests/artifact_capture_disposition.rs b/crates/eggwork-server/tests/artifact_capture_disposition.rs new file mode 100644 index 0000000..6e2d774 --- /dev/null +++ b/crates/eggwork-server/tests/artifact_capture_disposition.rs @@ -0,0 +1,207 @@ +//! The declared-artifact capture disposition, checked portably. +//! +//! This target exists because the server's own `#[cfg(test)]` harness is +//! Linux-shaped: it starts `/bin/sh`, uses `std::os::unix`, and sets +//! Unix-only file modes, so it does not compile for a Windows host. The +//! contract this milestone establishes — a declared output that was not +//! captured must never be reported as a successful execution — is a contract +//! about the *decision*, not about the host, so it is checked here against +//! the crate's public API on every platform. +//! +//! Nothing in this file may use `/bin/sh`, `std::os::unix`, or a Unix-only +//! mode: the target is compiled and run by the Windows job in CI. + +use eggwork_core::{ArtifactCaptureDisposition, ExecutionFailure, ExecutionState}; +use eggwork_server::{ + ArtifactCaptureAttempt, ArtifactCaptureCapability, ArtifactCaptureFacts, + artifact_capture_capability, decide_artifact_capture, +}; + +/// The disposition has the required states and round-trips on the wire. +/// +/// The spellings are a wire contract: a caller that reads the terminal +/// snapshot has to be able to name the state it is looking at. +#[test] +fn the_capture_disposition_has_the_required_states_and_round_trips() { + for (disposition, spelling) in [ + (ArtifactCaptureDisposition::NotRequested, "not_requested"), + (ArtifactCaptureDisposition::Completed, "completed"), + (ArtifactCaptureDisposition::Failed, "failed"), + ] { + let encoded = serde_json::to_string(&disposition).expect("the disposition serializes"); + assert_eq!( + encoded, + format!("\"{spelling}\""), + "the wire spelling of the disposition is a contract" + ); + let decoded: ArtifactCaptureDisposition = + serde_json::from_str(&encoded).expect("the disposition deserializes"); + assert_eq!(decoded, disposition); + } + // "Not requested" and "failed" are distinguishable from each other, and + // both are distinguishable from "completed": a caller never has to + // compare an artifact count against a declared-output count it does not + // have. + assert_ne!( + ArtifactCaptureDisposition::NotRequested, + ArtifactCaptureDisposition::Failed + ); + assert_ne!( + ArtifactCaptureDisposition::Completed, + ArtifactCaptureDisposition::Failed + ); +} + +/// The runtime capture-capability fact reports the correct value for the +/// platform it is running on. +/// +/// The fact is the node's, not the caller's: a caller asks the node's platform +/// rather than inferring the answer from its own `cfg`, because the two are +/// not necessarily the same one. On a platform that cannot open a file beneath +/// a workspace root safely, the fact says so. +#[test] +fn the_capture_capability_fact_matches_the_platform() { + let capability = artifact_capture_capability(); + if cfg!(unix) { + assert_eq!( + capability, + ArtifactCaptureCapability::Available, + "a Unix platform opens files beneath the workspace root with openat, \ + so it can capture declared outputs" + ); + } else { + assert_eq!( + capability, + ArtifactCaptureCapability::Unavailable, + "a platform without a descriptor-relative open cannot capture \ + declared outputs safely, and the fact has to say so" + ); + } +} + +/// A declared output that was not captured is never reported as a success. +/// +/// This is the regression the corrective exists for. Before it, the finalization +/// set the finalization-failure marker and left the terminal state +/// `Succeeded`, so a caller that declared outputs saw a successful execution +/// with zero artifacts and no error: the declared outputs were silently +/// dropped. The decision is checked here from outside the crate, so the +/// contract is reachable on a platform where the capture cannot run at all. +#[test] +fn a_declared_output_that_was_not_captured_never_reports_success() { + let capability = artifact_capture_capability(); + for attempt in [ + ArtifactCaptureAttempt::NotAttempted, + ArtifactCaptureAttempt::Failed, + ] { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability, + declared_outputs: true, + target_state: ExecutionState::Succeeded, + target_failure: None, + attempt, + }); + assert_ne!( + decision.state, + ExecutionState::Succeeded, + "an execution whose declared outputs were not captured must not \ + report success" + ); + assert_eq!(decision.state, ExecutionState::Failed); + assert_eq!( + decision.failure, + Some(ExecutionFailure::Internal), + "the capture failure is the node's own failure, not the target's" + ); + assert_eq!( + decision.disposition, + ArtifactCaptureDisposition::Failed, + "a declared output that was not captured must be reported as a \ + failed capture, never as a completed one" + ); + } +} + +/// A platform that cannot capture fails a declared output even when the +/// attempt claims otherwise. +/// +/// The capability decides the disposition before the attempt does: a node +/// whose platform cannot capture safely has no completed capture to report, +/// so the declared output is refused rather than dropped. +#[test] +fn a_platform_that_cannot_capture_refuses_a_declared_output() { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability: ArtifactCaptureCapability::Unavailable, + declared_outputs: true, + target_state: ExecutionState::Succeeded, + target_failure: None, + attempt: ArtifactCaptureAttempt::Completed, + }); + assert_ne!(decision.state, ExecutionState::Succeeded); + assert_eq!(decision.disposition, ArtifactCaptureDisposition::Failed); +} + +/// An execution that declared nothing reports that nothing was requested. +/// +/// The disposition distinguishes "no declared outputs were requested" from +/// "declared outputs were requested and the capture did not complete", so a +/// caller never has to compare the artifact count against a declared-output +/// count it does not have. +#[test] +fn an_execution_without_declared_outputs_reports_not_requested() { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability: artifact_capture_capability(), + declared_outputs: false, + target_state: ExecutionState::Succeeded, + target_failure: None, + attempt: ArtifactCaptureAttempt::NotAttempted, + }); + assert_eq!(decision.state, ExecutionState::Succeeded); + assert_eq!(decision.failure, None); + assert_eq!( + decision.disposition, + ArtifactCaptureDisposition::NotRequested + ); +} + +/// A completed capture on a capable platform leaves the target's outcome alone. +/// +/// The fail-closed rule must not swallow the success it is meant to protect: +/// a capture that completed keeps the target's own terminal state and +/// failure, and reports a completed disposition. +#[test] +fn a_completed_capture_keeps_the_targets_own_outcome() { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability: ArtifactCaptureCapability::Available, + declared_outputs: true, + target_state: ExecutionState::Succeeded, + target_failure: None, + attempt: ArtifactCaptureAttempt::Completed, + }); + assert_eq!(decision.state, ExecutionState::Succeeded); + assert_eq!(decision.failure, None); + assert_eq!(decision.disposition, ArtifactCaptureDisposition::Completed); +} + +/// A target that failed keeps its own failure when the capture also fails. +/// +/// A caller has to be able to tell "the target failed" from "the target +/// succeeded and its declared outputs could not be collected", so the +/// capture failure never overwrites the target's own failure. +#[test] +fn a_failed_target_keeps_its_own_failure_when_the_capture_also_fails() { + let decision = decide_artifact_capture(ArtifactCaptureFacts { + capability: ArtifactCaptureCapability::Available, + declared_outputs: true, + target_state: ExecutionState::Failed, + target_failure: Some(ExecutionFailure::Spawn), + attempt: ArtifactCaptureAttempt::Failed, + }); + assert_eq!(decision.state, ExecutionState::Failed); + assert_eq!( + decision.failure, + Some(ExecutionFailure::Spawn), + "the target's own failure must survive a capture failure" + ); + assert_eq!(decision.disposition, ArtifactCaptureDisposition::Failed); +} diff --git a/crates/eggwork-server/tests/installed_qualification.rs b/crates/eggwork-server/tests/installed_qualification.rs index 294bf32..11904fe 100644 --- a/crates/eggwork-server/tests/installed_qualification.rs +++ b/crates/eggwork-server/tests/installed_qualification.rs @@ -36,9 +36,10 @@ use std::{ use eggwork_client::NodeClient; use eggwork_core::{ - CommandSpec, EnvironmentEntry, ExecutionGeneration, ExecutionHandle, ExecutionId, - ExecutionSpec, ExecutionState, IsolationRequirement, LeaseId, NetworkRequirement, OutputPolicy, - Requirement, ResourceRequirements, StdinPolicy, + ArtifactCaptureDisposition, CommandSpec, DeclaredOutput, EnvironmentEntry, ExecutionGeneration, + ExecutionHandle, ExecutionId, ExecutionSpec, ExecutionState, IsolationRequirement, LeaseId, + NetworkRequirement, OutputPolicy, RelativePath, Requirement, ResourceRequirements, StdinPolicy, + WorkspaceId, WorkspaceManifest, }; use serde_json::{Value as Json, json}; const READY_TIMEOUT: Duration = Duration::from_secs(60); @@ -343,6 +344,28 @@ fn marker_command(marker: &Path, required: bool) -> Vec { } } +/// A command that creates the declared output inside the execution's working +/// directory, which is the workspace root for a workspace execution. +/// +/// The file has to exist before the capture runs: a declared output that the +/// target never produced is a *missing* output, which is a different +/// failure from a platform that cannot capture one. +fn declared_output_command() -> Vec { + if cfg!(windows) { + vec![ + target_shell().to_owned(), + "/C".to_owned(), + "echo eggwork-qualification > declared.txt".to_owned(), + ] + } else { + vec![ + "/bin/sh".to_owned(), + "-c".to_owned(), + "printf 'eggwork-qualification\\n' > declared.txt".to_owned(), + ] + } +} + async fn wait_for_terminal( client: &NodeClient, id: &ExecutionId, @@ -807,3 +830,184 @@ async fn installed_release_admits_execution_and_refuses_unsupported_isolation() ); Ok(()) } + +/// The declared-artifact disposition of an installed release binary. +/// +/// This is the property the corrective establishes, checked on the real host +/// rather than by inspection: where the node can capture declared outputs it +/// must capture them and say so, and where it cannot it must refuse them and +/// end the execution in a state that is not a success. Windows is the case +/// that matters — there is no descriptor-relative open beneath the workspace +/// root there — so the qualification proves the refusal path on the real +/// Windows host instead of asserting it from a Linux one. +#[tokio::test] +#[ignore = "qualifies an installed release binary; run with --ignored"] +async fn installed_release_reports_a_truthful_declared_artifact_disposition() -> Result<(), String> +{ + let subject = Subject::from_environment().expect("qualification subject"); + let mut facts: BTreeMap = BTreeMap::new(); + let node = start_installed_node(&subject, reserve_loopback_port()) + .await + .expect("the installed node starts and reports ready"); + let client = client(&subject, &node).expect("the production client builds"); + + // The advertisement follows the platform's capture capability: a node that + // cannot capture declared outputs must not claim that it can. + let capabilities = client.capabilities().await.expect("capabilities"); + let declared_capable = capabilities + .features + .iter() + .any(|feature| feature == "artifact.declared.v1"); + if cfg!(unix) { + assert!( + declared_capable, + "a Unix node can capture declared outputs and must advertise the \ + capability: {capabilities:?}" + ); + } else { + assert!( + !declared_capable, + "a node that cannot capture declared outputs must not advertise the \ + capability: {capabilities:?}" + ); + } + facts.insert( + "declared_artifact_capable".to_owned(), + json!(declared_capable), + ); + + // A declared output is read from the workspace root, so the execution + // needs a workspace. + let workspace_id = WorkspaceId::new(qualified_id("artifact-workspace")) + .map_err(|_| "the qualification workspace id is not usable".to_owned())?; + let execution_id = qualified_id("artifact-declared"); + client + .create_workspace( + &workspace_id, + &handle(&execution_id), + &WorkspaceManifest { + schema_version: 1, + entries: vec![], + }, + ) + .await + .map_err(|error| format!("creating the qualification workspace failed: {error}"))?; + let mut declared_spec = spec(declared_output_command(), IsolationRequirement::None); + declared_spec.command.declared_outputs = vec![DeclaredOutput { + path: RelativePath::new("declared.txt").map_err(|_| "the declared path is not usable")?, + required: true, + }]; + let stream = client + .execute_in_workspace(&declared_spec, &handle(&execution_id), &workspace_id) + .await + .map_err(|error| { + format!("the installed node refused the declared-output execution: {error}") + })?; + use futures_util::StreamExt; + let mut events = Box::pin(stream.into_events()); + while let Some(event) = events.next().await { + event.map_err(|error| format!("reading execution events failed: {error}"))?; + } + let observed = ExecutionId::new(&execution_id) + .map_err(|_| "the qualification execution id is not usable".to_owned())?; + let snapshot = wait_for_terminal(&client, &observed).await?; + let result = snapshot + .result + .clone() + .ok_or("the installed node reported no terminal result".to_owned())?; + let artifacts = client + .artifacts(&observed, 1) + .await + .map_err(|error| format!("listing the declared artifacts failed: {error}"))?; + + if declared_capable { + assert_eq!( + snapshot.state, + ExecutionState::Succeeded, + "a node that can capture declared outputs must complete the execution: {snapshot:?}" + ); + assert_eq!( + result.artifact_capture, + ArtifactCaptureDisposition::Completed, + "a completed capture must be reported as completed: {result:?}" + ); + assert_eq!( + artifacts.len(), + 1, + "the declared output must be published as an artifact: {artifacts:?}" + ); + } else { + // The refusal path: the declared output is refused, and the execution + // must not read as a success with the output silently dropped. + assert_ne!( + snapshot.state, + ExecutionState::Succeeded, + "a node that cannot capture declared outputs must not report a \ + successful execution: {snapshot:?}" + ); + assert_eq!( + result.artifact_capture, + ArtifactCaptureDisposition::Failed, + "a refused capture must be reported as a failed capture: {result:?}" + ); + assert_eq!( + result.artifact_count, 0, + "a refused capture must not report any captured artifact: {result:?}" + ); + assert!( + artifacts.is_empty(), + "a refused capture must not publish artifacts: {artifacts:?}" + ); + } + facts.insert( + "declared_artifact".to_owned(), + json!({ + "capable": declared_capable, + "state": format!("{:?}", snapshot.state), + "artifact_capture": format!("{:?}", result.artifact_capture), + "artifact_count": result.artifact_count, + "artifacts": artifacts.len(), + }), + ); + + let report = json!({ + "schema_version": 1, + "stage": format!("declared-artifact:{}", subject.platform), + "installed_daemon": subject.daemon.display().to_string(), + "facts": facts, + }); + if let Some(path) = declared_artifact_receipt(&subject) { + if let Some(parent) = path.parent() { + std::fs::create_dir_all(parent).map_err(|error| error.to_string())?; + } + std::fs::write( + &path, + serde_json::to_string_pretty(&report).map_err(|error| error.to_string())?, + ) + .map_err(|error| error.to_string())?; + } + println!( + "{}", + serde_json::to_string_pretty(&report).unwrap_or_default() + ); + Ok(()) +} + +/// The receipt path for the declared-artifact qualification. +/// +/// It is a sibling of the subject's receipt, not the receipt itself: the +/// execution qualification writes its own receipt to the same environment +/// path, and two suites writing one file would leave whichever ran last as +/// the only evidence. +fn declared_artifact_receipt(subject: &Subject) -> Option { + let path = subject.receipt.as_ref()?; + let stem = path.file_stem()?.to_string_lossy().into_owned(); + let extension = path + .extension() + .map(|value| value.to_string_lossy().into_owned()); + let name = match extension { + Some(extension) => format!("{stem}-declared-artifact.{extension}"), + None => format!("{stem}-declared-artifact"), + }; + Some(path.with_file_name(name)) +} diff --git a/docs/operations.md b/docs/operations.md index 3e3da5d..a2f5796 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -232,6 +232,22 @@ error, and never reveals whether a different id exists — authorization runs before resource resolution, so a denied caller cannot distinguish an existing resource from an absent one. +`executions show` prints the terminal snapshot, including the result's +`artifact_capture` field. It is the field to read when an execution declared +outputs: + +| `artifact_capture` | Meaning | What the operator sees | +|---|---|---| +| `not_requested` | The execution declared no outputs | Nothing was asked for, so nothing was lost | +| `completed` | The declared outputs were captured and published | The execution's artifacts are listed and downloadable | +| `failed` | The execution declared outputs and they were **not** captured | The terminal state is not `Succeeded`; the diagnostic in the event stream says whether the platform refused the capture or an attempted capture failed | +| `unknown` | The node reported no disposition (an execution recovered after a crash) | The terminal state is `Interrupted`; the declared outputs, if any, are gone | + +A declared output that could not be captured fails the execution rather than +leaving a successful execution with nothing in it, so a `Succeeded` execution +never hides a dropped declared output. The legacy `finalization_failure` +marker stays on the result as a secondary signal. + ## Redaction `config print` prints the effective config with the private key path and every diff --git a/plans/closure/workspace-artifact-transport/005a-status.md b/plans/closure/workspace-artifact-transport/005a-status.md new file mode 100644 index 0000000..dc3bed5 --- /dev/null +++ b/plans/closure/workspace-artifact-transport/005a-status.md @@ -0,0 +1,455 @@ +# Workspace and Artifact Transport M005a Closure — Declared-artifact capture fail-closed corrective + +- Milestone: **M005a — Declared-artifact capture fail-closed corrective** +- Corrective addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` (wins over the plan where they disagree) +- Implementation plan: `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md` +- Roadmap entry: `plans/subsystems/workspace-artifact-transport-roadmap.md` (§ M005a, status **implemented**) +- Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` +- Closed on: 2026-10-23 (Linux x86_64 host) + +## Finding + +The server's declared-artifact capture refuses on a platform that cannot open a file +beneath the workspace root safely: `artifact::open_file_beneath` has a `#[cfg(not(unix))]` +arm that returns `ErrorKind::Unsupported` rather than silently falling back to a +path-based open. The finalization, however, only recorded +`ExecutionFinalizationFailure::ArtifactCapture` and **left the terminal state +`Succeeded`**. A caller that declared outputs therefore saw a successful execution +with zero artifacts and no error: the declared outputs were silently dropped. The +same finalization set `artifact_count` to `0`, so the dropped outputs were +indistinguishable from an execution that declared none. + +The capability advertisement had the mirror-image defect: `static_capability_features` +listed `"artifact.declared.v1"` on **every** platform, so a Windows node advertised a +capability its capture path would refuse. The advertisement is what a caller uses to +decide whether to declare outputs at all, so the two facts had to be reconciled. + +The defect was asserted by a test, not merely implied by the code: the existing +integration assertion in `crates/eggwork-server/src/lib.rs` +(`blob_protocol_streams_verifies_deduplicates_and_enforces_quota`) pinned +`state == ExecutionState::Succeeded` together with `artifact_count == 0` and +`finalization_failure == Some(ArtifactCapture)`. That assertion was **revised +deliberately** by this milestone, not incidentally. + +## What was inspected by reading, and what was executed + +Everything in this record was produced on the Linux x86_64 host this milestone was +implemented on. The distinction is load-bearing, so it is stated per item: + +| Kind | Items | +| --- | --- | +| **Executed** | `cargo test --locked --workspace --all-targets` (every suite, including the new portable target and the revised server integration assertion), `cargo test --locked -p eggwork-core --all-targets`, `cargo test --locked -p eggwork-server --all-targets`, `cargo test --locked -p eggwork-server --test artifact_capture_disposition`, `cargo test --locked -p eggwork-server --features qualification --test installed_qualification` (compiles; its 3 tests are `#[ignore]`d), `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings`, `cargo fmt --all -- --check`, `cargo check --workspace`, `python3 scripts/check_execution_ownership.py`, `python3 scripts/check_execution_ownership.py --prove-negative-exit`, `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release`, `git diff --check`, `cargo check --locked -p eggwork-core --target x86_64-pc-windows-msvc`, `cargo check --locked -p eggwork-core --target x86_64-apple-darwin` | +| **Inspected only (code inspection)** | The Windows and macOS capture paths, the `#[cfg(not(unix))]` arm of `open_file_beneath`, the `windows-runner` CI job's new step, the hosted Windows qualification step, the `artifact.declared.v1` advertisement on a non-Unix node, and the whole of `crates/eggwork-server/tests/installed_qualification.rs` at run time | +| **Not run at all** | The hosted Windows qualification (`.github/workflows/operational-qualification.yml`) — it needs a tagged release, an installed daemon, and a Windows host. No receipt was produced. The `windows-runner` CI job has not run on this branch, because the branch is not pushed. | + +**A Linux run is not evidence for a Windows claim.** Nothing in this record should be +read as qualifying Windows or macOS. + +## Requirement-to-evidence matrix + +The criteria are numbered as in the plan's §12 (the plan's §11 is the documentation +list; the acceptance criteria are its §12). + +| # | Criterion | Implementation site | Test | Status | +| --- | --- | --- | --- | --- | +| 1 | No execution can reach terminal state `Succeeded` while a declared output it requested was not captured | `eggwork_server::decide_artifact_capture` (crate root, `crates/eggwork-server/src/lib.rs`), applied by `run_execution` | `a_declared_output_that_was_not_captured_never_reports_success` (server unit test and `tests/artifact_capture_disposition.rs`); `blob_protocol_streams_verifies_deduplicates_and_enforces_quota` (the missing-required-output path) | Met, executed on Linux | +| 2 | The capture failure is visible on the terminal state, in the event stream, and through the client's view — not only as `finalization_failure` | `publish_capture_diagnostic` (server crate root) on the existing `publish` path; `ExecutionResult.state` / `.failure` / `.artifact_capture` | The revised `blob_protocol_streams_verifies_deduplicates_and_enforces_quota` asserts the diagnostic event is present and that its position is **before** the `State(Failed)` event; the portable target asserts the terminal facts | Met, executed on Linux | +| 3 | The terminal result distinguishes "no declared outputs" from "declared outputs that vanished" through a first-class typed disposition, with no arithmetic required of the caller | `eggwork_core::ArtifactCaptureDisposition`; `ExecutionResult.artifact_capture` (`#[serde(default)]`) | `the_capture_disposition_round_trips` and `a_snapshot_without_the_capture_disposition_decodes_as_unknown` (core); `an_execution_without_declared_outputs_reports_not_requested` (server unit test and portable target) | Met, executed on Linux | +| 4 | The runtime capture-capability fact reports the correct value on every platform, and is reachable from outside the crate-private data-plane modules | `artifact::capture_capability` / `artifact::ArtifactCaptureCapability`, re-exported at the crate root as `eggwork_server::artifact_capture_capability` | `the_capture_capability_fact_matches_the_platform` (portable target) — asserts `Available` on `cfg!(unix)` and `Unavailable` otherwise; the *non-Unix* branch is **not executed here** | Met on Linux; the non-Unix value is code inspection plus the portable assertion, and is executed by the `windows-runner` job once it runs | +| 5 | The advertised capability set agrees with the runtime fact, and the plan records what a caller sees when the capability is absent | `server_capability_features` filters `ARTIFACT_DECLARED_CAPABILITY` on the fact; the capability *name* is unchanged | `the_declared_artifact_capability_is_advertised_only_when_the_platform_can_capture` (server unit test) | Met, executed on Linux (where the fact is `Available`, so the test pins the present case; the absent case is pinned by the same test's `Unavailable` arm and by code inspection) | +| 6 | The existing integration test that asserted `Succeeded` + `artifact_count == 0` + `finalization_failure == Some(ArtifactCapture)` has been replaced by an assertion of the corrected disposition, and the replacement is proven non-vacuous | The revised assertion in `blob_protocol_streams_verifies_deduplicates_and_enforces_quota` now asserts `Failed`, `failure == Some(Internal)`, `artifact_capture == Failed`, and the diagnostic-before-terminal ordering | The negative-evidence experiment below | Met, executed on Linux | +| 7 | The new portable test target compiles and passes on a non-unix host, and is wired into the `windows-runner` CI job | `crates/eggwork-server/tests/artifact_capture_disposition.rs`; `.github/workflows/ci.yml` step *declared-artifact capture disposition suite* | The 7 tests of the portable target pass on Linux; **the Windows compile and run is not observed here** — the cross-check is blocked by the environment (below) and the CI job is the evidence | Partially met: wired and green on Linux; the Windows run is outstanding | +| 8 | The Windows hosted qualification declares an output and asserts the truthful terminal disposition against the installed daemon, and the receipt is recorded | `installed_release_reports_a_truthful_declared_artifact_disposition` in `crates/eggwork-server/tests/installed_qualification.rs` | The test compiles with `--features qualification` and is `#[ignore]`d like its sibling; **it was not executed** — it needs an installed daemon, a Windows host, and a hosted run | Not met here: the test exists, the *run* does not, and the workflow step that would run it is coordinator-owned (finding F-01) | +| 9 | The README's Windows caveat and the `architecture/overview.md` divergences table state the artifact disposition, and the statement matches the code | `architecture/overview.md` row 22 (new *Platform limitations* subsection) | Inspection; the row is checked against `artifact::capture_capability` and `server_capability_features` | Partially met: the overview row is written; **the README is not edited** (coordinator-owned, finding F-02) | +| 10 | No bound is widened | No constant was added, removed, or changed in `eggwork-core`, `eggwork-server`, or `eggwork-runner` | `git diff` over the three crates: `MAX_OUTPUTS`, `MAX_ARTIFACT_FILES`, `MAX_ARTIFACT_TOTAL_BYTES`, `MAX_BLOB_BYTES`, and every digest bound are untouched | Met | +| 11 | The unix capture tests keep their original meaning and stay green, and the happy-path integration assertion is still green | The capture path (`artifact.rs`) is unchanged apart from the added capability fact | `descriptor_relative_capture_rejects_parent_swapped_to_symlink`, `missing_required_and_symlink_outputs_fail_without_records`, `disappearing_output_and_storage_quota_fail_without_publishing_records` — executed, green; the happy path now also asserts `artifact_capture == Completed` | Met, executed on Linux | +| 12 | The double hash in `crates/eggwork-server/src/artifact.rs` is still present and documented as accepted | `capture_blob` hashes while reading and `blobs.put_stream` verifies again | Inspection; the function is unchanged in this milestone | Met | +| 13 | No authentication, lease, generation, fencing, or digest-bound semantics weakened; no queue, worker selection, priority, fairness, DAG, or semantic retry introduced | The change is confined to the capture finalization, the capability advertisement, and the diagnostic class set | `python3 scripts/check_execution_ownership.py` (passed); the lease/admission code is untouched; no new crate edge | Met | +| 14 | `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` and `cargo test --locked --workspace --all-targets` are green on the same head | — | Executed here: both green (see *Verification actually run*) | Met | + +## Decisions taken where the plan left the choice open + +### The §5.4 resolution: **(b)** + +The platform cannot support safe capture — `open_file_beneath` is a descriptor-relative +`NOFOLLOW` chain with no non-Unix implementation — so **resolution (b)** is the truth +of the platform: + +- the platform's capture-capability fact reports capture as **unavailable** where safe + capture is not possible (`artifact::capture_capability` is `Unavailable` on + `not(unix)`); +- an execution that declares outputs there terminates in a **truthful non-success + state** (`ExecutionState::Failed`, `ExecutionFailure::Internal`, disposition + `Failed`); +- the platform claim states that declared outputs are **refused** on that platform + rather than silently dropped. + +The Windows *implementation* of a safe open remains outstanding. Per the plan's §5.5 it +is deferred to a follow-on, and the deferral is only legitimate because the fail-closed +contract is implemented in this same milestone. The follow-on is named in the +unresolved findings (F-04). + +On the Linux host used here, safe capture **does** work, so the fact reports +`Available` and the truthful-failure path is exercised by the portable test rather +than by the platform itself. Both branches of the decision exist and are reachable: +`decide_artifact_capture` is parameterised by the capability, and the portable target +drives the `Unavailable` branch directly. + +### The public-reachability shape: a targeted `pub use` re-export plus a public decision function + +`crates/eggwork-server/src/lib.rs` declares `mod artifact;` privately, alongside +`mod blob;`, `mod store;`, and `mod workspace;`. The least-privilege shape that makes +the contract reachable from outside the crate is: + +- `pub use artifact::ArtifactCaptureCapability;` and + `pub use artifact::capture_capability as artifact_capture_capability;` — the data + plane keeps ownership of the fact, and the crate root re-exports it rather than + reimplementing it. A caller asks the *node's* platform; it does not infer the + answer from its own `cfg`. +- `pub fn decide_artifact_capture(facts: ArtifactCaptureFacts) -> ArtifactCaptureDecision` + at the crate root — the single, testable decision. + +The alternative shapes were rejected: making `mod artifact` public would expose the +whole data-plane module (blob store internals, artifact store internals) rather than +the two facts the contract needs, and a wrapper function at the crate root would add +a second call path for the same fact. + +**Compatibility consequence.** `eggwork-server` is a published crate, so this is a +release-visible public API addition. It is **additive**: nothing is removed and +nothing is renamed, so it is compatible. The added surface is +`ArtifactCaptureCapability`, `artifact_capture_capability`, `ArtifactCaptureAttempt`, +`ArtifactCaptureFacts`, `ArtifactCaptureDecision`, and `decide_artifact_capture`. + +### The `ExecutionFailure` choice: the terminal state **and** the failure both change + +A capture that did not complete moves the terminal state to `ExecutionState::Failed` +**and** sets `ExecutionFailure::Internal`. The reasoning: + +- The plan requires that a caller can distinguish "the target failed" from "the target + succeeded and its declared outputs could not be collected". The terminal *state* + alone cannot carry that distinction, because both cases end in `Failed`. +- The *target's own* failure is never overwritten. A target that failed for its own + reason keeps that failure (`Some(ExecutionFailure::Spawn)` stays `Spawn`), so the + node's `Internal` failure appears only where the node itself failed. +- The new `ExecutionFailure` variant that would say "the capture failed" was **not** + added. The plan's stop condition (§13) makes a vocabulary change that the existing + vocabulary cannot express an architecture question. The existing vocabulary *can* + express it — `Failed` + `Internal`, plus the first-class disposition, plus the + diagnostic — so no ADR is needed. + +The distinction is therefore: `failure == Some(Internal)` **and** +`artifact_capture == Failed` means "the target succeeded and the node could not +collect its declared outputs"; `failure == Some()` means the target +failed for its own reason. + +### The disposition has a fourth state: `Unknown` + +The plan named three states (`not requested`, `completed`, `failed`). The +implementation has four: `NotRequested`, `Completed`, `Failed`, and `Unknown`. + +The fourth state exists because of the `#[serde(default)]` requirement. The field's +default is what a peer decodes when it reads a snapshot written *before* the field +existed, and the plan's own framing of the requirement is that a peer must not be +forced to read an absence as a fact. `NotRequested` as the default would be a claim — +"the caller asked for nothing" — that such a snapshot cannot support, and it would +reproduce exactly the silent-success misreading this milestone exists to kill. So the +default is `Unknown`: "the node reported no disposition", and a caller falls back to +the legacy `finalization_failure` marker and the artifact count. + +`Unknown` is also what the crash-recovery path writes, because +`ExecutionStore::recover` cannot know what the interrupted execution declared. That is +the same statement: the node reports no disposition. + +### The diagnostic class: `artifact.capture.failed` + +`eggwork_core::DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED = "artifact.capture.failed"`, +added to the closed `DIAGNOSTIC_CLASSES` set (which becomes `[&str; 3]`). The payload +carries `requirement=declared` (the caller declared outputs and the node owns +delivering them — this is not a degradation of a best-effort request), +`outcome=platform_unavailable | capture_failed`, and `reason`. + +The diagnostic rides the server's **existing** event-publishing path — the same +`publish` call every stdout/stderr/diagnostic chunk uses — so there is one publisher +for `ExecutionEventKind::Diagnostic`, not two. The Security M005a milestone's +publisher was extended, not duplicated. + +The payload is bounded by `MAX_DIAGNOSTIC_PAYLOAD_BYTES` (2048, which is +`MAX_METADATA_VALUE_BYTES`), and `ExecutionEvent::validate` bounds a `Diagnostic` +payload by `MAX_EVENT_CHUNK_BYTES` (65536). **2048 < 65536**, so the diagnostic can +never overflow the event it rides in; the relationship is asserted as a compile-time +fact in `eggwork-core` and documented in `architecture/protocol.md`. + +### The `finalization_failure` marker stays, as a secondary marker + +`ExecutionFinalizationFailure::ArtifactCapture` is still set on a failed capture, and +it is no longer the only signal. It remains a *secondary* marker with two known +properties, recorded as findings below: it can still be overwritten by the retention +marker when both the capture and the workspace retention fail (F-05), and a legacy +node's snapshot still carries it alone (F-06). + +### The §9 coverage combination: **Option B + Option C + Option D** + +The plan's recommended combination, taken in full. + +- **Option B** — a new portable integration test target, + `crates/eggwork-server/tests/artifact_capture_disposition.rs`, and a new + `windows-runner` step in `.github/workflows/ci.yml` that runs **only that target** + (`cargo test --locked -p eggwork-server --test artifact_capture_disposition`). The + job's scope comment was updated in the same commit to say what is now covered, and + the claim was not widened: the rest of the server's test surface is still + Linux-shaped and is still explicitly not claimed. +- **Option C** — `crates/eggwork-server/tests/installed_qualification.rs` gained + `installed_release_reports_a_truthful_declared_artifact_disposition`, which + declares an output, drives the installed daemon, and asserts the truthful terminal + disposition: `Succeeded` + `Completed` + one published artifact where the node + advertises the capability, and **not** `Succeeded` + `Failed` + zero artifacts + where it does not. +- **Option D** — the platform fact is reachable from the portable test + (`eggwork_server::artifact_capture_capability`), so the non-Unix stub's behaviour is + covered indirectly: the portable test asserts the fact's value for the host it runs + on and drives the fail-closed decision from it. + +**The trade-off accepted.** Option D's coverage of "`open_file_beneath` refuses" is +host-dependent: the stub's own error path is exercised only on a non-Unix host, so +the *decision* is covered everywhere and the *stub* only where the stub runs. Option B +costs a small additive public API change to a published crate and one more step in the +Windows job. Option C is workflow-level, tag-gated, and slow, so a regression could +merge green in `ci.yml` and be caught only at qualification time — which is exactly +why B is not optional. The combination buys PR-gate coverage on every platform, plus +the real-Windows evidence against installed bytes, at the cost of a public API +addition and a duplicated test surface (the same contract is asserted in the unit +harness and in the portable target). + +## Non-vacuity evidence + +The corrective is not proven by a green run alone: the new tests were shown to **fail +against the silent-success shape**. + +The production decision was temporarily patched to reproduce the old shape — a declared +output that was not captured leaves the terminal state `Succeeded` — and the suites +were re-run against the final code: + +```text +$ cargo test --locked -p eggwork-server --test artifact_capture_disposition +---- a_declared_output_that_was_not_captured_never_reports_success stdout ---- +thread 'a_declared_output_that_was_not_captured_never_reports_success' panicked at + crates/eggwork-server/tests/artifact_capture_disposition.rs:104:9: +assertion `left != right` failed: an execution whose declared outputs were not captured must not report success + left: Succeeded + right: Succeeded +---- a_platform_that_cannot_capture_refuses_a_declared_output stdout ---- +thread 'a_platform_that_cannot_capture_refuses_a_declared_output' panicked at + crates/eggwork-server/tests/artifact_capture_disposition.rs:140:5: +assertion `left != right` failed + left: Succeeded + right: Succeeded +test result: FAILED. 5 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out +``` + +```text +$ cargo test --locked -p eggwork-server --lib +test tests::a_declared_output_that_was_not_captured_never_reports_success ... FAILED +test tests::blob_protocol_streams_verifies_deduplicates_and_enforces_quota ... FAILED +---- tests::blob_protocol_streams_verifies_deduplicates_and_enforces_quota stdout ---- +thread 'tests::blob_protocol_streams_verifies_deduplicates_and_enforces_quota' panicked at + crates/eggwork-server/src/lib.rs:4055:9: +the terminal state event must report the failure: [ExecutionEvent { sequence: EventSequence(1), kind: State(Accepted), … }, +ExecutionEvent { sequence: EventSequence(2), kind: State(Running), … }, +ExecutionEvent { sequence: EventSequence(3), kind: Diagnostic { length: 166, value: "[REDACTED]" }, … }, +ExecutionEvent { sequence: EventSequence(4), kind: State(Succeeded), … }] +test result: FAILED. 154 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out +``` + +The second failure is the important one. The dumped event stream is the defect in +one place: the capture-failure **diagnostic** is published (sequence 3) and the +terminal event still says `State(Succeeded)` (sequence 4) — a successful execution +with a capture failure recorded and no error. The pre-existing integration assertion +— the one that had pinned the silent-success shape — fails against the corrected +behaviour, and the failure message names the missing terminal state event rather than +a symptom of it. + +The patch was reverted immediately afterwards, and both suites were re-run green +(156 passed; 7 passed). + +The other non-vacuity arguments: + +- The revised happy-path assertion (`artifact_count == 1`, + `finalization_failure == None`) gained `artifact_capture == Completed`, so a + corrective that turned a successful capture into a failure would fail the test. +- The portable target asserts the *wire spellings* of the disposition, so a + disposition that is renamed or re-spelled breaks it. +- The advertisement test asserts the capability is present **iff** the fact says the + platform can capture, so restoring the unconditional advertisement fails it on a + platform that cannot capture. + +## Verification actually run + +All commands were run on this Linux x86_64 host against the working tree as it stands +(commit `IMPLEMENTATION-COMMIT-PENDING`). + +| Command | Result | +| --- | --- | +| `cargo fmt --all -- --check` | **passed** — no diff | +| `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` | **passed** — no warnings. One clippy finding was fixed during the work: `clippy::assertions_on_constants` on the payload-bound assertion, replaced by a compile-time `const _: () = assert!(…)` | +| `cargo check --workspace` | **passed** | +| `cargo test --locked -p eggwork-core --all-targets` | **passed** — 35 unit + 7 contract tests, 0 failed | +| `cargo test --locked -p eggwork-server --all-targets` | **passed** — 156 unit tests, plus `gc_preview_parity` (3), `host_telemetry` (12), `release_contract` (36), `shared_contract_ownership` (6), `artifact_capture_disposition` (7), 0 failed | +| `cargo test --locked -p eggwork-server --test artifact_capture_disposition` | **passed** — 7 passed, 0 failed | +| `cargo test --locked -p eggwork-server --features qualification --test installed_qualification` | **compiles**; 3 tests present, all `#[ignore]`d, 0 run. The qualification needs an installed daemon and `EGGWORK_QUALIFY_*`, so it **was not executed** | +| `cargo test --locked --workspace --all-targets` | **passed** — every suite green: client 13, core 35, `shared_protocol_contract` 7, runner 28 (+1 ignored), `capability_probe` 2, `diagnostic_degradation` 7, `environment_policy` 5, `environment_policy_parity` 12, `landlock_runner` 18, server 156, `artifact_capture_disposition` 7, `gc_preview_parity` 3, `host_telemetry` 12, `release_contract` 36, `shared_contract_ownership` 6. The `windows_process_tree` suite is `#![cfg(windows)]` and reported 0 tests on this host | +| `python3 scripts/check_execution_ownership.py` | **passed** — approved process owners unchanged: `eggwork-runner` (2 spawn sites), `eggwork-sandbox-helper` (1 spawn site) | +| `python3 scripts/check_execution_ownership.py --prove-negative-exit` | **passed** — the synthetic forbidden spawn is detected | +| `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` | **passed** — 57 tests, OK | +| `git diff --check` | **passed** — no whitespace error | +| `cargo check --locked -p eggwork-core --target x86_64-pc-windows-msvc` | **passed** — the core crate, which carries the new disposition and the new diagnostic class, compiles for the Windows target | +| `cargo check --locked -p eggwork-core --target x86_64-apple-darwin` | **passed** — same, for the macOS target | +| `cargo check --locked -p eggwork-server --test artifact_capture_disposition --target x86_64-pc-windows-msvc` | **blocked by the environment, not by the change** — a transitive C dependency (`ring` / `aws-lc-sys`) needs MSVC's `lib.exe`, which is not installed on this Linux host. The failure happens in the dependency's build script, before any Eggwork code is compiled. This is the constraint `architecture/ci-guardrails.md` already records for a full `--workspace --target x86_64-pc-windows-msvc` check ("`cc-rs` needs MSVC's `lib.exe` for a transitive C dependency"). The Windows compile of the server crate and of the new target is the `windows-runner` CI job's evidence, and it has not run yet | + +**Workspace-wide gate.** The coordinator runs `cargo test --locked --workspace --all-targets` +and the `tests/release` unittest suite once at the end of the batch. This milestone ran +both itself (results above) and records them; that is a second observation of the same +command, not a substitute for the coordinator's. + +## Platform and feature matrix actually exercised + +| Platform | What was exercised | Status | +| --- | --- | --- | +| **Linux x86_64** | The full unit and integration suites, including the capture path, the revised missing-required-output integration assertion, the diagnostic ordering, the advertisement, and the portable target. The platform fact is `Available` here, so the *capable* branch of the decision is the one the platform itself drives. | **Executed and green.** This is the only platform with executed evidence. | +| **Windows x86_64 (`x86_64-pc-windows-msvc`)** | `eggwork-core` compiles for the target. The server crate and the new portable target **could not be cross-checked** (the environment lacks the MSVC C toolchain). The `#[cfg(not(unix))]` arm of `open_file_beneath`, the `Unavailable` capability branch, the Windows advertisement, and the hosted qualification are **code inspection only**. | **Not qualified.** Compilation is not qualification. The Windows rows stay open until the `windows-runner` job and the hosted qualification run green. | +| **macOS (`x86_64-apple-darwin`)** | `eggwork-core` compiles for the target. The capture path is the Unix path, so the platform behaves like Linux for this feature, but **nothing was executed** for macOS. | **Not qualified.** No macOS host and no execution. | + +## Compatibility review + +**Wire.** `ExecutionResult` gained one `#[serde(default)]` field, +`artifact_capture`. This is wire-additive: + +- a peer that predates the field **ignores** it, because `ExecutionResult` does not + deny unknown fields — so an older client still decodes a terminal snapshot produced + by a newer node; +- a peer that has the field decodes a snapshot written before it existed as + `Unknown`, because the field is `#[serde(default)]` and the default is `Unknown`. + +**The terminal snapshot is NOT byte-identical across this change.** Two things moved: +the result gained a field, and a capture that did not complete no longer reports +`Succeeded`. A consumer that diffs terminal snapshots byte-for-byte across the +upgrade will see a difference, and a consumer that reads `state` will see `Failed` +where it used to see `Succeeded` for a failed capture. This is the intended behaviour +change, not an accident. + +**No stored format changes.** No blob, workspace, artifact, manifest, or journal row +format changed. `ExecutionSnapshot` still serializes as it did, with one more field +inside its result. + +**No capability-string change.** The name `artifact.declared.v1` is unchanged. Only +its *advertisement* became conditional, which is the point of the milestone. No new +capability string was added, so `crates/eggwork-server/tests/release_contract.rs` +needed no change. + +**No migration.** Nothing is rewritten on disk. A node upgraded with this change +reports the corrected disposition for new executions only; historical terminal +snapshots keep their existing shape and their `finalization_failure` marker, and +decode as `Unknown` in the new field. + +**Client.** `crates/eggwork-client` returns `ExecutionSnapshot` from +`observe` / `observe_generation`, and `ExecutionSnapshot.result` is an +`eggwork_core::ExecutionResult`. The disposition is therefore already visible to a +client caller through the existing API: **no client API addition is required**, and +none was made. + +**Source compatibility (out-of-tree).** `ExecutionResult` is a public struct with +public fields, so adding a field breaks an out-of-tree *constructor* of it (it is +compatible for readers). Inside the workspace there are exactly two construction +sites outside the milestone's declared file ownership, and both were updated with a +one-line placeholder (see *Deviations from the plan*). + +## Documentation status + +| Document | Change | +| --- | --- | +| `architecture/protocol.md` | The diagnostic class set now names `artifact.capture.failed`; the required-keys table gained the `requirement=declared` value for that class and the `outcome` key; the bound section states the `MAX_DIAGNOSTIC_PAYLOAD_BYTES` (2048) / `MAX_EVENT_CHUNK_BYTES` (65536) relationship. The truncation rule is unchanged and still documented. | +| `architecture/data-plane.md` | A new section, *The capture-failure contract and the platform claim*, documents the capability fact, the conditional advertisement, the four disposition states, the decision, the diagnostic, and the unchanged eligibility rule. The *Honest gaps* entry about the untested non-Unix branches was revised to say what is now covered and what is still not. Three rows were added to the *Invariants and enforcement* table. | +| `architecture/overview.md` | The divergences section gained **row 22** in a new *Platform limitations* subsection, stating the platform limitation truthfully and marking the silent-success defect closed. Row 12 (the Control-plane M004 divergence) was **not** touched. | +| `docs/operations.md` | The *Inspection and history* section now documents the `artifact_capture` field an operator sees on `executions show`, with the four states and what each means. | +| `docs/quickstart.md` | **Not changed.** The plan requires both documents to be checked and says which changed. The quickstart is a Linux walkthrough, and on Linux the operator-facing behaviour of a declared output is unchanged (it is captured and published); the quickstart never mentions artifacts, so there was nothing to correct there. The failing-capture behaviour is documented in `docs/operations.md` instead. | +| `README.md` | **Not changed — coordinator-owned.** The Windows caveat is silent on artifacts, and the plan requires it to state the disposition. See finding F-02 for the exact text. | +| `architecture/ci-guardrails.md` | **Not changed — coordinator-owned.** It reproduces the `windows-runner` job's YAML verbatim, so the reproduced block is now one step short. See finding F-03 for the exact text. | +| `plans/subsystems/workspace-artifact-transport-roadmap.md` | The M005a entry is now **implemented**, with a closure-record link and an *Implemented* list. The status line was updated. The M005b section was **not** touched. | + +## Deviations from the plan + +1. **Two files outside the milestone's declared ownership were edited.** Adding a field + to `eggwork_core::ExecutionResult` — a public struct with public fields — breaks + every struct-literal construction of it. There are exactly two such sites outside + the milestone's ownership, and both had to be updated for the workspace to compile: + + - `crates/eggwork-runner/src/lib.rs` — `RunnerResult::execution_result()` now sets + `artifact_capture: eggwork_core::ArtifactCaptureDisposition::Unknown`. The runner + owns the process, not the capture; the server's finalization replaces this + placeholder. The placeholder claims nothing, which is why it is `Unknown` and + not `NotRequested`. + - `crates/eggwork-server/src/store.rs` — `ExecutionStore::recover` now sets + `artifact_capture: eggwork_core::ArtifactCaptureDisposition::Unknown`, because + the recovery path cannot know what the interrupted execution declared. + + Each is a one-line addition with a comment. No other line of either file changed, + and no behaviour of either file changed. The alternative — leaving the field out of + `ExecutionResult` — would have failed acceptance criterion 3 outright. + +2. **The disposition has a fourth state**, `Unknown`, beyond the three the plan named. + The reasoning is in *Decisions taken where the plan left the choice open*: the + `#[serde(default)]` default must not fabricate a claim, and the plan's own + requirement is that a peer must not read an absence as a fact. + +3. **The overview's new row is in a new *Platform limitations* subsection.** Rows 1-21 + are cited by number elsewhere in the repository, so inserting row 22 into an earlier + table would renumber them. The new subsection keeps the numbering monotonic and the + theme honest: the row is about a platform, not about a module. + +4. **The qualification receipt path is derived, not taken verbatim.** The new + qualification suite writes to `-declared-artifact.` rather than + to the subject's receipt path, because the execution qualification writes to that + path and two suites writing one file would leave whichever ran last as the only + evidence. + +## Unresolved findings by severity + +| # | Severity | Finding | Owner | +| --- | --- | --- | --- | +| F-01 | **High** | The hosted Windows qualification step that would run `installed_release_reports_a_truthful_declared_artifact_disposition` does not exist. `.github/workflows/operational-qualification.yml` runs the qualification suites by `--exact` name, so the new suite is never invoked. The exact step text is in the report to the coordinator. Until it is added, acceptance criterion 8 is unmet. | Coordinator (workflow is not in this milestone's ownership) | +| F-02 | **High** | The README's Windows caveat is still silent on artifacts. Acceptance criterion 9 requires the README and the divergences table to say the same thing; the table says it, the README does not. Exact text in the report to the coordinator. | Coordinator (README is not in this milestone's ownership) | +| F-03 | Medium | `architecture/ci-guardrails.md` reproduces the `windows-runner` job's YAML verbatim; the reproduced block is now one step short of the checked-in workflow. Exact text in the report to the coordinator. | Coordinator (file is not in this milestone's ownership) | +| F-04 | Medium | The Windows *implementation* of a safe descriptor-relative open beneath the workspace root is still outstanding. This milestone makes the refusal truthful; it does not make the capture work on Windows. The plan's §5.5 permits the deferral only because the fail-closed contract landed in the same milestone — which it did. | Product/roadmap (a named follow-on milestone) | +| F-05 | Low | The legacy `finalization_failure` marker can still be overwritten by the retention marker when both the capture and the workspace retention fail. The first-class disposition is unaffected, but a consumer that reads *only* the legacy marker can miss the capture failure in that combination. | Product/roadmap | +| F-06 | Low | A legacy node's silent-success shape cannot be repaired by a new peer: an old snapshot decodes with `artifact_capture == Unknown`, and the caller must fall back to the legacy `finalization_failure` marker and the artifact count. The new disposition says "not reported", not "fine". | Product/roadmap | +| F-07 | Low | The crash-recovery path reports `Unknown` rather than a disposition, because it cannot know what the interrupted execution declared. The execution's terminal state is `Interrupted`, so no caller is told a success it did not get. | Product/roadmap | +| F-08 | Low | `ExecutionResult` is a public struct with public fields, so the new field is source-breaking for an out-of-tree *constructor* of it (compatible for readers). The two in-workspace constructors were updated in this milestone. | Release management (semver note for the next release) | +| F-09 | Info | The `windows-runner` CI job's new step and the hosted qualification step have not run on this branch, because the branch is not pushed. The Windows rows of the platform matrix stay open until they do. | Coordinator (push and read the job) | + +## Registry and roadmap disposition + +- **Roadmap** — `plans/subsystems/workspace-artifact-transport-roadmap.md` § M005a is + now **implemented**, with a closure-record link and an *Implemented* list; the + status line reads *"M001-M004 closed; M005a data-plane corrective implemented; M005b + data-plane corrective implemented"*. The M005b section was not touched. +- **Registry** — `plans/registry.md` is coordinator-owned and was **not** edited. The + exact text for it is in the report to the coordinator. +- **Closure record** — this file. + +## Change set + +| File | Change | +| --- | --- | +| `crates/eggwork-core/src/lib.rs` | `DIAGNOSTIC_CLASS_ARTIFACT_CAPTURE_FAILED`; `DIAGNOSTIC_CLASSES` becomes `[&str; 3]`; `ArtifactCaptureDisposition` (+ `Default`); `ExecutionResult.artifact_capture`; three new unit tests | +| `crates/eggwork-server/src/artifact.rs` | `ArtifactCaptureCapability` and `capture_capability`, stated next to the platform-specific `open_file_beneath` | +| `crates/eggwork-server/src/lib.rs` | The crate-root public surface (`ArtifactCaptureAttempt`, `ArtifactCaptureFacts`, `ArtifactCaptureDecision`, `decide_artifact_capture`, the two re-exports); the conditional `artifact.declared.v1` advertisement; the finalization's fail-closed capture handling; `publish_capture_diagnostic`; the `failed_result` placeholder; the revised integration assertion; six new unit tests | +| `crates/eggwork-server/src/store.rs` | The crash-recovery placeholder (one line) — outside the declared ownership, see *Deviations* | +| `crates/eggwork-runner/src/lib.rs` | The runner's placeholder (one line) — outside the declared ownership, see *Deviations* | +| `crates/eggwork-server/tests/artifact_capture_disposition.rs` | **New.** The portable integration target: 7 tests, no `/bin/sh`, no `std::os::unix` | +| `crates/eggwork-server/tests/installed_qualification.rs` | The declared-artifact qualification suite and its receipt-path helper | +| `architecture/protocol.md` | The diagnostic class set, the `requirement`/`outcome` keys, the payload-bound relationship | +| `architecture/data-plane.md` | The capture-failure contract and platform claim; the revised *Honest gaps* entry; three invariant rows | +| `architecture/overview.md` | Divergences row 22 in a new *Platform limitations* subsection | +| `docs/operations.md` | The `artifact_capture` field in *Inspection and history* | +| `.github/workflows/ci.yml` | The `windows-runner` step *declared-artifact capture disposition suite*, and the job's scope comment updated to say what is now covered | +| `plans/subsystems/workspace-artifact-transport-roadmap.md` | The M005a entry (status, closure link, *Implemented* list) and the status line | +| `plans/closure/workspace-artifact-transport/005a-status.md` | **New.** This record | diff --git a/plans/registry.md b/plans/registry.md index 5896a97..28a1a3a 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -91,7 +91,7 @@ A repository-wide code interrogation pass over the reviewed baseline found no `t | Addendum | Milestones | Class | Status | |---|---|---|---| | `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | implemented | -| `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a proposed; M005b implemented | +| `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a implemented; M005b implemented | | `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a/M005b implemented; **M005c blocked on ADR-0007** | | `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | | `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | proposed | @@ -110,7 +110,7 @@ Two findings in this batch were deliberately **not** given a milestone, because | Optional Gregg host telemetry | **closed; M001 and M002 both closed** | M001 closed the default-off loopback Gregg adapter, normalized cache and single polling owner (`plans/closure/optional-gregg-host-telemetry/001-status.md`, implementation `ac55985`); M002 closed the authorized node telemetry API/client behind a narrow `telemetry` grant (`plans/closure/optional-gregg-host-telemetry/002-status.md`, implementation `5ccb1e6`). The frozen contract is `eggwork_core::NodeTelemetry` schema version 1. No Gregg changes, no Eggwork scheduling, no capability feature added. The CodeGG worker-telemetry consumer is unblocked. | `plans/subsystems/optional-gregg-host-telemetry-roadmap.md`, `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` | | Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | | Control-plane protocol | M001-M004 closed; no milestone in flight | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept — **implemented**: `eggwork-core` now owns the control-plane schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification, and the runner owns the capability names it produces. No wire value, wire field, or capability byte changed. Closure record: `plans/closure/control-plane-protocol/004-status.md` | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | -| Workspace / artifacts | M001-M004 closed; M005a and M005b correctives proposed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | +| Workspace / artifacts | M001-M004 closed; M005a and M005b correctives implemented | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) — **implemented**: a declared output that was not captured now ends the execution in a truthful non-success state with a first-class disposition and a diagnostic event, and a node whose platform cannot capture no longer advertises `artifact.declared.v1` — and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, `plans/closure/workspace-artifact-transport/005a-status.md`, `plans/closure/workspace-artifact-transport/005b-status.md` | | Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a implemented, M005b proposed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | | Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready; M008a/M008b proposed | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. A repository interrogation pass added M008a (five live metrics are never reported by the operator surface; one `active_executions` field name carries two meanings; every configuration fault collapses into one unhelpful message) and M008b (the release harness re-derives facts that already have an owner, and the design record's line citations and size figures are stale with no gate) | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md`, `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | @@ -142,6 +142,8 @@ The repository interrogation corrective batch is registered but is **not** depen | Workspace | M002 materialization | closed | `plans/closure/workspace-artifact-transport/002-status.md` | | Workspace | M003 artifacts/retention/GC | closed | `plans/closure/workspace-artifact-transport/003-status.md` | | Workspace | M004 reusable manifest CAS + derived materialization | closed | `plans/closure/workspace-artifact-transport/004-status.md`; consumed by closed downstream CodeGG M003 | +| Workspace | M005a declared-artifact capture fail-closed | implemented | `plans/closure/workspace-artifact-transport/005a-status.md` — a declared output that was not captured now ends the execution in a truthful non-success state with a first-class capture disposition, and a node whose platform cannot capture does not advertise `artifact.declared.v1`. The platform limitation itself remains: declared artifacts are captured on a Unix platform only. | +| Workspace | M005b GC preview and store ownership | implemented | `plans/closure/workspace-artifact-transport/005b-status.md` — the operator's GC preview and the apply pass now select candidates through the same store-owned statement, the store's path layout and metadata filenames have one owner, the materializer verifies the bytes it writes against the manifest digest while copying, and the manifest owner-id composite has one producer. | | Security | M001 authz/redaction/threat model | closed | `plans/closure/security-isolation-resource/001-status.md` | | Security | M002 Landlock | closed | `plans/closure/security-isolation-resource/002-status.md` | | Security | M002a `/dev/null` corrective | closed | `plans/closure/security-isolation-resource/002a-status.md` | @@ -173,7 +175,7 @@ The repository interrogation corrective batch is registered but is **not** depen | CodeGG M004 remote AgentRun worker | deferred | M003 is closed; only the stable AgentRun worker-entry contract remains outstanding | | Operations M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md`. Explicit `service-host --config` entry, shared shutdown+wait convergence, normal STOP does not create persistent drain, dedicated native Windows contract/SCM evidence, Eggup remains manager owner. Foundation M004 is already conditionally closed; the next immutable candidate should contain both for final M004 qualification. | | Control-plane M004 shared protocol contract corrective | **proposed** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. | -| Workspace M005a declared-artifact capture fail-closed corrective | **proposed** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`. | +| Workspace M005a declared-artifact capture fail-closed corrective | **implemented** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Implemented: the terminal result carries a first-class capture disposition (`ExecutionResult.artifact_capture`), the mapping from a capture attempt to the terminal facts is one public decision (`eggwork_server::decide_artifact_capture`), the platform's capture capability is one fact (`artifact::capture_capability`), the `artifact.declared.v1` advertisement follows that fact, and the capture failure is published on the server's existing event-publishing path as a diagnostic of class `artifact.capture.failed`. Closure record: `plans/closure/workspace-artifact-transport/005a-status.md`. | | Workspace M005b GC preview and store ownership corrective | **implemented** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass used different candidate predicates, in a module whose own doc comment states the two must be shared. Implemented: the candidate predicate, the metadata filenames, and the blob path layout each have one owner; the preview reaches owner code through a read-only, non-reconciling seam (`blob::preview_gc`, `workspace::preview_gc`, `artifact::preview_gc`); the materializer verifies the bytes it writes against the manifest digest **while copying** (`BlobStore::copy_verified`); and the manifest owner-id composite has one producer with two entry points. Closure record: `plans/closure/workspace-artifact-transport/005b-status.md`. | | Security M005a degraded-isolation observability corrective | **implemented** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` was emitted only from test code, so a degraded best-effort isolation or resource enforcement was invisible to an event-streaming caller. Implemented: the runner emits a bounded diagnostic through its output channel **before the target spawns**, the server forwards it as `ExecutionEventKind::Diagnostic`, and the diagnostic grammar is owned by `eggwork-core` so producer and server share one definition. The diagnostic precedes the target's first output and the terminal event, is durable in the journal, and is emitted exactly once per degradation. The `Required` path is untouched. Closure record: `plans/closure/security-isolation-resource/005a-status.md`. | | Security M005b sandbox-helper environment parity corrective | **implemented** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list was maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule had no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix is a shared artifact plus a pinning test, not a shared crate. **This was the most severe finding in the batch**, and it was live: the runner's launch-spec builder started from a fixed baseline and appended every non-denied caller key, and none of those baseline keys except `PATH` was denied. A caller that set `LANG` produced a launch specification with two `LANG` entries; the helper refused it with status 12; the runner read that as a pre-target setup failure and — for a **best-effort** request only — rewrote the sandbox outcome to `NotApplied` and **re-spawned the target directly with no Landlock ruleset at all**. Implemented: the environment policy now has one checked-in source of truth (`crates/eggwork-runner/policy/environment-policy.toml`), a deterministic generator (`scripts/generate_environment_policy.py`), and generated copies in each crate; one builder serves both the direct and the helper launch path; the runner drops denied keys and lets the node's value win for node-owned keys; the helper refuses a policy violation with its own status byte, **13**, distinct from the general specification-validation status 12. The `Required` path is untouched and still fails closed. Closure record: `plans/closure/security-isolation-resource/005b-status.md`. | @@ -220,7 +222,7 @@ Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 auth --> CodeGG worker telemetry consumer [UNBLOCKED; separately registered] Repository interrogation corrective batch [PROPOSED] --+--> Control-plane M004 shared protocol contract [IMPLEMENTED] - +--> Workspace M005a artifact capture fail-closed [PROPOSED] + +--> Workspace M005a artifact capture fail-closed [IMPLEMENTED] +--> Workspace M005b GC preview and store ownership [IMPLEMENTED] +--> Security M005a degraded-isolation observability [IMPLEMENTED] +--> Security M005b helper environment parity [IMPLEMENTED] diff --git a/plans/subsystems/workspace-artifact-transport-roadmap.md b/plans/subsystems/workspace-artifact-transport-roadmap.md index 51cf014..b10c60f 100644 --- a/plans/subsystems/workspace-artifact-transport-roadmap.md +++ b/plans/subsystems/workspace-artifact-transport-roadmap.md @@ -1,6 +1,6 @@ # Workspace and Artifact Transport Roadmap -Status: active roadmap; M001-M004 closed; M005a data-plane corrective proposed; M005b data-plane corrective implemented +Status: active roadmap; M001-M004 closed; M005a data-plane corrective implemented; M005b data-plane corrective implemented Canonical authority: @@ -136,7 +136,7 @@ Exit conditions: Class: invariant -Status: proposed +Status: implemented Corrective addendum: @@ -146,6 +146,10 @@ Implementation plan: - `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md` +Closure record: + +- `plans/closure/workspace-artifact-transport/005a-status.md` + Objective: Stop a shipped target from silently losing declared outputs. On a non-Unix target the safe artifact-capture open is refused, and the execution still reports `Succeeded` with a zero artifact count and a nested finalization-failure marker. An execution whose declared outputs could not be captured must not present as a successful execution with missing artifacts. @@ -157,6 +161,16 @@ Exit conditions: - the platform claim in the README and in the divergences table matches the code; - the required-isolation and fail-closed rules are unchanged. +Implemented: + +- the terminal result carries a first-class capture disposition, `ExecutionResult.artifact_capture` (`eggwork_core::ArtifactCaptureDisposition`), so the caller reads "did the declared outputs arrive" from the result instead of comparing an artifact count against a declared-output count it does not have; +- the mapping from a capture attempt to the terminal facts is one decision, `eggwork_server::decide_artifact_capture`, reachable from outside the crate: a declared output that was not captured never leaves the execution `Succeeded`, and the target's own failure is never overwritten by the node's; +- the platform's capture capability is one fact, `artifact::capture_capability`, stated next to the platform-specific `open_file_beneath` that can refuse a capture, and re-exported from the crate root as `artifact_capture_capability`; +- the `artifact.declared.v1` capability name is unchanged and its advertisement follows the fact: a node whose platform cannot capture does not advertise it; +- the capture failure is published on the server's existing event-publishing path as a diagnostic of class `artifact.capture.failed`, with the grammar, the bound, and the truncation rule in `architecture/protocol.md`; +- the capture-eligibility rule is unchanged: a cancelled, timed-out, interrupted, or output-limit-killed execution still captures nothing, and it reports its own terminal state; +- the terminal snapshot is not byte-identical across the change: the result gained a field, and a capture that did not complete no longer reports `Succeeded`. + ### M005b — GC preview and store ownership corrective Class: invariant From c0ccf68d834e202f315159f0a48dda79f1ee3830 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 17:22:46 +0000 Subject: [PATCH 09/37] docs(plans): record the Workspace M005a implementation commit Workspace M005a -> 4258964. --- plans/closure/workspace-artifact-transport/005a-status.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plans/closure/workspace-artifact-transport/005a-status.md b/plans/closure/workspace-artifact-transport/005a-status.md index dc3bed5..376b882 100644 --- a/plans/closure/workspace-artifact-transport/005a-status.md +++ b/plans/closure/workspace-artifact-transport/005a-status.md @@ -4,7 +4,7 @@ - Corrective addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` (wins over the plan where they disagree) - Implementation plan: `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md` - Roadmap entry: `plans/subsystems/workspace-artifact-transport-roadmap.md` (§ M005a, status **implemented**) -- Implementation commit: `IMPLEMENTATION-COMMIT-PENDING` +- Implementation commit: `4258964` - Closed on: 2026-10-23 (Linux x86_64 host) ## Finding @@ -285,7 +285,7 @@ The other non-vacuity arguments: ## Verification actually run All commands were run on this Linux x86_64 host against the working tree as it stands -(commit `IMPLEMENTATION-COMMIT-PENDING`). +(commit `4258964`). | Command | Result | | --- | --- | From 1f1b56cb4c9b60b610a2dc8ebb6ab4b87657fa39 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Fri, 23 Oct 2026 17:34:54 +0000 Subject: [PATCH 10/37] docs(plans): finish registering the five implemented milestones Control-plane M004 and the three M005 milestones were still carrying a stale 'proposed' status in the registry's workstream and planned-work rows after their implementation landed. The batch's execution-graph label now reads [PARTLY IMPLEMENTED], which is what the batch actually is: five implemented, four proposed, one blocked on ADR-0007. --- plans/registry.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/plans/registry.md b/plans/registry.md index 28a1a3a..a37f142 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -111,7 +111,7 @@ Two findings in this batch were deliberately **not** given a milestone, because | Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | | Control-plane protocol | M001-M004 closed; no milestone in flight | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept — **implemented**: `eggwork-core` now owns the control-plane schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification, and the runner owns the capability names it produces. No wire value, wire field, or capability byte changed. Closure record: `plans/closure/control-plane-protocol/004-status.md` | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | | Workspace / artifacts | M001-M004 closed; M005a and M005b correctives implemented | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) — **implemented**: a declared output that was not captured now ends the execution in a truthful non-success state with a first-class disposition and a diagnostic event, and a node whose platform cannot capture no longer advertises `artifact.declared.v1` — and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, `plans/closure/workspace-artifact-transport/005a-status.md`, `plans/closure/workspace-artifact-transport/005b-status.md` | -| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a implemented, M005b proposed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | +| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a and M005b implemented, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | | Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready; M008a/M008b proposed | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. A repository interrogation pass added M008a (five live metrics are never reported by the operator surface; one `active_executions` field name carries two meanings; every configuration fault collapses into one unhelpful message) and M008b (the release harness re-derives facts that already have an owner, and the design record's line citations and size figures are stale with no gate) | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md`, `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | @@ -174,7 +174,7 @@ The repository interrogation corrective batch is registered but is **not** depen | CodeGG M003 content-aware derived workspace transfer | closed downstream | Closed in CodeGG at `d51afe46` (implementation `1ce377ce`; hosted `36745285774` success, live derived reuse under required isolation) on Eggwork `e6a5d82`; closure record `dbowm91/codegg: plans/closure/eggwork-fixed-target-remote-execution/003-status.md` | | CodeGG M004 remote AgentRun worker | deferred | M003 is closed; only the stable AgentRun worker-entry contract remains outstanding | | Operations M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md`. Explicit `service-host --config` entry, shared shutdown+wait convergence, normal STOP does not create persistent drain, dedicated native Windows contract/SCM evidence, Eggup remains manager owner. Foundation M004 is already conditionally closed; the next immutable candidate should contain both for final M004 qualification. | -| Control-plane M004 shared protocol contract corrective | **proposed** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. | +| Control-plane M004 shared protocol contract corrective | **implemented** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. Implemented: `eggwork-core` owns the control-plane API schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification of `ExecutionState`; the runner owns the capability names it produces. The classification is an exhaustive match over all nine variants with no wildcard arm, so adding a tenth variant is a compile error in `eggwork-core` rather than a silent behaviour change downstream. No wire value, wire field, or capability byte changed. The ownership change is recorded in `plans/adrs/ADR-0008-core-protocol-contract-ownership.md`. Closure record: `plans/closure/control-plane-protocol/004-status.md`. | | Workspace M005a declared-artifact capture fail-closed corrective | **implemented** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Implemented: the terminal result carries a first-class capture disposition (`ExecutionResult.artifact_capture`), the mapping from a capture attempt to the terminal facts is one public decision (`eggwork_server::decide_artifact_capture`), the platform's capture capability is one fact (`artifact::capture_capability`), the `artifact.declared.v1` advertisement follows that fact, and the capture failure is published on the server's existing event-publishing path as a diagnostic of class `artifact.capture.failed`. Closure record: `plans/closure/workspace-artifact-transport/005a-status.md`. | | Workspace M005b GC preview and store ownership corrective | **implemented** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass used different candidate predicates, in a module whose own doc comment states the two must be shared. Implemented: the candidate predicate, the metadata filenames, and the blob path layout each have one owner; the preview reaches owner code through a read-only, non-reconciling seam (`blob::preview_gc`, `workspace::preview_gc`, `artifact::preview_gc`); the materializer verifies the bytes it writes against the manifest digest **while copying** (`BlobStore::copy_verified`); and the manifest owner-id composite has one producer with two entry points. Closure record: `plans/closure/workspace-artifact-transport/005b-status.md`. | | Security M005a degraded-isolation observability corrective | **implemented** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` was emitted only from test code, so a degraded best-effort isolation or resource enforcement was invisible to an event-streaming caller. Implemented: the runner emits a bounded diagnostic through its output channel **before the target spawns**, the server forwards it as `ExecutionEventKind::Diagnostic`, and the diagnostic grammar is owned by `eggwork-core` so producer and server share one definition. The diagnostic precedes the target's first output and the terminal event, is durable in the journal, and is emitted exactly once per degradation. The `Required` path is untouched. Closure record: `plans/closure/security-isolation-resource/005a-status.md`. | @@ -221,7 +221,7 @@ Operations release publication [HUMAN ACTION: §14] <----+--> public boot Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 authenticated API/client [CLOSED] --> CodeGG worker telemetry consumer [UNBLOCKED; separately registered] -Repository interrogation corrective batch [PROPOSED] --+--> Control-plane M004 shared protocol contract [IMPLEMENTED] +Repository interrogation corrective batch [PARTLY IMPLEMENTED] --+--> Control-plane M004 shared protocol contract [IMPLEMENTED] +--> Workspace M005a artifact capture fail-closed [IMPLEMENTED] +--> Workspace M005b GC preview and store ownership [IMPLEMENTED] +--> Security M005a degraded-isolation observability [IMPLEMENTED] From 275b070e917421bad1f8053a78eb9cbc9db013e9 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Sun, 25 Oct 2026 07:29:12 +0000 Subject: [PATCH 11/37] docs(plans): align the five milestones' status lines with their closure records The plan documents and closure records still read 'proposed' / 'implemented after the implementation landed, and the registry and roadmaps used a third word. One vocabulary now applies across all three surfaces, from plans/003-planning-process.md section 2. Three milestones are closed. Two are conditionally closed, and the distinction is the plan's own requirement rather than a judgement call: - Security M005a requires that a change to the runner's public OutputChunk type 'must also be exercised on the Windows and macOS targets the release matrix builds'. OutputChunk did change shape, and only Linux was exercised here. - Workspace M005a requires that the new portable test target 'compiles and passes on a non-unix host' and that the Windows hosted qualification asserts the truthful terminal disposition. The step and the wiring exist; neither has executed. Both name the outstanding evidence item in their closure record. Nothing is claimed about any platform that was not exercised. --- .../005a-status.md | 19 +++++++++- .../005b-status.md | 2 +- .../005a-status.md | 20 ++++++++++ .../005b-status.md | 2 + ...004-shared-protocol-contract-corrective.md | 4 +- ...aded-isolation-observability-corrective.md | 2 +- ...ox-helper-environment-parity-corrective.md | 2 +- ...artifact-capture-fail-closed-corrective.md | 2 +- ...-preview-and-store-ownership-corrective.md | 2 +- plans/registry.md | 37 ++++++++++--------- .../security-isolation-resource-roadmap.md | 6 +-- .../workspace-artifact-transport-roadmap.md | 6 +-- 12 files changed, 73 insertions(+), 31 deletions(-) diff --git a/plans/closure/security-isolation-resource/005a-status.md b/plans/closure/security-isolation-resource/005a-status.md index 5d32b65..9a3caa8 100644 --- a/plans/closure/security-isolation-resource/005a-status.md +++ b/plans/closure/security-isolation-resource/005a-status.md @@ -1,6 +1,6 @@ # Security M005a — Degraded-isolation observability corrective -Status: implemented — closure record written, implementation commit pending +Status: conditionally closed — implementation commit `6f41957`; the outstanding evidence item is the Windows and macOS exercise of the runner's `OutputChunk` shape change, which the plan requires and this host cannot provide Source implementation plan: `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md` @@ -453,3 +453,20 @@ separate, still-open item that this milestone neither closes nor worsens. - `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`: **not edited** — the plan is not in this milestone's ownership and is left as the authoritative statement of what was asked. + +## Outstanding evidence item (why this is conditionally closed) + +The implementation is complete and every acceptance criterion is met on the +Linux host, but one criterion requires evidence this host cannot produce: + +- the plan requires that a change to the runner's public `OutputChunk` type + "must also be exercised on the Windows and macOS targets the release matrix + builds, because the runner has platform-specific spawn paths and the + diagnostic sits in front of all of them." + +`OutputChunk` did change shape (struct to enum, carrying a `Diagnostic` +variant), so that requirement applies. Only Linux x86_64 was exercised here. +Nothing about the implementation is unfinished; what is missing is a run on +two platforms, and the milestone stays **conditionally closed** until the +`windows-runner` CI job and the macOS release job have run. The claim that is +*not* made is that any platform has been qualified. diff --git a/plans/closure/security-isolation-resource/005b-status.md b/plans/closure/security-isolation-resource/005b-status.md index 637a4bd..442af01 100644 --- a/plans/closure/security-isolation-resource/005b-status.md +++ b/plans/closure/security-isolation-resource/005b-status.md @@ -1,6 +1,6 @@ # Security M005b — Sandbox-helper environment parity corrective -Status: implemented — closure record written, implementation commit pending +Status: closed — implementation commit `63699df` Source implementation plan: `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md` diff --git a/plans/closure/workspace-artifact-transport/005a-status.md b/plans/closure/workspace-artifact-transport/005a-status.md index 376b882..89ed2d2 100644 --- a/plans/closure/workspace-artifact-transport/005a-status.md +++ b/plans/closure/workspace-artifact-transport/005a-status.md @@ -1,5 +1,7 @@ # Workspace and Artifact Transport M005a Closure — Declared-artifact capture fail-closed corrective +Status: conditionally closed — implementation commit `4258964`; the outstanding evidence item is the execution of the new portable test target on a non-unix host and of the hosted Windows qualification, both of which the plan requires and this host cannot provide + - Milestone: **M005a — Declared-artifact capture fail-closed corrective** - Corrective addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` (wins over the plan where they disagree) - Implementation plan: `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md` @@ -411,6 +413,24 @@ one-line placeholder (see *Deviations from the plan*). path and two suites writing one file would leave whichever ran last as the only evidence. +## Outstanding evidence item (why this is conditionally closed) + +The implementation is complete and every acceptance criterion's code and wiring +half is met on the Linux host, but two criteria require evidence this host +cannot produce: + +- acceptance criterion 7 requires that the new portable test target + "compiles and passes on a non-unix host", and it is wired into the + `windows-runner` CI job; +- acceptance criterion 8 requires that the Windows hosted qualification + declares an output and asserts the truthful terminal disposition. + +The step and the wiring both exist; neither has executed, because this host is +Linux x86_64 and the hosted qualification is tag-gated. The milestone stays +**conditionally closed** until the `windows-runner` job and the hosted +qualification have run. The claim that is *not* made is that Windows has been +qualified. + ## Unresolved findings by severity | # | Severity | Finding | Owner | diff --git a/plans/closure/workspace-artifact-transport/005b-status.md b/plans/closure/workspace-artifact-transport/005b-status.md index 76bfbfe..228b175 100644 --- a/plans/closure/workspace-artifact-transport/005b-status.md +++ b/plans/closure/workspace-artifact-transport/005b-status.md @@ -1,5 +1,7 @@ # Workspace and Artifact Transport M005b Closure — GC Preview and Store Ownership Corrective +Status: closed — implementation commit `63699df` + Source plan: `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md` Corrective addendum: `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` Subsystem roadmap: `plans/subsystems/workspace-artifact-transport-roadmap.md` diff --git a/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md b/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md index 3f593bd..d88d5db 100644 --- a/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md +++ b/plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md @@ -1,9 +1,11 @@ # Control Plane M004 — Shared Protocol Contract Ownership -Status: proposed +Status: closed Class: invariant +Closure record: `plans/closure/control-plane-protocol/004-status.md` + Source roadmap: - `plans/subsystems/control-plane-protocol-roadmap.md` diff --git a/plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md b/plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md index 4111593..6d236c4 100644 --- a/plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md +++ b/plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md @@ -1,6 +1,6 @@ # Security M005a — Degraded isolation observability corrective -Status: proposed +Status: conditionally closed Closure record: `plans/closure/security-isolation-resource/005a-status.md` diff --git a/plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md b/plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md index 216a487..d92a93d 100644 --- a/plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md +++ b/plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md @@ -1,6 +1,6 @@ # Security M005b — Sandbox-helper environment parity corrective -Status: proposed +Status: closed Closure record: `plans/closure/security-isolation-resource/005b-status.md` diff --git a/plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md b/plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md index 79417f3..4052b0f 100644 --- a/plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md +++ b/plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md @@ -1,6 +1,6 @@ # Workspace and Artifact Transport M005a — Declared-artifact capture fails closed -Status: proposed +Status: conditionally closed Class: invariant diff --git a/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md b/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md index 2a6f744..92d1c4b 100644 --- a/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md +++ b/plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md @@ -1,6 +1,6 @@ # Workspace and Artifact Transport M005b — GC preview/apply parity and store-owned formats -Status: proposed +Status: closed Class: invariant diff --git a/plans/registry.md b/plans/registry.md index a37f142..4179740 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -90,9 +90,9 @@ A repository-wide code interrogation pass over the reviewed baseline found no `t | Addendum | Milestones | Class | Status | |---|---|---|---| -| `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | implemented | -| `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a implemented; M005b implemented | -| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a/M005b implemented; **M005c blocked on ADR-0007** | +| `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | closed | +| `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a conditionally closed; M005b closed | +| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a conditionally closed; M005b closed; **M005c blocked on ADR-0007** | | `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | | `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | proposed | @@ -110,8 +110,8 @@ Two findings in this batch were deliberately **not** given a milestone, because | Optional Gregg host telemetry | **closed; M001 and M002 both closed** | M001 closed the default-off loopback Gregg adapter, normalized cache and single polling owner (`plans/closure/optional-gregg-host-telemetry/001-status.md`, implementation `ac55985`); M002 closed the authorized node telemetry API/client behind a narrow `telemetry` grant (`plans/closure/optional-gregg-host-telemetry/002-status.md`, implementation `5ccb1e6`). The frozen contract is `eggwork_core::NodeTelemetry` schema version 1. No Gregg changes, no Eggwork scheduling, no capability feature added. The CodeGG worker-telemetry consumer is unblocked. | `plans/subsystems/optional-gregg-host-telemetry-roadmap.md`, `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` | | Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | | Control-plane protocol | M001-M004 closed; no milestone in flight | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept — **implemented**: `eggwork-core` now owns the control-plane schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification, and the runner owns the capability names it produces. No wire value, wire field, or capability byte changed. Closure record: `plans/closure/control-plane-protocol/004-status.md` | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | -| Workspace / artifacts | M001-M004 closed; M005a and M005b correctives implemented | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) — **implemented**: a declared output that was not captured now ends the execution in a truthful non-success state with a first-class disposition and a diagnostic event, and a node whose platform cannot capture no longer advertises `artifact.declared.v1` — and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, `plans/closure/workspace-artifact-transport/005a-status.md`, `plans/closure/workspace-artifact-transport/005b-status.md` | -| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a and M005b implemented, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | +| Workspace / artifacts | M001-M004 closed; M005a conditionally closed, M005b closed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) — **implemented**: a declared output that was not captured now ends the execution in a truthful non-success state with a first-class disposition and a diagnostic event, and a node whose platform cannot capture no longer advertises `artifact.declared.v1` — and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, `plans/closure/workspace-artifact-transport/005a-status.md`, `plans/closure/workspace-artifact-transport/005b-status.md` | +| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a conditionally closed, M005b closed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | | Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready; M008a/M008b proposed | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. A repository interrogation pass added M008a (five live metrics are never reported by the operator surface; one `active_executions` field name carries two meanings; every configuration fault collapses into one unhelpful message) and M008b (the release harness re-derives facts that already have an owner, and the design record's line citations and size figures are stale with no gate) | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md`, `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | @@ -142,15 +142,16 @@ The repository interrogation corrective batch is registered but is **not** depen | Workspace | M002 materialization | closed | `plans/closure/workspace-artifact-transport/002-status.md` | | Workspace | M003 artifacts/retention/GC | closed | `plans/closure/workspace-artifact-transport/003-status.md` | | Workspace | M004 reusable manifest CAS + derived materialization | closed | `plans/closure/workspace-artifact-transport/004-status.md`; consumed by closed downstream CodeGG M003 | -| Workspace | M005a declared-artifact capture fail-closed | implemented | `plans/closure/workspace-artifact-transport/005a-status.md` — a declared output that was not captured now ends the execution in a truthful non-success state with a first-class capture disposition, and a node whose platform cannot capture does not advertise `artifact.declared.v1`. The platform limitation itself remains: declared artifacts are captured on a Unix platform only. | -| Workspace | M005b GC preview and store ownership | implemented | `plans/closure/workspace-artifact-transport/005b-status.md` — the operator's GC preview and the apply pass now select candidates through the same store-owned statement, the store's path layout and metadata filenames have one owner, the materializer verifies the bytes it writes against the manifest digest while copying, and the manifest owner-id composite has one producer. | +| Workspace | M005a declared-artifact capture fail-closed | conditionally closed | `plans/closure/workspace-artifact-transport/005a-status.md` — a declared output that was not captured now ends the execution in a truthful non-success state with a first-class capture disposition, and a node whose platform cannot capture does not advertise `artifact.declared.v1`. The platform limitation itself remains: declared artifacts are captured on a Unix platform only. | +| Workspace | M005b GC preview and store ownership | closed | `plans/closure/workspace-artifact-transport/005b-status.md` — the operator's GC preview and the apply pass now select candidates through the same store-owned statement, the store's path layout and metadata filenames have one owner, the materializer verifies the bytes it writes against the manifest digest while copying, and the manifest owner-id composite has one producer. | | Security | M001 authz/redaction/threat model | closed | `plans/closure/security-isolation-resource/001-status.md` | | Security | M002 Landlock | closed | `plans/closure/security-isolation-resource/002-status.md` | | Security | M002a `/dev/null` corrective | closed | `plans/closure/security-isolation-resource/002a-status.md` | | Security | M003 resource enforcement | qualified/closed | `plans/closure/security-isolation-resource/003-status.md` | | Security | M004 adversarial + cross-platform closure | closed | `plans/closure/security-isolation-resource/004-status.md` (implementation `283f3ea`, incl. null-device write hardening fix); platform claims limited to hosted Linux with macOS/Windows fail-closed by construction | | Security corrective | C001 remote enforcement admission + capability truthfulness | closed | `plans/closure/security-isolation-resource-remote-admission-corrective/001-status.md` | -| Security corrective | M005a degraded-isolation observability | implemented | `plans/closure/security-isolation-resource/005a-status.md` — a degraded best-effort request now produces a bounded diagnostic event published before the target's first output and before the terminal event; the diagnostic grammar is owned by `eggwork-core`. The runner's public `OutputChunk` became an enum carrying a `Diagnostic` variant, which is release-visible. | +| Security corrective | M005a degraded-isolation observability | conditionally closed | `plans/closure/security-isolation-resource/005a-status.md` — a degraded best-effort request now produces a bounded diagnostic event published before the target's first output and before the terminal event; the diagnostic grammar is owned by `eggwork-core`. The runner's public `OutputChunk` became an enum carrying a `Diagnostic` variant, which is release-visible. | +| Security corrective | M005b sandbox-helper environment parity | closed | `plans/closure/security-isolation-resource/005b-status.md` — the environment policy has one owner, a deterministic generator, and generated copies pinned by a behavioural parity test; a caller-supplied node-owned key can no longer produce a duplicate launch-specification key and cause a best-effort execution to lose its confinement. | | Optional Gregg telemetry | M001 default-off loopback adapter/cache | closed | `plans/closure/optional-gregg-host-telemetry/001-status.md` (implementation `ac55985`) | | Optional Gregg telemetry | M002 authenticated node telemetry API/client | closed | `plans/closure/optional-gregg-host-telemetry/002-status.md` (implementation `5ccb1e6`); frozen contract `eggwork_core::NodeTelemetry` schema version 1, narrow `telemetry` grant, `NodeClient::telemetry`/`telemetry_for` | | Operations | M001 node operations | closed | `plans/closure/operations-distribution/001-status.md` | @@ -174,11 +175,11 @@ The repository interrogation corrective batch is registered but is **not** depen | CodeGG M003 content-aware derived workspace transfer | closed downstream | Closed in CodeGG at `d51afe46` (implementation `1ce377ce`; hosted `36745285774` success, live derived reuse under required isolation) on Eggwork `e6a5d82`; closure record `dbowm91/codegg: plans/closure/eggwork-fixed-target-remote-execution/003-status.md` | | CodeGG M004 remote AgentRun worker | deferred | M003 is closed; only the stable AgentRun worker-entry contract remains outstanding | | Operations M007 Windows service host | **ready** | `plans/implementation/operations-distribution/007-windows-service-host.md`. Explicit `service-host --config` entry, shared shutdown+wait convergence, normal STOP does not create persistent drain, dedicated native Windows contract/SCM evidence, Eggup remains manager owner. Foundation M004 is already conditionally closed; the next immutable candidate should contain both for final M004 qualification. | -| Control-plane M004 shared protocol contract corrective | **implemented** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. Implemented: `eggwork-core` owns the control-plane API schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification of `ExecutionState`; the runner owns the capability names it produces. The classification is an exhaustive match over all nine variants with no wildcard arm, so adding a tenth variant is a compile error in `eggwork-core` rather than a silent behaviour change downstream. No wire value, wire field, or capability byte changed. The ownership change is recorded in `plans/adrs/ADR-0008-core-protocol-contract-ownership.md`. Closure record: `plans/closure/control-plane-protocol/004-status.md`. | -| Workspace M005a declared-artifact capture fail-closed corrective | **implemented** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Implemented: the terminal result carries a first-class capture disposition (`ExecutionResult.artifact_capture`), the mapping from a capture attempt to the terminal facts is one public decision (`eggwork_server::decide_artifact_capture`), the platform's capture capability is one fact (`artifact::capture_capability`), the `artifact.declared.v1` advertisement follows that fact, and the capture failure is published on the server's existing event-publishing path as a diagnostic of class `artifact.capture.failed`. Closure record: `plans/closure/workspace-artifact-transport/005a-status.md`. | -| Workspace M005b GC preview and store ownership corrective | **implemented** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass used different candidate predicates, in a module whose own doc comment states the two must be shared. Implemented: the candidate predicate, the metadata filenames, and the blob path layout each have one owner; the preview reaches owner code through a read-only, non-reconciling seam (`blob::preview_gc`, `workspace::preview_gc`, `artifact::preview_gc`); the materializer verifies the bytes it writes against the manifest digest **while copying** (`BlobStore::copy_verified`); and the manifest owner-id composite has one producer with two entry points. Closure record: `plans/closure/workspace-artifact-transport/005b-status.md`. | -| Security M005a degraded-isolation observability corrective | **implemented** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` was emitted only from test code, so a degraded best-effort isolation or resource enforcement was invisible to an event-streaming caller. Implemented: the runner emits a bounded diagnostic through its output channel **before the target spawns**, the server forwards it as `ExecutionEventKind::Diagnostic`, and the diagnostic grammar is owned by `eggwork-core` so producer and server share one definition. The diagnostic precedes the target's first output and the terminal event, is durable in the journal, and is emitted exactly once per degradation. The `Required` path is untouched. Closure record: `plans/closure/security-isolation-resource/005a-status.md`. | -| Security M005b sandbox-helper environment parity corrective | **implemented** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list was maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule had no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix is a shared artifact plus a pinning test, not a shared crate. **This was the most severe finding in the batch**, and it was live: the runner's launch-spec builder started from a fixed baseline and appended every non-denied caller key, and none of those baseline keys except `PATH` was denied. A caller that set `LANG` produced a launch specification with two `LANG` entries; the helper refused it with status 12; the runner read that as a pre-target setup failure and — for a **best-effort** request only — rewrote the sandbox outcome to `NotApplied` and **re-spawned the target directly with no Landlock ruleset at all**. Implemented: the environment policy now has one checked-in source of truth (`crates/eggwork-runner/policy/environment-policy.toml`), a deterministic generator (`scripts/generate_environment_policy.py`), and generated copies in each crate; one builder serves both the direct and the helper launch path; the runner drops denied keys and lets the node's value win for node-owned keys; the helper refuses a policy violation with its own status byte, **13**, distinct from the general specification-validation status 12. The `Required` path is untouched and still fails closed. Closure record: `plans/closure/security-isolation-resource/005b-status.md`. | +| Control-plane M004 shared protocol contract corrective | **closed** | `plans/implementation/control-plane-protocol/004-shared-protocol-contract-corrective.md`. `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it. The capability feature names are re-typed: the server hardcodes the three `resources.cgroups-v2.*` names that the runner produces, and the client hardcodes `exec.argv.v1` that the server also hardcodes; the runner pushes the Landlock name as a literal while the constant that names it exists beside it. The terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept. Addendum: `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md`. Independent of M007. Implemented: `eggwork-core` owns the control-plane API schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification of `ExecutionState`; the runner owns the capability names it produces. The classification is an exhaustive match over all nine variants with no wildcard arm, so adding a tenth variant is a compile error in `eggwork-core` rather than a silent behaviour change downstream. No wire value, wire field, or capability byte changed. The ownership change is recorded in `plans/adrs/ADR-0008-core-protocol-contract-ownership.md`. Closure record: `plans/closure/control-plane-protocol/004-status.md`. | +| Workspace M005a declared-artifact capture fail-closed corrective | **conditionally closed** | `plans/implementation/workspace-artifact-transport/005a-declared-artifact-capture-fail-closed-corrective.md`. On a non-Unix target, declared-artifact capture is refused with a nested `finalization_failure` marker while the execution still reports `Succeeded` with zero artifacts — a shipped target silently loses half the data plane. Two facts sharpen this: the static capability list advertises `artifact.declared.v1` on every platform, so a node advertises a capability it refuses; and the "capture failure does not change the terminal state" behavior is currently *asserted by a test* on the missing-declared-file path, so the corrective must decide whether the platform-refusal case follows that same contract or instead fails closed, and revise the test deliberately rather than incidentally. Not recorded in the divergences table. Implemented: the terminal result carries a first-class capture disposition (`ExecutionResult.artifact_capture`), the mapping from a capture attempt to the terminal facts is one public decision (`eggwork_server::decide_artifact_capture`), the platform's capture capability is one fact (`artifact::capture_capability`), the `artifact.declared.v1` advertisement follows that fact, and the capture failure is published on the server's existing event-publishing path as a diagnostic of class `artifact.capture.failed`. Closure record: `plans/closure/workspace-artifact-transport/005a-status.md`. | +| Workspace M005b GC preview and store ownership corrective | **closed** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass used different candidate predicates, in a module whose own doc comment states the two must be shared. Implemented: the candidate predicate, the metadata filenames, and the blob path layout each have one owner; the preview reaches owner code through a read-only, non-reconciling seam (`blob::preview_gc`, `workspace::preview_gc`, `artifact::preview_gc`); the materializer verifies the bytes it writes against the manifest digest **while copying** (`BlobStore::copy_verified`); and the manifest owner-id composite has one producer with two entry points. Closure record: `plans/closure/workspace-artifact-transport/005b-status.md`. | +| Security M005a degraded-isolation observability corrective | **conditionally closed** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` was emitted only from test code, so a degraded best-effort isolation or resource enforcement was invisible to an event-streaming caller. Implemented: the runner emits a bounded diagnostic through its output channel **before the target spawns**, the server forwards it as `ExecutionEventKind::Diagnostic`, and the diagnostic grammar is owned by `eggwork-core` so producer and server share one definition. The diagnostic precedes the target's first output and the terminal event, is durable in the journal, and is emitted exactly once per degradation. The `Required` path is untouched. Closure record: `plans/closure/security-isolation-resource/005a-status.md`. | +| Security M005b sandbox-helper environment parity corrective | **closed** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list was maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule had no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix is a shared artifact plus a pinning test, not a shared crate. **This was the most severe finding in the batch**, and it was live: the runner's launch-spec builder started from a fixed baseline and appended every non-denied caller key, and none of those baseline keys except `PATH` was denied. A caller that set `LANG` produced a launch specification with two `LANG` entries; the helper refused it with status 12; the runner read that as a pre-target setup failure and — for a **best-effort** request only — rewrote the sandbox outcome to `NotApplied` and **re-spawned the target directly with no Landlock ruleset at all**. Implemented: the environment policy now has one checked-in source of truth (`crates/eggwork-runner/policy/environment-policy.toml`), a deterministic generator (`scripts/generate_environment_policy.py`), and generated copies in each crate; one builder serves both the direct and the helper launch path; the runner drops denied keys and lets the node's value win for node-owned keys; the helper refuses a policy violation with its own status byte, **13**, distinct from the general specification-validation status 12. The `Required` path is untouched and still fails closed. Closure record: `plans/closure/security-isolation-resource/005b-status.md`. | | Security M005c resource-scoped authorization corrective | **blocked** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. Blocked on ADR-0007 (`plans/adrs/ADR-0007-resource-scoped-authorization.md`, **proposed, not accepted**), which must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. The gap itself is already recorded as divergence #4; this is a decision about a known gap, not a new defect. | | Operations M008a operator surface truthfulness corrective | **proposed** | `plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md`. Five live metrics are incremented by the server and never reported by `eggworkd status`/`eggworkd metrics`; one `active_executions` field name carries two different meanings across the API and the CLI; and every configuration fault collapses into the single unhelpful message `configuration is invalid or unreadable`. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | | Operations M008b release harness and documentation single-sourcing corrective | **proposed** | `plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md`. The release harness re-derives the workspace version, the release asset inventory, the install identities, and the target classification that already have owners; the tag guard's own docstring deliberately keeps it out of CI, so the defect is the divergent parser and the absence of any automated exercise, not the missing CI wiring. Roughly 92% of the design record's line-number citations no longer point at the symbol they claim, every crate size figure in `architecture/overview.md` is stale, and divergence #20 now describes a fixed issue as open. CI type-checks feature-gated code it never executes — the qualification workflow is `workflow_dispatch`-only, so the suite runs on no ordinary pull request, and adding `--all-features` would not close the gap because those tests are `#[ignore]`d — while one runner test passes with zero assertions on the normal CI path. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | @@ -221,11 +222,11 @@ Operations release publication [HUMAN ACTION: §14] <----+--> public boot Optional Gregg M001 loopback adapter/cache [CLOSED] --> Optional Gregg M002 authenticated API/client [CLOSED] --> CodeGG worker telemetry consumer [UNBLOCKED; separately registered] -Repository interrogation corrective batch [PARTLY IMPLEMENTED] --+--> Control-plane M004 shared protocol contract [IMPLEMENTED] - +--> Workspace M005a artifact capture fail-closed [IMPLEMENTED] - +--> Workspace M005b GC preview and store ownership [IMPLEMENTED] - +--> Security M005a degraded-isolation observability [IMPLEMENTED] - +--> Security M005b helper environment parity [IMPLEMENTED] +Repository interrogation corrective batch [PARTLY IMPLEMENTED] --+--> Control-plane M004 shared protocol contract [CLOSED] + +--> Workspace M005a artifact capture fail-closed [CONDITIONALLY CLOSED] + +--> Workspace M005b GC preview and store ownership [CLOSED] + +--> Security M005a degraded-isolation observability [CONDITIONALLY CLOSED] + +--> Security M005b helper environment parity [CLOSED] +--> Security M005c resource-scoped authorization [BLOCKED on ADR-0007] +--> Operations M008a operator surface truthfulness [PROPOSED] +--> Operations M008b release harness and docs single-sourcing [PROPOSED] diff --git a/plans/subsystems/security-isolation-resource-roadmap.md b/plans/subsystems/security-isolation-resource-roadmap.md index 920b257..a376839 100644 --- a/plans/subsystems/security-isolation-resource-roadmap.md +++ b/plans/subsystems/security-isolation-resource-roadmap.md @@ -1,6 +1,6 @@ # Security, Isolation, and Resource Enforcement Roadmap -Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a and M005b implemented (closure records written, implementation commits pending); M005c blocked on ADR-0007 +Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a conditionally closed, M005b closed, M005c blocked on ADR-0007 Canonical authority: @@ -154,7 +154,7 @@ Run hostile input/process/workspace/transport fixtures, audit dependencies and u Class: invariant -Status: implemented — closure record written, implementation commit pending +Status: conditionally closed — implementation commit `6f41957`; the outstanding evidence item is the Windows and macOS exercise of the runner's `OutputChunk` shape change Closure evidence: `plans/closure/security-isolation-resource/005a-status.md` (implementation `6f41957`) @@ -182,7 +182,7 @@ Exit conditions: Class: invariant -Status: implemented — closure record written, implementation commit pending +Status: closed — implementation commit `63699df` Closure evidence: `plans/closure/security-isolation-resource/005b-status.md` (implementation `63699df`) diff --git a/plans/subsystems/workspace-artifact-transport-roadmap.md b/plans/subsystems/workspace-artifact-transport-roadmap.md index b10c60f..7c659c2 100644 --- a/plans/subsystems/workspace-artifact-transport-roadmap.md +++ b/plans/subsystems/workspace-artifact-transport-roadmap.md @@ -1,6 +1,6 @@ # Workspace and Artifact Transport Roadmap -Status: active roadmap; M001-M004 closed; M005a data-plane corrective implemented; M005b data-plane corrective implemented +Status: active roadmap; M001-M004 closed; M005a data-plane corrective conditionally closed; M005b data-plane corrective closed Canonical authority: @@ -136,7 +136,7 @@ Exit conditions: Class: invariant -Status: implemented +Status: conditionally closed — implementation commit `4258964`; the outstanding evidence item is the execution of the portable test target on a non-unix host and of the hosted Windows qualification Corrective addendum: @@ -175,7 +175,7 @@ Implemented: Class: invariant -Status: implemented +Status: closed — implementation commit `63699df` Corrective addendum: From af5a21709573e20f26eca77df83bd5560c46e936 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Sun, 25 Oct 2026 07:36:17 +0000 Subject: [PATCH 12/37] =?UTF-8?q?docs(plans):=20accept=20ADR-0007=20?= =?UTF-8?q?=E2=80=94=20implement=20resource-scoped=20grants?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Option A. The node gains a real per-resource authorization boundary instead of keeping an inert hook that only looks available. - GrantAuthorizer implements Authorizer::authorize_request so the typed ResourceId is consulted; ClientGrant gains an optional, additive, bounded resource-scope list. - The store's principal_id fences stay authoritative for Execution, Workspace and Artifact: the authorizer narrows, never widens. Blob has no owner, so a blob scope is an explicit digest list. - The scope applies to every operation whose resource is already resolved, including the five that resource_for_path resolves for dispatch. - Every configuration error class is refused at load time; the node refuses to start rather than degrade to a permissive decision. - No wire value, wire field, capability byte, or API_SCHEMA_VERSION changes. Unblocks Security M005c, which implements Branch A of its implementation plan. --- .../ADR-0007-resource-scoped-authorization.md | 65 +++++++++++++++++-- plans/registry.md | 2 +- 2 files changed, 59 insertions(+), 8 deletions(-) diff --git a/plans/adrs/ADR-0007-resource-scoped-authorization.md b/plans/adrs/ADR-0007-resource-scoped-authorization.md index 4a72d20..85fa9ff 100644 --- a/plans/adrs/ADR-0007-resource-scoped-authorization.md +++ b/plans/adrs/ADR-0007-resource-scoped-authorization.md @@ -1,9 +1,13 @@ # ADR-0007: Resource-Scoped Authorization — Implement the Boundary or Remove the Hook -Status: proposed — **not yet accepted**. This ADR records a decision that has not been made. No implementation work may be handed off on the strength of this document. +Status: accepted Date: 2026-10-23 +Decision: **Option A — implement resource-scoped grants.** The node gains a real per-resource authorization boundary. `GrantAuthorizer` implements the existing `Authorizer::authorize_request` hook so the typed `ResourceId` is consulted; `ClientGrant` gains an optional, additive, bounded resource-scope list; the store's `principal_id` fences remain authoritative for ownership and the authorizer may narrow, never widen; blobs are governed by an explicit digest list because content-addressed blob storage has no owner to fence against. No wire value, wire field, capability byte, or `API_SCHEMA_VERSION` changes. + +Decision date: 2026-10-25 + Decision owners: project maintainers Related authority: @@ -15,7 +19,7 @@ Related authority: - `plans/security/threat-model.md` - `architecture/overview.md` — divergence #4 - `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` — finding SI-3 -- `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` — the implementation plan, **blocked** on this ADR +- `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` — the implementation plan this decision authorises (Branch A) - `plans/003-planning-process.md` §4 (dependency discipline) and §8 (architecture changes) ## Context @@ -152,13 +156,60 @@ The review must also confirm that the chosen option does not move Eggwork toward ## Decision -**Not yet made.** This ADR is `proposed`. +**Option A — implement resource-scoped grants.** Accepted on 2026-10-25. + +The node gains a real per-resource authorization boundary. The hook that is already built and publicly exported becomes live instead of inert, the threat model's open boundary can be closed with evidence rather than with a caveat, and the published API of `eggwork-server` is not broken. + +The constraints that apply to this decision are these, and they bind the implementation. + +### 1. The scope is additive and never widens an operation grant + +`ClientGrant` gains an optional resource-scope list. A grant without scopes keeps exactly today's operation-level meaning, so an existing deployment's behaviour is unchanged. A scope names the **operation** it applies to, the **resource kind**, and the **resource identifier**; a scope can only narrow an operation the grant already holds, and a scope for an operation the grant does not hold is a configuration error. The identifier is the string form of the corresponding `ResourceId` variant and is parsed back into the typed variant (`ExecutionId::new`, `BlobDigest::parse`, `WorkspaceId::new`, `ArtifactId::new`), so the configuration and the wire path agree on what an identifier is. + +### 2. The store remains authoritative for ownership + +For `Execution`, `Workspace`, and `Artifact` the store's existing `principal_id` fences stay authoritative: `ExecutionStore::load_snapshot_for_principal`, the artifact store's `load`, and the workspace store's `lookup_manifest` continue to select by owner. The authorizer's resource-scoped decision is consistent with that ownership and may only narrow it. A resource-scoped grant must never be usable to reach a resource owned by another principal, even if the grant list is misconfigured. + +For `Blob` there is no owner — blob storage is content-addressed and shared — so a blob scope is an **explicit digest list** and never an ownership comparison. This is the boundary `plans/security/threat-model.md` names. + +### 3. The scope applies to every operation whose resource is already resolved + +The scope applies to the operations the existing call sites already name — `BlobRead`/`Blob`, `BlobWrite`/`Blob`, `WorkspaceCreate`/`Workspace`, `Execute`/`Execution`, `Execute`/`Workspace` — **and** to the operations `resource_for_path` already resolves for `dispatch`: `Observe`, `Cancel`, `Renew`, `Events`, and `ArtifactRead`. Scoping the handler-level call sites while leaving `dispatch` unscoped would produce an inconsistent boundary, and `dispatch` already constructs the resource. + +### 4. The decision rule is bounded and in-memory + +The operation grant must be present; when a scope is configured for that operation and resource kind the resource must be within the granted set; when no scope is configured for that operation and resource kind, and when the request carries no resource, the decision falls back to the operation-level grant. The decision consults a configuration-derived set only. It must not require the authorizer to consult the store in a way that introduces a lock or an ordering dependency that authorization does not have today. + +### 5. The configuration fails closed, and is bounded + +Every configuration error class is refused at load time, before the node accepts traffic, and the node refuses to start rather than degrade to a permissive decision: an unknown operation name, an unknown resource kind, a malformed identifier, a scope for an unheld operation, a duplicate scope, and an over-cap grant count. The scope list is bounded by a per-grant cap and a per-node cap on the total number of resource-scoped grants, validated in `OperatorConfig::validate` alongside the existing caps. `ClientGrant` remains `#[serde(deny_unknown_fields)]`, so a typo in a scope is a refusal rather than a silently absent scope. + +### 6. A denial is indistinguishable from any other denial + +Authorization still strictly precedes resource resolution in `dispatch`. A resource-scoped denial must be indistinguishable from an operation-level denial and from a missing resource, in both status code and response body. The store's existing ownership fences must not be weakened. + +### 7. No wire change, and no new authority + +No request or response wire shape changes, so `API_SCHEMA_VERSION` is unchanged and no coordination with the control-plane shared-protocol contract corrective is required. The change is additive at the wire and API level. It introduces no policy language, no rule engine, no role system, and no multi-tenant IAM: a scope is a name, a kind, and an identifier, and it can only narrow an existing per-principal grant. + +### 8. The `deny_unknown_fields` refusal is deliberate + +An **older** node reading a **newer** configuration that contains a resource scope will refuse to start, because `ClientGrant` denies unknown fields. That refusal is correct — a node must not silently ignore a scope it does not understand — and it is documented as a configuration-compatibility note rather than treated as a defect. + +### 9. Alternatives not selected, and why + +Option B (remove the hook and its plumbing) was not selected: it is a breaking removal from the public API of a published workspace crate, and it would leave the blob boundary open while removing the only mechanism that could close it. Option C (defer and mark the mechanism unavailable) was not selected: it is a deferral, not a decision, and it does not satisfy the truthfulness driver that this ADR exists to satisfy — the mechanism would still *look* like a working resource-scoped hook to a reader of the code. + +### 10. The architecture review's confirmation + +This decision class requires architecture review, and this ADR is that review's vehicle. The review confirms that the chosen option does **not** move Eggwork toward owning policy, roles, or a multi-tenant IAM product — a scope narrows one existing operation grant and does nothing else — and that it does **not** weaken the store's ownership fences, which remain authoritative and become the backstop behind the authorizer's decision. + +### 11. Documentation that must follow the decision + +The implementation milestone must update, in this order of authority: `architecture/overview.md`'s divergences table (divergence #4), `plans/security/threat-model.md`'s remaining-boundary column for the "Authenticated unauthorized principal" row, `architecture/server-node.md`, `architecture/operations-cli.md`, and `examples/eggworkd.example.json`. The divergences row must state what now enforces the boundary and what residual boundary remains; it must not describe the blob boundary as closed. -When the decision is made, this section is completed with the selected option, the decision date, and the constraints that apply to it, and the `Status:` line above is changed from `proposed` to `accepted`. Until then: +The implementation plan is `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`, whose §5 (Branch A) is the work this decision authorises. -- `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` remains `blocked`, with this ADR named as its concrete blocker; -- per `plans/003-planning-process.md` §4, that plan must not be handed off as ready merely because adjacent implementation exists; -- the implementation plan's Branch A (§5) and Branch B (§6) are written to be executable without re-deriving the design, so that whichever option is selected, the implementation is mechanical. ## Supersession diff --git a/plans/registry.md b/plans/registry.md index 4179740..a8cb385 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -21,7 +21,7 @@ Follow-up accepted ADR: `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` ( Follow-up accepted ADR: `plans/adrs/ADR-0008-core-protocol-contract-ownership.md` (2026-10-23) — `eggwork-core` owns the control-plane API schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification of `ExecutionState`; the runner keeps producer ownership of the capability names it produces and of the sandbox profile name. No wire value, wire field, or capability byte changes. This is the `plans/003-planning-process.md` §8 record that Control-plane M004's §12.3 stop condition requires. -Proposed ADR, **not yet accepted**: `plans/adrs/ADR-0007-resource-scoped-authorization.md` (decides whether resource-scoped grants are implemented or the inert hook and its plumbing are removed). Security M005c is blocked on it. +Accepted ADR: `plans/adrs/ADR-0007-resource-scoped-authorization.md` (2026-10-25) — **Option A: implement resource-scoped grants.** The node gains a real per-resource authorization boundary: `GrantAuthorizer` implements the existing `authorize_request` hook so the typed `ResourceId` is consulted, `ClientGrant` gains an optional, additive, bounded resource-scope list, the store's `principal_id` fences remain authoritative for ownership (the authorizer narrows, never widens), and blobs are governed by an explicit digest list because content-addressed blob storage has no owner. No wire value, wire field, capability byte, or `API_SCHEMA_VERSION` changes. Security M005c is unblocked and implements Branch A. ## Status vocabulary From 721768df265540a49762bb8a0a9afc5d995bc8ff Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Sun, 25 Oct 2026 08:02:38 +0000 Subject: [PATCH 13/37] =?UTF-8?q?feat(server):=20M005c=20resource-scoped?= =?UTF-8?q?=20authorization=20=E2=80=94=20implement=20the=20ADR-0007=20bou?= =?UTF-8?q?ndary?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ADR-0007 was accepted as Option A: the node gains a real per-resource authorization boundary instead of an inert hook that only looked available. - GrantAuthorizer implements Authorizer::authorize_request, so the typed ResourceId is consulted on the production path. The decision rule is the ADR's: the operation grant must be present; a scope configured for that (operation, resource kind) must contain the resource; otherwise the operation-level grant applies. The decision reads a configuration-derived set only — no store call, no lock, no ordering dependency. - ClientGrant gains an optional, bounded resource_scopes list (#[serde(default)], deny_unknown_fields kept). A grant without scopes keeps exactly today's operation-level meaning. - The store's principal_id fences stay authoritative for Execution, Workspace and Artifact: the authorizer narrows, never widens. Blob has no owner, so a blob scope is an explicit digest list — the residual boundary stays operation-wide and is stated as such. - Every configuration error class is refused at load time: unknown operation, unknown resource kind, malformed identifier, scope for an unheld operation, scope for a kind the operation never names, duplicate scope, and the per-grant and per-node caps. - A resource-scoped denial is indistinguishable from an operation-level denial and from a missing resource, in status code and body. - No wire value, wire field, capability byte, or API_SCHEMA_VERSION changes. The divergences row, the threat-model row, and both deep dives are updated to state the boundary as it now is. --- architecture/operations-cli.md | 151 +++-- architecture/server-node.md | 96 ++- crates/eggwork-server/src/lib.rs | 517 +++++++++++++++- crates/eggwork-server/src/operations.rs | 403 ++++++++++++- .../tests/resource_scoped_authorization.rs | 408 +++++++++++++ examples/eggworkd.example.json | 28 + .../005c-status.md | 562 ++++++++++++++++++ ...esource-scoped-authorization-corrective.md | 6 +- plans/registry.md | 6 +- plans/security/threat-model.md | 25 +- .../security-isolation-resource-roadmap.md | 14 +- 11 files changed, 2130 insertions(+), 86 deletions(-) create mode 100644 crates/eggwork-server/tests/resource_scoped_authorization.rs create mode 100644 plans/closure/security-isolation-resource/005c-status.md diff --git a/architecture/operations-cli.md b/architecture/operations-cli.md index a410290..57f5060 100644 --- a/architecture/operations-cli.md +++ b/architecture/operations-cli.md @@ -71,9 +71,10 @@ load error rather than a silently ignored setting. field, are resolved relative to the config file's own directory when they are relative — so a config can be moved as a unit. -The shape in `examples/eggworkd.example.json` matches this table exactly, with one -`clients` entry granting all eleven operation names and absolute paths under -`/var/lib/eggwork` and `/etc/eggwork`. +The shape in `examples/eggworkd.example.json` matches this table exactly, with +absolute paths under `/var/lib/eggwork` and `/etc/eggwork` and two `clients` +entries: one granting all twelve operation names, and one carrying a +`resource_scopes` list that narrows three of them. **Load-time checks (`OperatorConfig::load`).** Before any parsing, `fs::symlink_metadata` must show a regular file that is not a symlink, is at most `MAX_CONFIG_BYTES` (1 MiB), and @@ -87,6 +88,27 @@ across the grant set (compared lowercased), every named operation must resolve, `read_certificates` (regular file, not a symlink, not writable by others, non-empty) and the private key through `trusted_private_key`. +**Resource scopes (`ClientGrant.resource_scopes`).** A grant may carry an optional list of +resource scopes. Each scope names an operation, a resource kind (`execution`, `blob`, +`workspace`, `artifact`), and a resource identifier — the string form of the identifier, +parsed back into the typed form. A scope may only narrow an operation the same grant +already holds. Every one of these is a configuration error, and the node refuses to start +rather than degrade to a decision that ignores the scope: + +| Error class | Refused because | +| --- | --- | +| Unknown operation name | The scope does not name a known operation. | +| Unknown resource kind | The scope does not name a known resource kind. | +| Malformed identifier | The identifier is not the string form of the kind's typed identifier. | +| Scope for an unheld operation | The scope would grant an operation the grant does not hold. | +| Scope for a kind the operation never names | The scope could never be consulted, so it would narrow nothing. | +| Duplicate scope | The same `(operation, kind, identifier)` appears twice in one grant. | +| Over-cap grant count | More than `MAX_RESOURCE_SCOPES_PER_GRANT` (64) scopes in one grant, or more than `MAX_RESOURCE_SCOPES_TOTAL` (4096) across the node's grant set. | + +The caps are the same kind of bound the other configuration caps are, and they are checked +in `validate` alongside them. `principals()` parses the same shapes strictly, so a node +that could not build its grant table refuses to start even if `validate` was bypassed. + The directory and file trust predicates, on Unix: - `trusted_directory`: owned by the effective uid, and `mode & 0o777 == 0o700` exactly. @@ -108,35 +130,44 @@ On non-Unix targets these predicates are the trivial `true`/`false` stubs; the U ownership and mode checks do not exist there. **Redaction.** `OperatorConfig::redacted_json` serializes the whole config and then -replaces exactly two things: `tls.private_key` and every `clients[].certificate_sha256`, -each with the literal string `[REDACTED]`. Only `config print` uses this. Why it is a -security property and not cosmetics: `config print` output is the artifact an operator -pastes into a ticket, a chat channel, or a support bundle. The private key *path* names -where the key lives, and the client fingerprints bind a principal to a leaf certificate — -together they are the two fields an attacker needs to start targeting key custody or to -fingerprint a specific client. Everything else printed (chain path, client CA path, -principal ids, quotas) is an identifier the operator already needs. Note precisely what is -redacted: the *strings* are replaced, and no key material is ever loaded into the redacted -document to begin with. +replaces exactly three things: `tls.private_key`, every `clients[].certificate_sha256`, and +every `clients[].resource_scopes[].resource_id`, each with the literal string +`[REDACTED]`. Only `config print` uses this. Why it is a security property and not +cosmetics: `config print` output is the artifact an operator pastes into a ticket, a chat +channel, or a support bundle. The private key *path* names where the key lives, and the +client fingerprints bind a principal to a leaf certificate — together they are the two +fields an attacker needs to start targeting key custody or to fingerprint a specific +client. A scope's identifier is the third: it names the exact resource the operator +confined the grant to, and for a blob it is a content address whose disclosure says what +the principal is allowed to see. The scope's `operation` and `resource_kind` stay visible, +because the *shape* of the narrowing is what an operator reads; the identifier does not. +Everything else printed (chain path, client CA path, principal ids, quotas) is an identifier +the operator already needs. Note precisely what is redacted: the *strings* are replaced, +and no key material is ever loaded into the redacted document to begin with. ## Authorization model -A `ClientGrant` is a principal plus an explicit set of operation names: +A `ClientGrant` is a principal plus an explicit set of operation names, and optionally +plus a set of resource scopes that narrow those names: `principal_id`, `certificate_sha256` (documented in source as the lowercase hex SHA-256 -digest of the verified leaf certificate DER), and `operations: Vec`. +digest of the verified leaf certificate DER), `operations: Vec`, and +`resource_scopes: Vec`. `OperatorConfig::principals()` builds a pair. Every grant contributes `(certificate_sha256.to_ascii_lowercase(), PrincipalId)` to a -`FingerprintPrincipalResolver`, and a `HashSet` to a `GrantAuthorizer`. The +`FingerprintPrincipalResolver`, and a `PrincipalGrant` to a `GrantAuthorizer`. The lowercasing on both sides is what makes config-time and handshake-time fingerprints comparable. -`GrantAuthorizer` is a newtype over `HashMap>` and -implements the server's `Authorizer` trait with a single method: +A `PrincipalGrant` is the set of `Operation`s the principal holds plus a scope table keyed +by `(Operation, ResourceKind)` holding typed resource identifiers. `GrantAuthorizer` +implements the server's `Authorizer` trait: ```rust fn authorize(&self, principal: &NodePrincipal, operation: Operation) -> bool { - self.0.get(&principal.id).is_some_and(|allowed| allowed.contains(&operation)) + self.grants + .get(&principal.id) + .is_some_and(|grant| grant.operations.contains(&operation)) } ``` @@ -144,21 +175,38 @@ The default is fail-closed by construction: an unknown principal produces `None` map lookup, an ungranted operation is absent from the set, and both collapse to `false` through `is_some_and`. There is no allow-by-default branch anywhere in the file. -The name → enum mapping is a closed 11-name table in `fn operation`: `capabilities`, -`status`, `execute`, `observe`, `cancel`, `renew`, `events`, `blob-read`, `blob-write`, -`workspace-create`, `artifact-read`. Anything else returns `None`, which `validate` treats -as a config error, so a typo in a grant is a startup refusal rather than a silently -missing permission. - -**Scope of the policy, stated conservatively.** In `operations.rs` the authorizer -overrides *only* `authorize`. This file does not implement, and does not reference, any -resource-aware `authorize_request` hook. I could not verify from the two files owned by -this deep dive whether the `Authorizer` trait in `lib.rs` declares such a hook and what -its default body does; the resolution is recorded in [server-node.md](server-node.md). The -operationally important consequence is the part that *is* visible here: the policy -expressed in this file is a principal × operation product with no resource dimension at -all. Any per-resource narrowing a deployment needs is therefore not produced by -`GrantAuthorizer` and must be enforced by the request path. +The name → enum mapping is a closed 12-name table in `fn operation`: `capabilities`, +`status`, `telemetry`, `execute`, `observe`, `cancel`, `renew`, `events`, `blob-read`, +`blob-write`, `workspace-create`, `artifact-read`. Anything else returns `None`, which +`validate` treats as a config error, so a typo in a grant is a startup refusal rather than +a silently missing permission. + +**Scope of the policy.** The policy expressed in this file is a principal × operation +product, optionally narrowed per resource. `GrantAuthorizer` overrides both `authorize` and +the trait's resource-aware `authorize_request` hook; the hook's decision is: + +1. the operation grant must be present — a scope never grants an operation the principal + does not hold; +2. a request that carries no resource falls back to the operation-level grant; +3. when a scope is configured for that operation **and** that resource kind, the resource + must be inside it; +4. otherwise the operation-level grant stands. + +Rule 3 is per `(operation, kind)`: a scope for `execute`/`execution` does not narrow +`execute`/`workspace`. The decision consults a configuration-derived set only — it never +asks the store who owns a resource — so it adds no lock and no ordering dependency to the +request path. Ownership stays where it already was: the store's `principal_id` fences, +which the authorizer can only narrow in front of, never widen around. A scope that names +another principal's resource lets the request reach the store, and the store refuses it +there. The exception is `blob`: blob storage is content-addressed and shared, so a blob has +no owner to fence it, and a blob scope is an explicit digest list rather than an ownership +comparison. The full decision record is in [server-node.md](server-node.md). + +**Compatibility.** `ClientGrant` keeps `#[serde(deny_unknown_fields)]` and the new field is +`#[serde(default)]`, so a configuration written before scopes existed still loads, and an +*older node* reading a newer configuration that carries a scope refuses to start rather +than silently ignoring the narrowing the operator wrote. That refusal is correct behaviour: +a node whose boundary is wider than its configuration states is the defect. ## Command surface @@ -622,9 +670,12 @@ be able to tell them apart from the JSON alone, since the exit code is 2 in ever | --- | --- | --- | | A group/other-writable or symlinked config is refused | `OperatorConfig::load` metadata gate | `invalid_configuration_is_rejected_without_exposing_secret_material` | | A private key readable by group/other is refused | `trusted_private_key` | `valid_operator_config_builds_required_mtls_server_identity` | -| `config print` never emits the key path or client fingerprints | `OperatorConfig::redacted_json` | `redacted_config_print_hides_private_key_path_and_client_fingerprints` | +| `config print` never emits the key path, client fingerprints, or scope identifiers | `OperatorConfig::redacted_json` | `redacted_config_print_hides_private_key_path_and_client_fingerprints`, `the_printed_configuration_redacts_resource_scope_identifiers` | | An unknown operation name is a config error, not a missing permission | `validate` → `operation()` returning `None` | `valid_operator_config_builds_required_mtls_server_identity` | -| An unknown principal or ungranted operation is denied | `GrantAuthorizer::authorize` via `is_some_and` | No unit test in this file; see [server-node.md](server-node.md) | +| An unknown principal or ungranted operation is denied | `GrantAuthorizer::authorize` via `is_some_and` | `a_scope_never_grants_an_operation_the_principal_does_not_hold` (`tests/resource_scoped_authorization.rs`); see [server-node.md](server-node.md) | +| A resource scope narrows an operation the grant holds and never widens it | `GrantAuthorizer::authorize_request` | `a_resource_scope_narrows_the_operation_grant_it_names` (`tests/resource_scoped_authorization.rs`) | +| A malformed scope is a config error, not an ignored entry | `validate` + `principals()` | `a_malformed_resource_scope_is_refused_by_the_configuration`, `a_duplicate_resource_scope_is_refused_by_the_configuration`, `too_many_resource_scopes_in_one_grant_are_refused`, `too_many_resource_scopes_across_the_node_are_refused` | +| An older node refuses a configuration that carries a scope | `deny_unknown_fields` on `ClientGrant` | `an_older_node_refuses_a_configuration_that_carries_a_resource_scope` (`tests/resource_scoped_authorization.rs`) | | `doctor` agrees with the enforcement path on helper trust | `trusted_helper` → `verify_trusted_helper`, shared with the runner | `valid_operator_config_builds_required_mtls_server_identity` (adjacent); see [sandbox-helper.md](sandbox-helper.md) | | Execution listings are bounded and paginate | `MAX_EXECUTION_PAGE`, `load_snapshots` `LIMIT 2049` + `Bounds` | `execution_listing_is_bounded_and_paginates_over_durable_records` | | Symlinks are never followed when measuring a tree | `tree_bytes` `file_type().is_symlink()` check | `tree_size_never_follows_symlinks` | @@ -640,8 +691,16 @@ be able to tell them apart from the JSON alone, since the exit code is 2 in ever ## Test coverage -`operations.rs` has exactly 9 tests in its in-file `mod tests`, all library-level: +`operations.rs` has exactly 17 tests in its in-file `mod tests`, all library-level: `redacted_config_print_hides_private_key_path_and_client_fingerprints`, +`the_printed_configuration_redacts_resource_scope_identifiers`, +`a_resource_scope_that_narrows_a_held_operation_is_accepted`, +`a_malformed_resource_scope_is_refused_by_the_configuration`, +`a_duplicate_resource_scope_is_refused_by_the_configuration`, +`too_many_resource_scopes_in_one_grant_are_refused`, +`too_many_resource_scopes_across_the_node_are_refused`, +`a_configuration_written_before_resource_scopes_still_validates`, +`the_grant_table_refuses_a_scope_it_cannot_parse`, `drain_state_survives_process_restart_and_undrain_removes_marker`, `tree_size_never_follows_symlinks`, `execution_listing_is_bounded_and_paginates_over_durable_records`, @@ -650,9 +709,17 @@ be able to tell them apart from the JSON alone, since the exit code is 2 in ever `metrics_report_uses_a_fixed_bounded_counter_set`, `invalid_configuration_is_rejected_without_exposing_secret_material`, and `valid_operator_config_builds_required_mtls_server_identity`. They cover config -load/validate, redaction, drain, sizing, pagination, both GC modes, and metrics. They -build their fixture config inline, which is why the field set is duplicated in the test -helper and why a new `OperatorConfig` field is a compile-time reminder there. +load/validate, redaction, drain, sizing, pagination, both GC modes, metrics, and the +resource-scope configuration surface. They build their fixture config inline, which is why +the field set is duplicated in the test helper and why a new `OperatorConfig` field is a +compile-time reminder there. + +`tests/resource_scoped_authorization.rs` is a separate, portable target: it drives the +grant table through the public API only, so it needs no filesystem, no process, no TLS +handshake, and no host platform. It holds the decision rule and the configuration shape — +that a scope narrows, that it never grants, that it is per `(operation, kind)`, that a +request without a resource falls back to the operation grant, and that an older node +refuses a configuration carrying a scope. **`bin/eggworkd.rs` has no `#[cfg(test)]` module at all.** Every CLI concern is therefore untested at the unit level: argv parsing and the `--config` splice, `parse_option` @@ -674,7 +741,9 @@ both a nonzero return code and that `draining` is present in the output. I read harness only by targeted grep, so the list above is grep-verified but not exhaustively so. -**Honest gaps.** No unit test for `GrantAuthorizer` itself; no test for +**Honest gaps.** The `GrantAuthorizer` decision is covered by +`tests/resource_scoped_authorization.rs` and by the server's own end-to-end test, but the +*in-file* `operations.rs` module has no test that calls the authorizer directly; no test for `active_execution_count`'s fail-closed branches; no test for `storage_summary`'s WAL/shm accounting; no test for the three `inspect_*` functions or the blob size cross-check; no test for `start_server`; and no test at all in the binary. The macOS launchd flag matrix diff --git a/architecture/server-node.md b/architecture/server-node.md index dc5fc0c..b256d18 100644 --- a/architecture/server-node.md +++ b/architecture/server-node.md @@ -191,18 +191,59 @@ only ever see the operation — never the resource. Resource scoping requires a `derived_workspace_denied_and_oversized_bodies_are_typed` (`lib.rs:4499`) and `resource_aware_authorizer_can_scope_blob_capability` (`lib.rs:3039`). -**How `GrantAuthorizer` realizes per-principal grants.** `GrantAuthorizer(HashMap>)` (`operations.rs:332-340`) implements only `authorize`: -`self.0.get(&principal.id).is_some_and(|allowed| allowed.contains(&operation))`. It is built by -`principals()` (`operations.rs:305-325`), which walks the configured clients, lowercases each -`certificate_sha256` into the `FingerprintPrincipalResolver` table, and maps each configured -operation *name* to an `Operation` through `operation(name)` (`operations.rs:342-357`) — note -`filter_map`, so an unrecognized operation name in configuration is **silently dropped** rather -than rejected, shrinking that client's grant set. Absent principal ⇒ `None` ⇒ `false` (deny by -default). Because it does not override `authorize_request`, grant-based deployments are strictly -operation-wide; the `resource_for_path` enrichment in `dispatch` has no effect for them. The -`GrantAuthorizer` has no cross-principal or cross-execution scoping: per-execution ownership is -enforced later, in the store, by comparing `existing.principal_id` (`lib.rs:1677`, `2044`, `2267`). +**How `GrantAuthorizer` realizes per-principal grants.** `GrantAuthorizer` (`operations.rs:535-581`) holds a +`HashMap`; a `PrincipalGrant` (`operations.rs:524-527`) is the set of +`Operation`s the principal holds plus an optional resource-scope table keyed by +`(Operation, ResourceKind)` and holding typed `ResourceId`s. It is built by `principals()` +(`operations.rs:472-511`), which walks the configured clients, lowercases each `certificate_sha256` into the +`FingerprintPrincipalResolver` table, and maps each configured operation *name* to an `Operation` through +`operation(name)` (`operations.rs:615-631`) — note `filter_map`, so an unrecognized operation name in +configuration is **silently dropped** rather than rejected, shrinking that client's grant set. Absent +principal ⇒ `None` ⇒ `false` (deny by default). + +**Resource-scoped grants.** `ClientGrant` (`operations.rs:156-175`) carries an optional `resource_scopes` +list. Each `ResourceScope` (`operations.rs:142-153`) names an **operation**, a **resource kind** +(`execution`, `blob`, `workspace`, `artifact`), and a **resource identifier** — the string form of the +`ResourceId` variant, parsed back into the typed variant by `parse_resource_id` +(`operations.rs:600-613`) through the same constructors the request path uses, so configuration and the +request path cannot disagree about what an identifier is. A grant with no scopes keeps exactly its +operation-level meaning, which is what every configuration written before scopes existed means. + +The decision rule (`GrantAuthorizer::authorize_request`, `operations.rs:566-580`) is, in order: + +1. the operation grant must be present — a scope never grants an operation the principal does not hold; +2. a request that carries no resource falls back to the operation-level grant; +3. when a scope is configured for that operation **and** that resource kind, the resource must be inside it; +4. otherwise the operation-level grant stands. + +Rule 3 is per `(operation, kind)`: a scope for `Execute`/`Execution` does not narrow `Execute`/`Workspace`, +and a scope for `BlobRead`/`Blob` does not narrow `BlobWrite`/`Blob`. An operator who wants both kinds +constrained writes a scope for each. The decision consults a **configuration-derived set only** — it never +asks the store who owns a resource — so authorization keeps the in-memory, lock-free shape it has always +had and acquires no ordering dependency it did not have before. + +**The store stays authoritative for ownership.** The authorizer's resource decision can only *narrow*: it +never grants an operation, and it never widens a grant. For `Execution`, `Workspace`, and `Artifact` the +existing `principal_id` fences remain the authority, so a scope that names another principal's resource lets +the request reach the store and the store refuses it there (`store.load_snapshot_for_principal`, the owner +comparison in `workspaces.materialize`, `artifacts.get`/`artifacts.list`). `Blob` is different and +deliberately so: blob storage is content-addressed and shared, so a blob has no owner to fence it — a blob +scope is an **explicit digest list**, never an ownership comparison. + +**Configuration fails closed at load time.** Every error class is a configuration error and the node +refuses to start rather than degrade to a permissive decision: an unknown operation name, an unknown resource +kind, a malformed identifier, a scope for an operation the grant does not hold, a scope for a kind that +operation never names, a duplicate scope, and an over-cap grant count. `OperatorConfig::validate` enforces +the per-grant cap (`MAX_RESOURCE_SCOPES_PER_GRANT = 64`) and the per-node cap +(`MAX_RESOURCE_SCOPES_TOTAL = 4096`) alongside the existing caps; `principals()` parses the same shapes +strictly, so a node that could not build its grant table refuses to start even if `validate` was bypassed. + +**`deny_unknown_fields` is deliberate.** `ClientGrant` keeps `#[serde(deny_unknown_fields)]` and the new +field is `#[serde(default)]`, so an older configuration file still loads — and an *older node* reading a +newer configuration that carries a scope refuses to start rather than silently ignoring the narrowing the +operator wrote. That refusal is correct behaviour, not a defect: a node whose boundary is wider than its +configuration states is the defect. + **Authorization runs BEFORE resource resolution.** In `dispatch` the order is: route lookup (728) → authentication (732) → `authorize_request` (744) → handler (755). `resource_for_path` (`lib.rs:783-806`) @@ -212,9 +253,13 @@ store. Handlers then resolve existence — `store.load_snapshot_for_principal` i deliberate: a client that is not authorized for an operation learns nothing about whether the target execution, blob, or artifact exists, because it is rejected with a uniform `403` before any lookup happens. Where a handler must do a *second* resource check (body-derived ids), an unauthorized -result is still a bare `403` and never leaks existence. The residual disclosure to note: the -operation-wide gate is uniform across resources, so a principal granted `BlobRead` can use -`POST /v1/blobs/missing` to probe digest presence — presence is data the grant explicitly confers. +result is still a bare `403` and never leaks existence. A **resource-scoped** denial is the same bare +`403 forbidden` / "operation is not authorized" as an operation-level denial, and is identical for a +resource that exists and for one that does not — the caller learns nothing about which. The residual +disclosure to note: the operation-wide gate is uniform across resources, so a principal granted `BlobRead` +with **no** blob scope can use `POST /v1/blobs/missing` to probe digest presence — presence is data the +grant explicitly confers, and a blob scope is the only boundary available for a resource that has no +owner. `Route::BlobInvalidDigest` (`lib.rs:767-771`) is reached only *after* authorization, and returns a distinct `400 invalid_digest`, so an unauthorized caller cannot use it to distinguish "malformed" from "well-formed but denied". @@ -901,6 +946,9 @@ echoes its address: a node whose provider happens to be down is still a healthy | The feature list is single-canonical and deduped | `static_capability_features` + sort/dedup | `static_capability_features_are_a_single_canonical_list`, `server_capability_features_do_not_duplicate_static_dynamic_overlap`, `the_advertised_argv_feature_is_the_one_the_owner_declares` | | Only the fixed, versioned route set exists | `operation_for` (`lib.rs:640-700`) | `route_contract_is_fixed_target_and_versioned` (2934) | | An authorized op on a different resource is still denied | `authorize_resource` re-checks (`lib.rs:808`, `928`, `983`, `1038`, `1159`, `1518`) | `resource_aware_authorizer_can_scope_blob_capability` (3039), `derived_workspace_denied_and_oversized_bodies_are_typed` (4499) | +| A resource scope narrows the operation grant and never widens it | `GrantAuthorizer::authorize_request` (`operations.rs:566-580`) | `a_resource_scope_narrows_the_operation_grant_it_names`, `a_scope_never_grants_an_operation_the_principal_does_not_hold` (`tests/resource_scoped_authorization.rs`) | +| A scope never reaches another principal's resource | the store's `principal_id` fences, unchanged | `a_resource_scope_cannot_reach_a_foreign_principal_resource` (`lib.rs`) | +| A malformed scope is a configuration error, not an ignored entry | `OperatorConfig::validate` (`operations.rs`) + `principals()` | `a_malformed_resource_scope_is_refused_by_the_configuration`, `a_duplicate_resource_scope_is_refused_by_the_configuration` (`operations.rs`) | | A repeat submit never starts a second execution | `store.lookup` pre-check + `ReserveResult::Existing` (`lib.rs:1664`, `1793`) | `blob_protocol_streams_verifies_deduplicates_and_enforces_quota` (3399) | | Identity conflicts are refused, not merged | `lib.rs:1670-1690`, `1808-1835` | `mtls_authorization_and_fixed_target_execution` (3137) | | Stale generations cannot mutate state | generation preconditions in `control` (`lib.rs:2072`) and `events_route` | `cross_principal_execution_fencing_without_lease_oracle` (5766) | @@ -942,6 +990,13 @@ file). Fixtures first: `init_tls`, `issue_identity`, `tls_material`, `untrusted_ - 3039 `resource_aware_authorizer_can_scope_blob_capability` — an authorizer overriding **only** `authorize_request` denies one digest, exercising the resource-scoped path independently of `GrantAuthorizer`. +- `a_resource_scope_cannot_reach_a_foreign_principal_resource` — a second principal whose scopes + name the first principal's execution, workspace, and artifact: the authorizer lets the requests + through the scope and the store's owner fence refuses them. +- `tests/resource_scoped_authorization.rs` — the decision rule and the configuration shape, portable + across hosts: the scope narrows, the scope never grants, the scope is per `(operation, kind)`, a + request without a resource falls back to the operation grant, an older node refuses a configuration + that carries a scope. - 3090 `lease_expiry_takes_precedence_over_cancel_before_spawn` — the match order in `failure_for_runner_error` (`Spawn` > expired > `CancelledBeforeSpawn`) is load-bearing. - 3137 `mtls_authorization_and_fixed_target_execution`, with 3326 `routed_mtls_execution` and the @@ -1004,9 +1059,14 @@ file). Fixtures first: `init_tls`, `issue_identity`, `tls_material`, `untrusted_ - **Digest reuse across callers.** `store.lookup` compares `principal_id` *before* the digest (`1677` vs `1684`), so a foreign principal learns an execution id exists from the 403 while a matching principal learns identity conflicts. Intended? -- **`GrantAuthorizer` ignores resources.** It implements only `authorize`, so `resource` in - `OperationRequest` is inert for the real deployment path. Is store-level per-execution ownership - genuinely sufficient, or are resource-scoped grants required? +- **Resource scopes are per `(operation, kind)`.** A scope for `Execute`/`Execution` does not + narrow `Execute`/`Workspace`, and a scope for `BlobRead`/`Blob` does not narrow `BlobWrite`/`Blob`. + Is that granularity what an operator expects, or should a scope on an operation narrow every kind + that operation names? +- **Blob scope identifiers must be known in advance.** Blob digests are content addresses, so a + blob scope can only name digests the operator already knows. Is there an operation that would let + an operator learn a digest and then scope it, or is "learn the digest, then edit the config" + the intended workflow? - **Silent config-drop in `operation(name)`** (`operations.rs:342-357`): `filter_map` means a typo in a configured operation name quietly narrows a client's grants with no startup error. Should it be `OperationsError::Config`? diff --git a/crates/eggwork-server/src/lib.rs b/crates/eggwork-server/src/lib.rs index b0ebe2d..c4a1cec 100644 --- a/crates/eggwork-server/src/lib.rs +++ b/crates/eggwork-server/src/lib.rs @@ -180,7 +180,43 @@ pub enum Operation { ArtifactRead, } -#[derive(Debug, Clone, PartialEq, Eq)] +impl Operation { + /// The resource kinds this operation's requests can name. + /// + /// A resource scope is refused when its `(operation, kind)` pair is not + /// in this table: a scope that could never be consulted would narrow + /// nothing while the operator believed it did. The table is exactly the + /// set the request path resolves — `resource_for_path` for the + /// path-derived operations, and the handler-level `authorize_resource` + /// calls for the body-derived ones — so a scope can never be written + /// for a resource the node does not resolve. + pub fn resource_kinds(&self) -> &'static [ResourceKind] { + match self { + Self::Execute => &[ResourceKind::Execution, ResourceKind::Workspace], + Self::Observe | Self::Cancel | Self::Renew | Self::Events => &[ResourceKind::Execution], + Self::BlobRead | Self::BlobWrite => &[ResourceKind::Blob], + Self::WorkspaceCreate => &[ResourceKind::Workspace], + Self::ArtifactRead => &[ResourceKind::Artifact, ResourceKind::Execution], + Self::Capabilities | Self::Status | Self::Telemetry => &[], + } + } +} + +/// The kind of resource a request names. +/// +/// A resource scope names a kind and an identifier, and the two must agree: +/// a scope for `Blob` is compared against blob identifiers only. The kind is +/// derived from the typed [`ResourceId`] variant so the configuration and +/// the request path cannot disagree about what an identifier is. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ResourceKind { + Execution, + Blob, + Workspace, + Artifact, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum ResourceId { Execution(ExecutionId), Blob(eggwork_core::BlobDigest), @@ -188,6 +224,18 @@ pub enum ResourceId { Artifact(eggwork_core::ArtifactId), } +impl ResourceId { + /// The kind of resource this identifier names. + pub fn kind(&self) -> ResourceKind { + match self { + Self::Execution(_) => ResourceKind::Execution, + Self::Blob(_) => ResourceKind::Blob, + Self::Workspace(_) => ResourceKind::Workspace, + Self::Artifact(_) => ResourceKind::Artifact, + } + } +} + #[derive(Debug, Clone, PartialEq, Eq)] pub struct OperationRequest { pub operation: Operation, @@ -235,6 +283,13 @@ pub trait Authorizer: Send + Sync + 'static { /// Resource-aware hook. Existing operation-wide policies remain valid; /// scoped policies can override this method to inspect authenticated IDs. + /// + /// The default body is exactly the operation-level decision, which is the + /// behaviour a deployment that configures no resource scope keeps. An + /// override may only *narrow* that decision: the store's `principal_id` + /// fences remain authoritative for ownership, so an authorizer that + /// permits a resource the principal does not own still gets refused by + /// the store. fn authorize_request(&self, principal: &NodePrincipal, request: &OperationRequest) -> bool { self.authorize(principal, request.operation) } @@ -3712,6 +3767,466 @@ mod tests { server.wait().await.unwrap(); } + /// Build the node's grant table from client grants. + /// + /// `OperatorConfig::principals` reads only the client grants, so the + /// paths and the TLS material below are never touched: this is the same + /// table the daemon builds, reached without a configuration file. + fn scoped_grant_table( + clients: Vec, + ) -> crate::operations::GrantAuthorizer { + crate::operations::OperatorConfig { + schema_version: 1, + node_id: "node-scoped".into(), + bind: "127.0.0.1:0".into(), + execution_root: PathBuf::from("unused"), + database_path: PathBuf::from("unused"), + blob_root: PathBuf::from("unused"), + blob_quota_bytes: 1, + workspace_root: PathBuf::from("unused"), + workspace_quota_bytes: 1, + max_active_executions: 1, + lease_ttl_seconds: 1, + sandbox_helper: None, + tls: crate::operations::TlsFiles { + certificate_chain: PathBuf::from("unused"), + private_key: PathBuf::from("unused"), + client_ca: PathBuf::from("unused"), + }, + clients, + host_telemetry: None, + } + .principals() + .expect("the grant table builds") + .1 + } + + fn scoped_grant( + principal: &str, + fingerprint: u64, + operations: &[&str], + resource_scopes: Vec, + ) -> crate::operations::ClientGrant { + crate::operations::ClientGrant { + principal_id: principal.into(), + certificate_sha256: format!("{fingerprint:064x}"), + operations: operations.iter().map(|name| (*name).to_string()).collect(), + resource_scopes, + } + } + + fn scoped_scope( + operation: &str, + resource_kind: &str, + resource_id: &str, + ) -> crate::operations::ResourceScope { + crate::operations::ResourceScope { + operation: operation.into(), + resource_kind: resource_kind.into(), + resource_id: resource_id.into(), + } + } + + /// A resource scope is a narrowing, never a grant. + /// + /// The second principal's scopes name the *first* principal's resources. + /// The authorizer lets those requests through the scope — it consults a + /// configuration-derived set and cannot know who owns a resource — and the + /// store's `principal_id` fence refuses them. That is the whole claim: + /// a resource-scoped grant naming another principal's resource does not + /// reach it, for an execution, a workspace, and an artifact. + #[tokio::test] + async fn a_resource_scope_cannot_reach_a_foreign_principal_resource() { + init_tls(); + let (root, server_identity, owner_identity, intruder_identity) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let owner = eggwork_core::PrincipalId::new("controller-a").unwrap(); + let intruder = eggwork_core::PrincipalId::new("controller-b").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([ + ( + FingerprintPrincipalResolver::fingerprint(owner_identity.cert.as_ref()), + owner.clone(), + ), + ( + FingerprintPrincipalResolver::fingerprint(intruder_identity.cert.as_ref()), + intruder.clone(), + ), + ])); + // Both principals hold the same operations. The second one's scopes + // name the first one's resources. + let authorizer = Arc::new(scoped_grant_table(vec![ + scoped_grant( + "controller-a", + 1, + &[ + "capabilities", + "status", + "execute", + "observe", + "workspace-create", + "artifact-read", + "blob-write", + ], + vec![], + ), + scoped_grant( + "controller-b", + 2, + &[ + "capabilities", + "status", + "execute", + "observe", + "workspace-create", + "artifact-read", + "blob-write", + ], + vec![ + scoped_scope("execute", "execution", "exec-owned-by-a"), + scoped_scope("observe", "execution", "exec-owned-by-a"), + scoped_scope("workspace-create", "workspace", "ws-owned-by-a"), + scoped_scope("artifact-read", "execution", "exec-owned-by-a"), + scoped_scope("artifact-read", "artifact", "art-owned-by-a"), + ], + ), + ])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: None, + node_id: NodeId::new("node-scoped").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + authorizer.clone(), + ) + .await + .unwrap(); + let owner_temp = TempDir::new().unwrap(); + let owner_client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&owner_temp, root.as_ref(), &owner_identity), + ) + .unwrap(); + let intruder_temp = TempDir::new().unwrap(); + let intruder_client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&intruder_temp, root.as_ref(), &intruder_identity), + ) + .unwrap(); + + // The owner creates the execution the intruder's scopes name. + let owner_handle = execution_handle("exec-owned-by-a"); + let accepted = owner_client + .execute( + &execution_spec(vec!["/bin/sh".into(), "-c".into(), "exit 0".into()]), + &owner_handle, + ) + .await; + let detail = match &accepted { + Ok(_) => "accepted".to_string(), + Err(eggwork_client::ClientError::Api { + status, + code, + message, + }) => format!("{status} {code} {message}"), + Err(other) => format!("{other:?}"), + }; + assert!( + accepted.is_ok(), + "the owner must be able to execute: {detail}" + ); + let execution_id = ExecutionId::new("exec-owned-by-a").unwrap(); + // The owner reads its own execution. + assert!(owner_client.observe(&execution_id).await.is_ok()); + // The scope lets the intruder through the authorizer: the scope names + // the execution, so the authorizer has no reason to refuse it. + assert!(authorizer.authorize_request( + &NodePrincipal { + id: intruder.clone(), + }, + &OperationRequest { + operation: Operation::Observe, + resource: Some(ResourceId::Execution(execution_id.clone())), + }, + )); + // The store's owner fence refuses it anyway. + assert!(matches!( + intruder_client.observe(&execution_id).await, + Err(eggwork_client::ClientError::Api { status: 404, .. }) + )); + + // The owner creates the workspace the intruder's scope names. + let workspace_id = eggwork_core::WorkspaceId::new("ws-owned-by-a").unwrap(); + let manifest = eggwork_core::WorkspaceManifest { + schema_version: 1, + entries: vec![], + }; + assert!( + owner_client + .create_workspace( + &workspace_id, + &execution_handle("ws-owned-by-a-execution"), + &manifest, + ) + .await + .is_ok(), + "the owner must be able to create the workspace" + ); + assert!(authorizer.authorize_request( + &NodePrincipal { + id: intruder.clone(), + }, + &OperationRequest { + operation: Operation::WorkspaceCreate, + resource: Some(ResourceId::Workspace(workspace_id.clone())), + }, + )); + // The workspace belongs to the owner; the intruder's create conflicts + // with it rather than taking it over. + assert!(matches!( + intruder_client + .create_workspace( + &workspace_id, + &execution_handle("ws-owned-by-a-intruder-execution"), + &manifest, + ) + .await, + Err(eggwork_client::ClientError::Api { status: 409, .. }) + )); + + // The owner publishes an artifact the intruder's scope names. + let payload = b"artifact-owned-by-a"; + let digest = eggwork_core::BlobDigest::from_bytes(payload); + let chunks = payload + .chunks(32 * 1024) + .map(|chunk| Ok::<_, eggfetch_core::Error>(Bytes::copy_from_slice(chunk))) + .collect::>(); + owner_client + .upload_blob( + &digest, + payload.len() as u64, + Box::pin(stream::iter(chunks)), + ) + .await + .unwrap(); + let record = eggwork_core::ArtifactRecord { + artifact_id: eggwork_core::ArtifactId::new("art-owned-by-a").unwrap(), + execution_id: execution_id.clone(), + generation: ExecutionGeneration::new(1).unwrap(), + path: eggwork_core::RelativePath::new("out.txt").unwrap(), + kind: eggwork_core::ArtifactType::File, + digest: digest.clone(), + size_bytes: payload.len() as u64, + executable: false, + created_unix_ms: artifact::now_unix_ms(), + expires_unix_ms: artifact::now_unix_ms() + 3_600_000, + }; + let artifact_store = artifact::ArtifactStore::open(artifact::metadata_path( + &temp.path().join("node.sqlite"), + )) + .unwrap(); + artifact_store + .insert_many(std::slice::from_ref(&record), &owner) + .unwrap(); + // The owner sees its own artifact and can read it. + assert_eq!( + owner_client + .artifacts(&execution_id, 1) + .await + .unwrap() + .len(), + 1 + ); + assert!(owner_client.download_artifact(&record).await.is_ok()); + // The scope lets the intruder through the authorizer for both kinds + // the artifact read names. + assert!(authorizer.authorize_request( + &NodePrincipal { + id: intruder.clone(), + }, + &OperationRequest { + operation: Operation::ArtifactRead, + resource: Some(ResourceId::Artifact(record.artifact_id.clone())), + }, + )); + assert!(authorizer.authorize_request( + &NodePrincipal { + id: intruder.clone(), + }, + &OperationRequest { + operation: Operation::ArtifactRead, + resource: Some(ResourceId::Execution(execution_id.clone())), + }, + )); + // The store's owner fence refuses both: the intruder's list is empty + // and the artifact itself is not found. + assert!( + intruder_client + .artifacts(&execution_id, 1) + .await + .unwrap() + .is_empty(), + "another principal's artifacts must stay invisible" + ); + assert!(matches!( + intruder_client.download_artifact(&record).await, + Err(eggwork_client::ClientError::Api { status: 404, .. }) + )); + server.shutdown().await; + server.wait().await.unwrap(); + } + + /// The status code, error code, and message a denied caller sees. + fn denial_shape(error: &eggwork_client::ClientError) -> (u16, String, String) { + match error { + eggwork_client::ClientError::Api { + status, + code, + message, + } => (*status, code.clone(), message.clone()), + other => panic!("expected an API error, got {other:?}"), + } + } + + /// A resource-scoped denial is indistinguishable from an operation-level + /// denial, and from the denial of a resource that does not exist. + /// + /// A scoped principal must not be able to tell "that resource exists but is + /// outside my scope" from "that resource does not exist" from "you may not + /// read blobs at all": the same status code, the same error code, and the + /// same message in all three cases. + #[tokio::test] + async fn a_resource_scoped_denial_is_indistinguishable_from_an_operation_level_denial() { + init_tls(); + let (root, server_identity, scoped_identity, ungranted_identity) = tls_material(); + let temp = TempDir::new().unwrap(); + let work_root = temp.path().join("work"); + fs::create_dir_all(&work_root).unwrap(); + let scoped_principal = eggwork_core::PrincipalId::new("scoped-controller").unwrap(); + let ungranted_principal = eggwork_core::PrincipalId::new("ungranted-controller").unwrap(); + let resolver = Arc::new(FingerprintPrincipalResolver::new([ + ( + FingerprintPrincipalResolver::fingerprint(scoped_identity.cert.as_ref()), + scoped_principal.clone(), + ), + ( + FingerprintPrincipalResolver::fingerprint(ungranted_identity.cert.as_ref()), + ungranted_principal.clone(), + ), + ])); + let in_scope = eggwork_core::BlobDigest::from_bytes(b"blob-inside-the-scope"); + let out_of_scope = eggwork_core::BlobDigest::from_bytes(b"blob-outside-the-scope"); + let absent = eggwork_core::BlobDigest::from_bytes(b"blob-never-published"); + let authorizer = Arc::new(scoped_grant_table(vec![ + scoped_grant( + "scoped-controller", + 1, + &["capabilities", "status", "blob-read", "blob-write"], + vec![scoped_scope("blob-read", "blob", in_scope.as_str())], + ), + scoped_grant( + "ungranted-controller", + 2, + &["capabilities", "status"], + vec![], + ), + ])); + let server = NodeServer::start( + NodeConfig { + host_telemetry: None, + node_id: NodeId::new("node-scoped").unwrap(), + bind: "127.0.0.1:0".parse().unwrap(), + execution_root: work_root, + database_path: temp.path().join("node.sqlite"), + blob_root: temp.path().join("blob-store"), + blob_quota_bytes: 1024 * 1024, + workspace_root: temp.path().join("workspace-store"), + workspace_quota_bytes: 1024 * 1024, + max_active_executions: 2, + lease_ttl: std::time::Duration::from_secs(30), + tls: tls_server_config(root.clone(), &server_identity), + }, + Arc::new(LocalProcessRunner::default()), + resolver, + authorizer.clone(), + ) + .await + .unwrap(); + let scoped_temp = TempDir::new().unwrap(); + let scoped_client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&scoped_temp, root.as_ref(), &scoped_identity), + ) + .unwrap(); + let ungranted_temp = TempDir::new().unwrap(); + let ungranted_client = NodeClient::new( + format!("https://localhost:{}", server.local_addr().port()), + write_client_config(&ungranted_temp, root.as_ref(), &ungranted_identity), + ) + .unwrap(); + // The scoped principal publishes two blobs: one inside its scope and + // one outside it. + for payload in [ + b"blob-inside-the-scope".as_slice(), + b"blob-outside-the-scope".as_slice(), + ] { + let digest = eggwork_core::BlobDigest::from_bytes(payload); + let chunks = payload + .chunks(32 * 1024) + .map(|chunk| Ok::<_, eggfetch_core::Error>(Bytes::copy_from_slice(chunk))) + .collect::>(); + scoped_client + .upload_blob( + &digest, + payload.len() as u64, + Box::pin(stream::iter(chunks)), + ) + .await + .unwrap(); + } + let scoped_digest = in_scope; + let out_of_scope_digest = out_of_scope; + let absent_digest = absent; + // The digest inside the scope is readable: the scope is consulted and + // it let this one through. + assert!(scoped_client.download_blob(&scoped_digest).await.is_ok()); + // A digest outside the scope is refused, whether or not it exists. + let scoped_denial = scoped_client + .download_blob(&out_of_scope_digest) + .await + .map(|_| ()) + .expect_err("an out-of-scope digest must be refused"); + let absent_denial = scoped_client + .download_blob(&absent_digest) + .await + .map(|_| ()) + .expect_err("an absent digest must be refused the same way"); + // A principal with no blob grant at all is refused the same way. + let operation_denial = ungranted_client + .download_blob(&scoped_digest) + .await + .map(|_| ()) + .expect_err("an ungranted operation must be refused"); + let scoped_shape = denial_shape(&scoped_denial); + assert_eq!(scoped_shape.0, 403); + assert_eq!(scoped_shape, denial_shape(&absent_denial)); + assert_eq!(scoped_shape, denial_shape(&operation_denial)); + server.shutdown().await; + server.wait().await.unwrap(); + } + async fn routed_mtls_execution(route: &str, execution_id: &str) { init_tls(); let (root, server_identity, client_identity, _) = tls_material(); diff --git a/crates/eggwork-server/src/operations.rs b/crates/eggwork-server/src/operations.rs index b4de768..cb62c95 100644 --- a/crates/eggwork-server/src/operations.rs +++ b/crates/eggwork-server/src/operations.rs @@ -2,11 +2,13 @@ use crate::{ Authorizer, FingerprintPrincipalResolver, NodeConfig, NodeGcReport, NodePrincipal, NodeServer, - Operation, artifact::ArtifactStore, blob::BlobStore, telemetry::HostTelemetryConfig, - workspace::WorkspaceManager, + Operation, OperationRequest, ResourceId, ResourceKind, artifact::ArtifactStore, + blob::BlobStore, telemetry::HostTelemetryConfig, workspace::WorkspaceManager, }; use eggserve_core::tls::TlsServerConfig; -use eggwork_core::{ExecutionGeneration, ExecutionId, NodeId, PrincipalId}; +use eggwork_core::{ + ArtifactId, BlobDigest, ExecutionGeneration, ExecutionId, NodeId, PrincipalId, WorkspaceId, +}; use rusqlite::OptionalExtension; use rustls::pki_types::CertificateDer; use serde::{Deserialize, Serialize}; @@ -24,6 +26,14 @@ use thiserror::Error; const MAX_CONFIG_BYTES: u64 = 1024 * 1024; const MAX_GC_BATCH: usize = 1024; const MAX_EXECUTION_PAGE: usize = 200; +/// The maximum number of resource scopes one grant may carry. +/// +/// A scope is a small, hand-written narrowing of an operation the principal +/// already holds, not a policy language. The cap bounds the configuration's +/// size and the work the authorizer does per request. +const MAX_RESOURCE_SCOPES_PER_GRANT: usize = 64; +/// The maximum number of resource scopes one node's grant set may carry. +const MAX_RESOURCE_SCOPES_TOTAL: usize = 4096; const METRIC_NAMES: &[&str] = &[ "executions_accepted", "rejected_route", @@ -121,6 +131,26 @@ pub struct TlsFiles { pub client_ca: PathBuf, } +/// A resource-scoped narrowing of one operation a principal already holds. +/// +/// A scope is a name, a kind, and an identifier — nothing more. It cannot +/// grant an operation the grant does not hold, and it cannot widen a grant: +/// the store's `principal_id` fences stay authoritative for ownership, so a +/// scope only ever removes access. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ResourceScope { + /// The operation this scope narrows. Must be an operation the same grant + /// already holds. + pub operation: String, + /// The resource kind this scope names: `execution`, `blob`, `workspace`, + /// or `artifact`. + pub resource_kind: String, + /// The string form of the resource identifier, parsed back into the typed + /// variant its kind names. + pub resource_id: String, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct ClientGrant { @@ -128,6 +158,18 @@ pub struct ClientGrant { /// Lowercase hex SHA-256 digest of the verified leaf certificate DER. pub certificate_sha256: String, pub operations: Vec, + /// Optional resource-scoped narrowing of the operations above. + /// + /// Absent or empty means the grant is exactly as broad as its operation + /// list, which is the meaning every configuration written before + /// resource scopes existed has. A scope narrows one operation and one + /// resource kind; it never grants an operation the grant does not hold. + /// + /// `deny_unknown_fields` on this struct is deliberate: an older node + /// reading a configuration that carries a scope refuses to start rather + /// than silently ignoring the narrowing the operator wrote. + #[serde(default)] + pub resource_scopes: Vec, } #[derive(Debug, Clone, Serialize)] @@ -253,6 +295,7 @@ impl OperatorConfig { return Err(OperationsError::Config); } let mut fingerprints = HashSet::new(); + let mut total_scopes = 0usize; for grant in &self.clients { if PrincipalId::new(grant.principal_id.clone()).is_err() || grant.certificate_sha256.len() != 64 @@ -269,6 +312,43 @@ impl OperatorConfig { { return Err(OperationsError::Config); } + total_scopes += grant.resource_scopes.len(); + if total_scopes > MAX_RESOURCE_SCOPES_TOTAL + || grant.resource_scopes.len() > MAX_RESOURCE_SCOPES_PER_GRANT + { + return Err(OperationsError::Config); + } + // A scope narrows an operation the grant already holds, so the + // grant's own operation list is the reference a scope is checked + // against. Every name in that list already resolved above. + let held: HashSet = grant + .operations + .iter() + .filter_map(|name| operation(name)) + .collect(); + let mut seen: HashSet<(Operation, ResourceKind, ResourceId)> = HashSet::new(); + for scope in &grant.resource_scopes { + let Some(narrowed) = operation(&scope.operation) else { + return Err(OperationsError::Config); + }; + let Some(kind) = resource_kind(&scope.resource_kind) else { + return Err(OperationsError::Config); + }; + // A scope for an operation the grant does not hold would be a + // grant written in the wrong place; a scope for a kind that + // operation never names could never be consulted and would + // narrow nothing while the operator believed it did. Both are + // configuration errors, not silently ignored entries. + if !held.contains(&narrowed) || !narrowed.resource_kinds().contains(&kind) { + return Err(OperationsError::Config); + } + let Some(identifier) = parse_resource_id(kind, &scope.resource_id) else { + return Err(OperationsError::Config); + }; + if !seen.insert((narrowed, kind, identifier)) { + return Err(OperationsError::Config); + } + } } let _ = self.tls_config()?; if let Some(settings) = &self.host_telemetry { @@ -350,6 +430,21 @@ impl OperatorConfig { for client in clients { if let Some(object) = client.as_object_mut() { object.insert("certificate_sha256".into(), "[REDACTED]".into()); + // The scope's identifier names the exact resource the + // operator confined the grant to — the same class of + // value as the certificate fingerprint. The operation and + // kind stay visible, because the shape of the narrowing + // is what an operator reads; the identifier does not. + if let Some(scopes) = object + .get_mut("resource_scopes") + .and_then(serde_json::Value::as_array_mut) + { + for scope in scopes { + if let Some(scope_object) = scope.as_object_mut() { + scope_object.insert("resource_id".into(), "[REDACTED]".into()); + } + } + } } } } @@ -381,7 +476,7 @@ impl OperatorConfig { &self, ) -> Result<(FingerprintPrincipalResolver, GrantAuthorizer), OperationsError> { let mut identities = Vec::with_capacity(self.clients.len()); - let mut grants = HashMap::new(); + let mut grants: HashMap = HashMap::new(); for client in &self.clients { let id = PrincipalId::new(client.principal_id.clone()) .map_err(|_| OperationsError::Config)?; @@ -391,11 +486,33 @@ impl OperatorConfig { .iter() .filter_map(|name| operation(name)) .collect(); - grants.insert(id, allowed); + let mut scopes: HashMap<(Operation, ResourceKind), HashSet> = + HashMap::new(); + for scope in &client.resource_scopes { + // Parsing is strict here even though `validate` already + // refused the same shapes: `principals` is what the daemon + // calls, and a node that could not build its grant table must + // refuse to start rather than start with a permissive one. + let narrowed = operation(&scope.operation).ok_or(OperationsError::Config)?; + let kind = resource_kind(&scope.resource_kind).ok_or(OperationsError::Config)?; + let identifier = + parse_resource_id(kind, &scope.resource_id).ok_or(OperationsError::Config)?; + scopes + .entry((narrowed, kind)) + .or_default() + .insert(identifier); + } + grants.insert( + id, + PrincipalGrant { + operations: allowed, + scopes, + }, + ); } Ok(( FingerprintPrincipalResolver::new(identities), - GrantAuthorizer(grants), + GrantAuthorizer { grants }, )) } @@ -404,16 +521,97 @@ impl OperatorConfig { } } -pub struct GrantAuthorizer(HashMap>); +/// One principal's grant: the operations it holds, and the resource scopes +/// that narrow them. +/// +/// The scope table is keyed by `(operation, resource kind)` and holds typed +/// identifiers, so a scope for `Blob` can never be compared against an +/// `Execution` even if the configuration tried. +struct PrincipalGrant { + operations: HashSet, + scopes: HashMap<(Operation, ResourceKind), HashSet>, +} + +/// The per-principal grant table the node authorizes against. +/// +/// The grant table is derived entirely from the operator configuration: the +/// decision it makes is a lookup, never a store round trip, so authorization +/// keeps the in-memory shape it has always had and never acquires a lock or +/// an ordering dependency it did not have before. +pub struct GrantAuthorizer { + grants: HashMap, +} impl Authorizer for GrantAuthorizer { fn authorize(&self, principal: &NodePrincipal, operation: Operation) -> bool { - self.0 + self.grants .get(&principal.id) - .is_some_and(|allowed| allowed.contains(&operation)) + .is_some_and(|grant| grant.operations.contains(&operation)) + } + + /// The resource-scoped decision. + /// + /// The rule, in order: + /// + /// 1. the operation grant must be present — a scope never grants an + /// operation the principal does not hold; + /// 2. a request that carries no resource falls back to the operation-level + /// grant, exactly as before resource scopes existed; + /// 3. when a scope is configured for that operation *and* that resource + /// kind, the resource must be inside it; + /// 4. otherwise the operation-level grant stands. + /// + /// Rule 3 is per `(operation, kind)`: scoping `Execute` against + /// `Execution` does not scope `Execute` against `Workspace`. An operator + /// who wants both constrained writes a scope for each. + /// + /// This decision can only narrow. It never asks who owns the resource, so + /// the store's `principal_id` fences remain the authority on ownership: a + /// scope that names another principal's resource lets the request reach + /// the store, and the store refuses it there. + fn authorize_request(&self, principal: &NodePrincipal, request: &OperationRequest) -> bool { + if !self.authorize(principal, request.operation) { + return false; + } + let Some(resource) = request.resource.as_ref() else { + return true; + }; + let Some(grant) = self.grants.get(&principal.id) else { + return false; + }; + match grant.scopes.get(&(request.operation, resource.kind())) { + Some(allowed) => allowed.contains(resource), + None => true, + } } } +/// The resource kinds a scope may name. +fn resource_kind(name: &str) -> Option { + Some(match name { + "execution" => ResourceKind::Execution, + "blob" => ResourceKind::Blob, + "workspace" => ResourceKind::Workspace, + "artifact" => ResourceKind::Artifact, + _ => return None, + }) +} + +/// Parse a scope's identifier into the typed variant its kind names. +/// +/// The identifier is the string form of the corresponding `ResourceId` +/// variant, and it is parsed back through the same constructors the request +/// path uses, so a configuration cannot name a resource the request path +/// would refuse to resolve. +fn parse_resource_id(kind: ResourceKind, value: &str) -> Option { + Some(match kind { + ResourceKind::Execution => ResourceId::Execution(ExecutionId::new(value.to_owned()).ok()?), + ResourceKind::Blob => ResourceId::Blob(BlobDigest::parse(value.to_owned()).ok()?), + ResourceKind::Workspace => ResourceId::Workspace(WorkspaceId::new(value.to_owned()).ok()?), + ResourceKind::Artifact => ResourceId::Artifact(ArtifactId::new(value.to_owned()).ok()?), + }) +} + fn operation(name: &str) -> Option { Some(match name { "capabilities" => Operation::Capabilities, @@ -1213,6 +1411,7 @@ mod tests { principal_id: "controller".into(), certificate_sha256: "ab".repeat(32), operations: vec!["status".into()], + resource_scopes: Vec::new(), }], host_telemetry: None, } @@ -1227,6 +1426,192 @@ mod tests { assert!(encoded.contains("[REDACTED]")); } + /// The printed configuration must not carry the resource a scope names, + /// the same way it does not carry the private key path or the certificate + /// fingerprint. The shape of the narrowing stays readable: the operator + /// reads which operation and which kind were confined. + #[test] + fn the_printed_configuration_redacts_resource_scope_identifiers() { + let temp = TempDir::new().unwrap(); + let mut config = config(temp.path()); + config.clients[0].operations = vec!["blob-read".into()]; + config.clients[0].resource_scopes = vec![ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: "cd".repeat(32), + }]; + let encoded = config.redacted_json().unwrap(); + assert!(!encoded.contains(&"cd".repeat(32))); + assert!(!encoded.contains("super-secret-key.pem")); + assert!(!encoded.contains(&"ab".repeat(32))); + assert!(encoded.contains("[REDACTED]")); + assert!(encoded.contains("blob-read")); + assert!(encoded.contains("blob")); + } + + /// A scope that narrows an operation the grant already holds is accepted. + #[test] + fn a_resource_scope_that_narrows_a_held_operation_is_accepted() { + let temp = TempDir::new().unwrap(); + let mut config = installed_config(temp.path()); + config.clients[0].operations = vec!["blob-read".into()]; + config.clients[0].resource_scopes = vec![ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: "a".repeat(64), + }]; + assert!(config.validate().is_ok()); + } + + /// Every malformed scope is a configuration error. The node refuses to + /// start rather than degrade to a decision that ignores the scope. + #[test] + fn a_malformed_resource_scope_is_refused_by_the_configuration() { + let cases: Vec<(&str, ResourceScope)> = vec![ + ( + "an unknown operation name", + ResourceScope { + operation: "blob-readd".into(), + resource_kind: "blob".into(), + resource_id: "a".repeat(64), + }, + ), + ( + "an unknown resource kind", + ResourceScope { + operation: "blob-read".into(), + resource_kind: "blobs".into(), + resource_id: "a".repeat(64), + }, + ), + ( + "a malformed identifier", + ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: "not-a-digest".into(), + }, + ), + ( + "a scope for an operation the grant does not hold", + ResourceScope { + operation: "blob-write".into(), + resource_kind: "blob".into(), + resource_id: "a".repeat(64), + }, + ), + ( + "a scope for a kind the operation never names", + ResourceScope { + operation: "blob-read".into(), + resource_kind: "execution".into(), + resource_id: "exec-1".into(), + }, + ), + ( + "a scope for an operation that names no resource at all", + ResourceScope { + operation: "status".into(), + resource_kind: "execution".into(), + resource_id: "exec-1".into(), + }, + ), + ]; + for (label, scope) in cases { + let temp = TempDir::new().unwrap(); + let mut config = installed_config(temp.path()); + config.clients[0].operations = vec!["blob-read".into(), "status".into()]; + config.clients[0].resource_scopes = vec![scope]; + assert!(config.validate().is_err(), "{label} must be refused"); + } + } + + /// The same scope twice is a duplicate, not a redundancy to be tolerated. + #[test] + fn a_duplicate_resource_scope_is_refused_by_the_configuration() { + let temp = TempDir::new().unwrap(); + let mut config = installed_config(temp.path()); + config.clients[0].operations = vec!["blob-read".into()]; + config.clients[0].resource_scopes = vec![ + ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: "a".repeat(64), + }, + ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: "a".repeat(64), + }, + ]; + assert!(config.validate().is_err()); + } + + /// One grant cannot carry more scopes than the per-grant cap. + #[test] + fn too_many_resource_scopes_in_one_grant_are_refused() { + let temp = TempDir::new().unwrap(); + let mut config = installed_config(temp.path()); + config.clients[0].operations = vec!["blob-read".into()]; + config.clients[0].resource_scopes = (0..=MAX_RESOURCE_SCOPES_PER_GRANT) + .map(|index| ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: format!("{index:064x}"), + }) + .collect(); + assert!(config.validate().is_err()); + } + + /// The node's grant set cannot carry more scopes than the per-node cap, + /// even when every individual grant is within its own cap. + #[test] + fn too_many_resource_scopes_across_the_node_are_refused() { + let temp = TempDir::new().unwrap(); + let mut config = installed_config(temp.path()); + let base = config.clients.remove(0); + let grants = MAX_RESOURCE_SCOPES_TOTAL / MAX_RESOURCE_SCOPES_PER_GRANT + 1; + for grant in 0..grants { + let mut client = base.clone(); + client.principal_id = format!("controller-{grant:02}"); + client.certificate_sha256 = format!("{grant:064x}"); + client.operations = vec!["blob-read".into()]; + client.resource_scopes = (0..MAX_RESOURCE_SCOPES_PER_GRANT) + .map(|index| ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: format!("{:064x}", (grant as u64) * 1_000 + index as u64), + }) + .collect(); + config.clients.push(client); + } + assert!(config.validate().is_err()); + } + + /// A configuration written before resource scopes existed still validates. + #[test] + fn a_configuration_written_before_resource_scopes_still_validates() { + let temp = TempDir::new().unwrap(); + let config = installed_config(temp.path()); + assert!(config.clients[0].resource_scopes.is_empty()); + assert!(config.validate().is_ok()); + } + + /// The grant table the daemon builds refuses a scope it cannot parse, + /// even if `validate` was never called on the way to it. + #[test] + fn the_grant_table_refuses_a_scope_it_cannot_parse() { + let temp = TempDir::new().unwrap(); + let mut config = installed_config(temp.path()); + config.clients[0].operations = vec!["blob-read".into()]; + config.clients[0].resource_scopes = vec![ResourceScope { + operation: "blob-read".into(), + resource_kind: "blob".into(), + resource_id: "not-a-digest".into(), + }]; + assert!(config.principals().is_err()); + } + /// A configuration document in the shape the loader accepts. fn config_json(root: &Path) -> serde_json::Value { serde_json::json!({ diff --git a/crates/eggwork-server/tests/resource_scoped_authorization.rs b/crates/eggwork-server/tests/resource_scoped_authorization.rs new file mode 100644 index 0000000..aa6441d --- /dev/null +++ b/crates/eggwork-server/tests/resource_scoped_authorization.rs @@ -0,0 +1,408 @@ +//! Resource-scoped authorization: the configuration shape, the decision rule, +//! and the boundaries the decision may not cross. +//! +//! These tests drive the authorizer through the same public surface the +//! daemon uses — the operator configuration's grant table — so they need no +//! filesystem, no process, no TLS handshake, and no host platform. The +//! end-to-end proof that a scope cannot reach another principal's resource +//! lives in the server's own test module, which starts a real node; this +//! file pins the decision itself. +//! +//! Nothing in this file may use `/bin/sh`, `std::os::unix`, or a Unix-only +//! mode: the target is compiled and run by the Windows job in CI. + +use eggwork_core::{BlobDigest, ExecutionId, PrincipalId, WorkspaceId}; +use eggwork_server::{ + Authorizer, NodePrincipal, Operation, OperationRequest, ResourceId, + operations::{ClientGrant, GrantAuthorizer, OperatorConfig, ResourceScope, TlsFiles}, +}; +use serde::Deserialize; +use serde_json::json; +use std::path::PathBuf; + +/// Build the node's grant table from the client grants. +/// +/// `OperatorConfig::principals` reads only the client grants: the paths and +/// the TLS material are never touched, so a grant table can be built here +/// without a node, a certificate, or a directory. +fn grant_table(clients: Vec) -> GrantAuthorizer { + OperatorConfig { + schema_version: 1, + node_id: "node-test".into(), + bind: "127.0.0.1:0".into(), + execution_root: PathBuf::from("unused"), + database_path: PathBuf::from("unused"), + blob_root: PathBuf::from("unused"), + blob_quota_bytes: 1, + workspace_root: PathBuf::from("unused"), + workspace_quota_bytes: 1, + max_active_executions: 1, + lease_ttl_seconds: 1, + sandbox_helper: None, + tls: TlsFiles { + certificate_chain: PathBuf::from("unused"), + private_key: PathBuf::from("unused"), + client_ca: PathBuf::from("unused"), + }, + clients, + host_telemetry: None, + } + .principals() + .expect("the grant table builds") + .1 +} + +fn client( + principal: &str, + fingerprint: u64, + operations: &[&str], + resource_scopes: Vec, +) -> ClientGrant { + ClientGrant { + principal_id: principal.into(), + certificate_sha256: format!("{fingerprint:064x}"), + operations: operations.iter().map(|name| (*name).to_string()).collect(), + resource_scopes, + } +} + +fn scope(operation: &str, resource_kind: &str, resource_id: &str) -> ResourceScope { + ResourceScope { + operation: operation.into(), + resource_kind: resource_kind.into(), + resource_id: resource_id.into(), + } +} + +fn principal(name: &str) -> NodePrincipal { + NodePrincipal { + id: PrincipalId::new(name.to_owned()).expect("principal id"), + } +} + +fn request(operation: Operation, resource: Option) -> OperationRequest { + OperationRequest { + operation, + resource, + } +} + +fn digest_a() -> String { + "a".repeat(64) +} + +fn digest_b() -> String { + "b".repeat(64) +} + +fn blob(value: &str) -> ResourceId { + ResourceId::Blob(BlobDigest::parse(value.to_owned()).expect("blob digest")) +} + +fn execution(value: &str) -> ResourceId { + ResourceId::Execution(ExecutionId::new(value.to_owned()).expect("execution id")) +} + +fn workspace(value: &str) -> ResourceId { + ResourceId::Workspace(WorkspaceId::new(value.to_owned()).expect("workspace id")) +} + +/// A grant that carries no scope keeps exactly its operation-level meaning. +#[test] +fn a_grant_without_resource_scopes_keeps_its_operation_level_meaning() { + let authorizer = grant_table(vec![client( + "controller", + 1, + &["status", "blob-read"], + vec![], + )]); + let controller = principal("controller"); + assert!(authorizer.authorize_request(&controller, &request(Operation::Status, None))); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::BlobRead, Some(blob(&digest_a()))) + )); + assert!(!authorizer.authorize_request(&controller, &request(Operation::Execute, None))); +} + +/// Two principals, the same operations, different scopes: the scope is what +/// separates them, and the operation grant alone does not. +#[test] +fn two_principals_with_the_same_operations_and_different_scopes_get_different_answers() { + let authorizer = grant_table(vec![ + client( + "controller-a", + 1, + &["blob-read"], + vec![scope("blob-read", "blob", &digest_a())], + ), + client( + "controller-b", + 2, + &["blob-read"], + vec![scope("blob-read", "blob", &digest_b())], + ), + ]); + let a = principal("controller-a"); + let b = principal("controller-b"); + assert!( + authorizer.authorize_request(&a, &request(Operation::BlobRead, Some(blob(&digest_a())))) + ); + assert!( + !authorizer.authorize_request(&a, &request(Operation::BlobRead, Some(blob(&digest_b())))) + ); + assert!( + authorizer.authorize_request(&b, &request(Operation::BlobRead, Some(blob(&digest_b())))) + ); + assert!( + !authorizer.authorize_request(&b, &request(Operation::BlobRead, Some(blob(&digest_a())))) + ); +} + +/// The scope is consulted. Without this the decision would be the +/// operation-level grant alone, and the digest the scope does not name would +/// be allowed. +#[test] +fn a_resource_scope_narrows_the_operation_grant_it_names() { + let authorizer = grant_table(vec![client( + "controller", + 1, + &["blob-read"], + vec![scope("blob-read", "blob", &digest_a())], + )]); + let controller = principal("controller"); + // The operation grant alone would allow both digests. + assert!(authorizer.authorize(&controller, Operation::BlobRead)); + // The scope refuses the digest it does not name, and allows the one it + // does. + assert!(!authorizer.authorize_request( + &controller, + &request(Operation::BlobRead, Some(blob(&digest_b()))) + )); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::BlobRead, Some(blob(&digest_a()))) + )); +} + +/// A scope cannot grant an operation the principal does not hold — not even +/// when the grant list is misconfigured to name an operation it does not +/// hold. +#[test] +fn a_scope_never_grants_an_operation_the_principal_does_not_hold() { + let authorizer = grant_table(vec![client( + "controller", + 1, + &["status"], + vec![scope("blob-read", "blob", &digest_a())], + )]); + let controller = principal("controller"); + assert!(!authorizer.authorize_request( + &controller, + &request(Operation::BlobRead, Some(blob(&digest_a()))) + )); + assert!(!authorizer.authorize_request(&controller, &request(Operation::BlobRead, None))); +} + +/// A scope narrows the operation *and* the resource kind it names, and only +/// those. `blob-write` has no scope of its own, so it falls back to the +/// operation grant. +#[test] +fn a_scope_narrows_only_the_operation_and_kind_it_names() { + let authorizer = grant_table(vec![client( + "controller", + 1, + &["blob-read", "blob-write"], + vec![scope("blob-read", "blob", &digest_a())], + )]); + let controller = principal("controller"); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::BlobRead, Some(blob(&digest_a()))) + )); + assert!(!authorizer.authorize_request( + &controller, + &request(Operation::BlobRead, Some(blob(&digest_b()))) + )); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::BlobWrite, Some(blob(&digest_a()))) + )); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::BlobWrite, Some(blob(&digest_b()))) + )); +} + +/// A request that carries no resource falls back to the operation-level +/// grant, exactly as it did before resource scopes existed. +#[test] +fn a_request_without_a_resource_falls_back_to_the_operation_grant() { + let authorizer = grant_table(vec![client( + "controller", + 1, + &["blob-read"], + vec![scope("blob-read", "blob", &digest_a())], + )]); + let controller = principal("controller"); + assert!(authorizer.authorize_request(&controller, &request(Operation::BlobRead, None))); +} + +/// `execute` names two kinds — the execution and the workspace — and a scope +/// for one does not narrow the other. +#[test] +fn an_execute_scope_names_the_execution_and_the_workspace_separately() { + let authorizer = grant_table(vec![client( + "controller", + 1, + &["execute"], + vec![ + scope("execute", "execution", "exec-1"), + scope("execute", "workspace", "ws-1"), + ], + )]); + let controller = principal("controller"); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::Execute, Some(execution("exec-1"))) + )); + assert!(!authorizer.authorize_request( + &controller, + &request(Operation::Execute, Some(execution("exec-2"))) + )); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::Execute, Some(workspace("ws-1"))) + )); + assert!(!authorizer.authorize_request( + &controller, + &request(Operation::Execute, Some(workspace("ws-2"))) + )); +} + +/// The scope's identifier is the string form of the typed resource, so the +/// configuration and the request path agree on what an identifier is. +#[test] +fn a_scope_identifier_is_the_string_form_of_the_typed_resource() { + let authorizer = grant_table(vec![client( + "controller", + 1, + &["observe"], + vec![scope("observe", "execution", "exec-1")], + )]); + let controller = principal("controller"); + let resolved = ResourceId::Execution(ExecutionId::new("exec-1".to_owned()).unwrap()); + assert!( + authorizer.authorize_request(&controller, &request(Operation::Observe, Some(resolved))) + ); + let other = ResourceId::Execution(ExecutionId::new("exec-2".to_owned()).unwrap()); + assert!(!authorizer.authorize_request(&controller, &request(Operation::Observe, Some(other)))); +} + +/// The authorizer decides the scope; ownership stays with the store. +/// +/// A scope names a resource the principal may not own. The authorizer cannot +/// know who owns it — it consults a configuration-derived set only, and never +/// the store — so it lets the request reach the store, and the store's +/// `principal_id` fence refuses it there. The authorizer must not pretend to +/// be that fence. +#[test] +fn the_authorizer_decides_the_scope_and_leaves_ownership_to_the_store() { + let authorizer = grant_table(vec![client( + "controller-b", + 1, + &["observe"], + vec![scope("observe", "execution", "exec-owned-by-controller-a")], + )]); + let b = principal("controller-b"); + assert!(authorizer.authorize_request( + &b, + &request( + Operation::Observe, + Some(execution("exec-owned-by-controller-a")) + ) + )); +} + +/// The residual boundary, stated as a test: a broad `blob-read` grant with no +/// scope still reaches every digest. Blob storage is content-addressed and +/// shared, so a blob has no owner to fence it; scoping is the only boundary +/// available for it, and it is opt-in. +#[test] +fn without_a_blob_scope_the_blob_boundary_is_the_operation_grant() { + let authorizer = grant_table(vec![client("controller", 1, &["blob-read"], vec![])]); + let controller = principal("controller"); + assert!(authorizer.authorize_request( + &controller, + &request(Operation::BlobRead, Some(blob(&digest_b()))) + )); +} + +/// A configuration written before resource scopes existed still loads. +#[test] +fn a_configuration_written_before_resource_scopes_still_loads() { + let grant: ClientGrant = serde_json::from_value(json!({ + "principal_id": "controller", + "certificate_sha256": format!("{:064x}", 1), + "operations": ["status"], + })) + .expect("the older grant loads"); + assert!(grant.resource_scopes.is_empty()); +} + +/// An unknown field inside a scope is refused rather than ignored. +#[test] +fn an_unknown_field_in_a_resource_scope_is_refused() { + let document = json!({ + "principal_id": "controller", + "certificate_sha256": format!("{:064x}", 1), + "operations": ["blob-read"], + "resource_scopes": [{ + "operation": "blob-read", + "resource_kind": "blob", + "resource_id": digest_a(), + "unexpected": true, + }], + }); + assert!(serde_json::from_value::(document).is_err()); +} + +/// The shape an older node's `ClientGrant` had: no `resource_scopes` field, +/// and `deny_unknown_fields` on the struct. +/// +/// This is a simulation of the older node's deserializer, not an older +/// binary: the refusal it demonstrates is the refusal an older node makes, +/// because the older struct had exactly these fields and exactly this +/// attribute. The fields are declared so the shape matches; this test never +/// reads them. +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +#[allow(dead_code)] +struct OlderClientGrant { + principal_id: String, + certificate_sha256: String, + operations: Vec, +} + +/// An older node refuses a configuration that carries a resource scope. +/// +/// This is correct behaviour, not a defect: a node that silently ignored the +/// narrowing the operator wrote would be a node with a wider boundary than +/// its configuration states. +#[test] +fn an_older_node_refuses_a_configuration_that_carries_a_resource_scope() { + let document = json!({ + "principal_id": "controller", + "certificate_sha256": format!("{:064x}", 1), + "operations": ["blob-read"], + "resource_scopes": [{ + "operation": "blob-read", + "resource_kind": "blob", + "resource_id": digest_a(), + }], + }); + // The current node reads it. + assert!(serde_json::from_value::(document.clone()).is_ok()); + // An older node's deserializer refuses it. + assert!(serde_json::from_value::(document).is_err()); +} diff --git a/examples/eggworkd.example.json b/examples/eggworkd.example.json index 244bd24..8e5f371 100644 --- a/examples/eggworkd.example.json +++ b/examples/eggworkd.example.json @@ -34,6 +34,34 @@ "workspace-create", "artifact-read" ] + }, + { + "principal_id": "controller-02", + "certificate_sha256": "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210", + "operations": [ + "capabilities", + "status", + "execute", + "observe", + "blob-read" + ], + "resource_scopes": [ + { + "operation": "execute", + "resource_kind": "execution", + "resource_id": "batch-2026-10-25-001" + }, + { + "operation": "observe", + "resource_kind": "execution", + "resource_id": "batch-2026-10-25-001" + }, + { + "operation": "blob-read", + "resource_kind": "blob", + "resource_id": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08" + } + ] } ] } diff --git a/plans/closure/security-isolation-resource/005c-status.md b/plans/closure/security-isolation-resource/005c-status.md new file mode 100644 index 0000000..1d01ad8 --- /dev/null +++ b/plans/closure/security-isolation-resource/005c-status.md @@ -0,0 +1,562 @@ +# Security M005c — Resource-scoped authorization corrective + +Status: closing — implementation is in the working tree; the coordinator runs +the full pre-submit gate and sets the final status. + +Source implementation plan: +`plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md` + +Source corrective addendum (authoritative where it disagrees with the plan): +`plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` +(finding SI-3) + +Source roadmap: +`plans/subsystems/security-isolation-resource-roadmap.md` (M005c now +"implemented") + +Deciding ADR: +`plans/adrs/ADR-0007-resource-scoped-authorization.md` — **accepted** +(2026-10-25), **Option A: implement resource-scoped grants**. The ADR's +`## Decision` section states eleven numbered constraints; this implementation +follows them as written, and §2 below maps each of them to the code. + +Reviewed repository head before implementation: `af5a217` +(`af5a21709573e20f26eca77df83bd5560c46e936`) +Implementation commit: **none** — the working tree was left dirty for the +coordinator to review and commit; no commit was made by the implementing +agent. + +Branch: `corrective/interrogation-batch-2026-10`. + +> A parallel worker was editing `crates/eggwork-runner/**`, +> `crates/eggwork-core/src/lib.rs`, `architecture/runner-execution.md`, and +> `architecture/core-domain.md` in the same tree during this work. Nothing in +> those paths was touched here. The verification below is therefore scoped to +> `eggwork-server` and its documentation; the workspace-wide gate is the +> coordinator's. + +## 1. Executive finding + +The boundary is now real, and the node no longer presents a mechanism as +available while it is inert. `GrantAuthorizer` implements the +resource-aware `authorize_request` hook that `dispatch` has always called, so +the typed `ResourceId` that every request carries is consulted instead of +being dropped on the floor. + +A grant may now carry an optional, additive, bounded list of **resource +scopes**. A scope names an operation, a resource kind, and a resource +identifier, and it may only narrow an operation the same grant already +holds. The decision is a lookup in a configuration-derived set: it never asks +the store who owns the resource, so authorization keeps the in-memory, +lock-free shape it has always had and acquires no ordering dependency it did +not have before. + +Two properties are load-bearing and both are proven below rather than +asserted: + +- **A scope can only narrow.** It cannot grant an operation the principal does + not hold, and it cannot widen one it does. The store's `principal_id` + fences remain authoritative for ownership, so a scope that names another + principal's execution, workspace, or artifact lets the request reach the + store — and the store refuses it there. The end-to-end test shows exactly + that: the authorizer *allows* the intruder's request (its scope names the + resource) and the store refuses it. +- **A denial reveals nothing.** A resource-scoped denial is the same + `403 forbidden` / "operation is not authorized" as an operation-level + denial, and is byte-identical for a resource that exists and one that does + not. The caller cannot tell which. + +Configuration fails closed at load time. Every malformed scope — unknown +operation name, unknown resource kind, malformed identifier, a scope for an +operation the grant does not hold, a scope for a kind that operation never +names, a duplicate scope, and an over-cap grant count — is a configuration +error, and the node refuses to start rather than degrade to a permissive +decision. + +**The blob boundary is not closed.** Blob storage is content-addressed and +shared, so a blob has no owner to fence it. A blob scope is an explicit +digest list an operator must configure, and a grant with no blob scope is +still operation-wide: a broad `BlobRead` still reaches any known digest. §10 +states this plainly, and it is stated the same way in the threat model. + +## 2. The ADR's decision constraints, and where each one lives + +| ADR constraint | Implementation | Evidence | +|---|---|---| +| 1. Optional, additive scope list; a grant without scopes keeps today's meaning; the identifier is the string form of the `ResourceId` variant and is parsed back into the typed variant | `ClientGrant.resource_scopes` (`operations.rs`, `#[serde(default)]`), `ResourceScope` (`operations.rs`), `parse_resource_id` (`operations.rs`) | `a_configuration_written_before_resource_scopes_still_loads`, `a_scope_identifier_is_the_string_form_of_the_typed_resource` | +| 2. The store remains authoritative for ownership; a scope may only narrow | `GrantAuthorizer::authorize_request` consults a configuration set only; `store.rs` untouched | `a_resource_scope_cannot_reach_a_foreign_principal_resource` | +| 3. Blob has no owner; a blob scope is an explicit digest list | `ResourceKind::Blob` scopes hold typed `BlobDigest`s; no ownership comparison exists for blobs | `without_a_blob_scope_the_blob_boundary_is_the_operation_grant` | +| 4. The scope applies to the six handler-level call sites *and* to the operations `resource_for_path` resolves | `resource_for_path` unchanged and still called by `dispatch`; the six `authorize_resource` sites unchanged and still called | `a_resource_scope_cannot_reach_a_foreign_principal_resource` (dispatch path: `Observe`), `a_resource_scoped_denial_is_indistinguishable_from_an_operation_level_denial` (dispatch path: `BlobRead`) | +| 5. The decision consults a configuration-derived set only; no new lock, no ordering dependency | `GrantAuthorizer` holds a `HashMap` built once at startup; the decision path takes no lock and touches no store | Code inspection of `GrantAuthorizer::authorize_request` plus §9's command output; no store call appears on the authorization path | +| 6. Configuration fails closed at load time; every error class is a configuration error; per-grant and per-node caps validated in `OperatorConfig::validate`; `deny_unknown_fields` kept; the new field is `#[serde(default)]` | `OperatorConfig::validate` scope block; `MAX_RESOURCE_SCOPES_PER_GRANT = 64`, `MAX_RESOURCE_SCOPES_TOTAL = 4096`; `principals()` parses strictly as a second gate | `a_malformed_resource_scope_is_refused_by_the_configuration`, `a_duplicate_resource_scope_is_refused_by_the_configuration`, `too_many_resource_scopes_in_one_grant_are_refused`, `too_many_resource_scopes_across_the_node_are_refused`, `the_grant_table_refuses_a_scope_it_cannot_parse` | +| 7. Authorization still precedes resource resolution; a resource-scoped denial is indistinguishable from an operation-level denial and from a missing resource; the store's fences are not weakened | `dispatch` order unchanged; the denial bodies are the same `403 forbidden` | `a_resource_scoped_denial_is_indistinguishable_from_an_operation_level_denial` | +| 8. No wire change; `API_SCHEMA_VERSION` and capability names unchanged | No wire type touched; `crates/eggwork-core` untouched by this milestone | §9's `cargo check` and the full `eggwork-server` test suite, including `tests/shared_contract_ownership.rs` (`the_schema_version_is_declared_exactly_once_in_the_workspace`) and `tests/release_contract.rs` (36 tests) | +| 9. No policy language, no rule engine, no role system, no IAM | A scope is exactly `(operation, kind, identifier)`; there is no expression, no combinator, no inheritance | Code inspection: `ResourceScope` has three `String` fields and no other type carries policy | +| 10. The `deny_unknown_fields` interaction is deliberate and documented | `ClientGrant` keeps `deny_unknown_fields`; documented in `architecture/operations-cli.md`, `architecture/server-node.md`, and §8 below | `an_older_node_refuses_a_configuration_that_carries_a_resource_scope` | + +## 3. The mechanism, and why + +**The grant table is configuration, not a query.** `GrantAuthorizer` now holds +`HashMap`, where a `PrincipalGrant` is the +principal's `HashSet` plus a scope table keyed by +`(Operation, ResourceKind)` holding typed `ResourceId`s. The table is built +once, at startup, by `OperatorConfig::principals()`. The decision is a +lookup. That is the whole reason the ADR's constraint 5 is satisfiable +without a lock or an ordering dependency: nothing on the authorization path +can ask a question that needs the store. + +**The scope is `(operation, kind, identifier)`, and the kind is derived from +the typed identifier.** A scope's `resource_id` is parsed through the same +constructors the request path uses — `ExecutionId::new`, `BlobDigest::parse`, +`WorkspaceId::new`, `ArtifactId::new` — so the configuration and the request +path cannot disagree about what an identifier is. The kind is then derived +from the typed variant (`ResourceId::kind`), so a scope written for `blob` +can never be compared against an execution, whatever the configuration says. + +**The decision rule is the ADR's rule, in the ADR's order.** Operation grant +present → resource present → scope configured for that `(operation, kind)` → +resource must be inside it → otherwise the operation-level grant stands. The +fallbacks are what make the change safe: a request that carries no resource +(the `dispatch`-level path for `Execute` and `WorkspaceCreate`, where the +resource is in the body) keeps the operation-level answer, and an +`(operation, kind)` pair with no scope keeps the operation-level answer. + +**The granularity is per `(operation, kind)`, and that is stated, not hidden.** +A scope for `Execute`/`Execution` does not narrow `Execute`/`Workspace`; a +scope for `BlobRead`/`Blob` does not narrow `BlobWrite`/`Blob`. This is the +ADR's rule 3 read literally. It is a real sharp edge for an operator — see +§11 finding 1 — so it is stated in the threat model, in both deep dives, and +in the `Review focus` section of `architecture/server-node.md`. + +**A scope for a kind the operation never names is a configuration error.** +`Operation::resource_kinds()` is the table of the kinds each operation's +requests can actually name, and it is exactly the set the request path +resolves. A scope outside that table could never be consulted, so accepting +it would mean accepting a narrowing the operator believes in and that does +not happen. Refusing it at load time is the same class of decision as +refusing an unknown operation name. + +## 4. Requirement-to-evidence matrix + +Acceptance criteria are numbered as in the implementation plan's §12. + +| # | Acceptance criterion | Evidence (command output or test) | +|---|---|---| +| 1 | The decided branch is recorded in ADR-0007 as accepted | `plans/adrs/ADR-0007-resource-scoped-authorization.md` § *Decision* — read, not modified by this milestone (the coordinator's commit `af5a217` already accepted it) | +| 2 | `architecture/overview.md` divergence #4 reflects the decided disposition | **Coordinator-owned.** The exact proposed row text is in §14 below; this milestone did not edit `architecture/overview.md` | +| 3 | The threat model states the boundary as it is after the change | `plans/security/threat-model.md` — invariant 5 and the "Authenticated unauthorized principal" row's remaining-boundary column, both rewritten in this change | +| 4 | The node does not present an inert mechanism | `a_resource_scope_narrows_the_operation_grant_it_names` — the test fails if the scope is ignored: it asserts the operation grant alone would allow a digest the scope then refuses | +| 5 | Authorization still precedes resource resolution, and an unauthorized caller cannot distinguish an existing resource from an absent one | `a_resource_scoped_denial_is_indistinguishable_from_an_operation_level_denial` — the three denials (out-of-scope existing, out-of-scope absent, operation-level) are asserted equal on `(status, code, message)`; the in-scope read is asserted to succeed, which shows the difference is the scope | +| 6 | The store's owner fences are not weakened, and the existing authorization matrix is green | `crates/eggwork-server/src/store.rs` is **unmodified** (see §7); the full `eggwork-server` suite is green, including `mtls_authorization_and_fixed_target_execution` and `resource_aware_authorizer_can_scope_blob_capability`, unchanged in their assertions | +| 7 | The configuration loader still fails closed on a malformed or unknown field | `an_unknown_field_in_a_resource_scope_is_refused`; the pre-existing `invalid_configuration_is_rejected_without_exposing_secret_material` remains green | +| 8 | No wire protocol change | No wire type touched. `crates/eggwork-core/src/lib.rs` is **not modified by this milestone**; `API_SCHEMA_VERSION` is untouched; `tests/shared_contract_ownership.rs` (6 tests) and `tests/release_contract.rs` (36 tests) are green | +| 9 | The full pre-submit gate is green on the reviewed head | **Not run by this agent** — the coordinator runs the full gate. The scoped verification in §9 was run and is green | +| 10 | A resource scope measurably narrows an operation grant, proven by a test that fails if the scope is ignored | `a_resource_scope_narrows_the_operation_grant_it_names` — asserts `authorize(principal, BlobRead) == true` while `authorize_request` for the unnamed digest is `false`; if the scope were ignored this assertion would fail | +| 11 | The owner fence holds for `Execution`, `Workspace`, and `Artifact`; blobs are governed by an explicit digest list | `a_resource_scope_cannot_reach_a_foreign_principal_resource` — for each of the three kinds the intruder's scope names the owner's resource, the authorizer *allows* the request (asserted), and the store refuses it (404 not found / 409 conflict / empty list) | +| 12 | A principal with no resource scopes receives exactly the operation-level decision | `a_grant_without_resource_scopes_keeps_its_operation_level_meaning` | +| 13 | Every configuration error class is refused at load time | `a_malformed_resource_scope_is_refused_by_the_configuration` (six classes), `a_duplicate_resource_scope_is_refused_by_the_configuration`, `too_many_resource_scopes_in_one_grant_are_refused`, `too_many_resource_scopes_across_the_node_are_refused` | + +Plan §9's required tests map onto the same evidence: + +| Plan §9 item | Test | Where | +|---|---|---| +| 1 (common) — the divergence table matches the code | `two_principals_with_the_same_operations_and_different_scopes_get_different_answers` | `tests/resource_scoped_authorization.rs` | +| 2 (common) — no regression in the existing boundary | the whole existing `eggwork-server` suite, unchanged assertions | §9 | +| 3 (common) — authorization still precedes resource resolution | `a_resource_scoped_denial_is_indistinguishable_from_an_operation_level_denial` | `lib.rs` | +| 4 — a resource scope actually narrows | `a_resource_scope_narrows_the_operation_grant_it_names` | `tests/resource_scoped_authorization.rs` | +| 5 — the owner fence holds | `a_resource_scope_cannot_reach_a_foreign_principal_resource` | `lib.rs` | +| 6 — blobs have no owner fence, and the scope says so | `without_a_blob_scope_the_blob_boundary_is_the_operation_grant` | `tests/resource_scoped_authorization.rs` | +| 7 — operation grants are never widened by a scope | `a_scope_never_grants_an_operation_the_principal_does_not_hold` | `tests/resource_scoped_authorization.rs` | +| 8 — no scope configured means today's behaviour | `a_grant_without_resource_scopes_keeps_its_operation_level_meaning` | `tests/resource_scoped_authorization.rs` | +| 9 — configuration failures are refused | five tests, see matrix row 13 | `operations.rs` | +| 10 — redaction | `the_printed_configuration_redacts_resource_scope_identifiers` | `operations.rs` | + +## 5. The new tests, and what each one proves + +### `crates/eggwork-server/tests/resource_scoped_authorization.rs` (new, 13 tests) + +Portable by construction: it drives the grant table through the public API +only, so it needs no filesystem, no process, no TLS handshake, and no host +platform. It compiles and runs on the Windows job. + +| Test | Proves | +|---|---| +| `a_grant_without_resource_scopes_keeps_its_operation_level_meaning` | A grant with no scopes answers exactly as before: the operation grant decides, and an ungranted operation is still refused | +| `two_principals_with_the_same_operations_and_different_scopes_get_different_answers` | The scope is reached and consulted: two principals with identical operation grants and different scopes get different answers for the same digest (plan §9 item 1) | +| `a_resource_scope_narrows_the_operation_grant_it_names` | **Non-vacuous.** The operation grant alone allows both digests; the scope refuses the digest it does not name and permits the one it does. If the scope were ignored, the `!authorize_request(...)` assertion fails | +| `a_scope_never_grants_an_operation_the_principal_does_not_hold` | A scope for an operation the grant does not hold grants nothing — *including* when the grant list is misconfigured that way, which is the case `validate` refuses | +| `a_scope_narrows_only_the_operation_and_kind_it_names` | The rule is per `(operation, kind)`: a `blob-read` scope does not narrow `blob-write` | +| `a_request_without_a_resource_falls_back_to_the_operation_grant` | A request with no resource keeps the operation-level answer | +| `an_execute_scope_names_the_execution_and_the_workspace_separately` | `execute` names two kinds; scoping one does not scope the other | +| `a_scope_identifier_is_the_string_form_of_the_typed_resource` | The configuration and the request path agree on what an identifier is: the scope's string is the same typed value the request path resolves | +| `the_authorizer_decides_the_scope_and_leaves_ownership_to_the_store` | The authorizer cannot know ownership and does not pretend to; it lets the request through so the store's fence can refuse it | +| `without_a_blob_scope_the_blob_boundary_is_the_operation_grant` | The residual boundary, stated as a test rather than in prose | +| `a_configuration_written_before_resource_scopes_still_loads` | An older configuration file still loads (`#[serde(default)]`) | +| `an_unknown_field_in_a_resource_scope_is_refused` | `deny_unknown_fields` reaches into the scope | +| `an_older_node_refuses_a_configuration_that_carries_a_resource_scope` | The deliberate older-node refusal (see §8 for what this does and does not prove) | + +### `crates/eggwork-server/src/operations.rs` (in-file, 8 new tests) + +| Test | Proves | +|---|---| +| `the_printed_configuration_redacts_resource_scope_identifiers` | `config print` prints neither the scope identifier, nor the private key path, nor the certificate fingerprint — while keeping the scope's operation and kind readable | +| `a_resource_scope_that_narrows_a_held_operation_is_accepted` | The valid shape is accepted, so the refusals below are not blanket refusals | +| `a_malformed_resource_scope_is_refused_by_the_configuration` | Six error classes, each refused: unknown operation name, unknown resource kind, malformed identifier, scope for an unheld operation, scope for a kind the operation never names, scope for an operation that names no resource | +| `a_duplicate_resource_scope_is_refused_by_the_configuration` | The same scope twice is a duplicate, not a tolerated redundancy | +| `too_many_resource_scopes_in_one_grant_are_refused` | The per-grant cap (64) is enforced | +| `too_many_resource_scopes_across_the_node_are_refused` | The per-node cap (4096) is enforced across 65 grants of 64 scopes each — every grant individually within its own cap | +| `a_configuration_written_before_resource_scopes_still_validates` | An older configuration file still passes `validate()` | +| `the_grant_table_refuses_a_scope_it_cannot_parse` | `principals()` — the gate the daemon actually calls — is a second, independent fail-closed gate | + +### `crates/eggwork-server/src/lib.rs` (in-file, 2 new end-to-end tests) + +Both start a real node over mTLS and drive it with the production client. + +| Test | Proves | +|---|---| +| `a_resource_scope_cannot_reach_a_foreign_principal_resource` | The owner fence holds for all three owned kinds. The intruder's scopes name the owner's execution, workspace, and artifact; the test asserts the **authorizer allows** each request (so the refusal is the store's, not the authorizer's), and that the store refuses them: 404 not found for the execution, 409 conflict for the workspace, an empty artifact list and 404 for the artifact. The owner's own reads succeed, so the difference is ownership and not a broken path | +| `a_resource_scoped_denial_is_indistinguishable_from_an_operation_level_denial` | The three denials are equal on `(status, code, message)`, and the in-scope digest is readable — so the difference is the scope and nothing else is disclosed | + +## 6. Verification actually run + +All commands used a private target directory so they did not fight the +parallel worker for the cargo lock: + +``` +export CARGO_TARGET_DIR=/home/sugarwookie/projects/eggwork/target-w1c +``` + +| Command | Result | +|---|---| +| `cargo fmt -p eggwork-server` | Applied (formatting only to the files this milestone owns) | +| `cargo fmt -p eggwork-server -- --check` | **Clean** — no output | +| `cargo clippy --locked -p eggwork-server --all-targets --all-features -- -D warnings` | **Clean** — `Finished dev profile`, no warnings. One `clippy::cloned_ref_to_slice_refs` finding in the new test was fixed (`std::slice::from_ref`) before the final run | +| `cargo test --locked -p eggwork-server --all-targets` | **243 passed, 0 failed** — 166 in `src/lib.rs`, 13 in the new `tests/resource_scoped_authorization.rs`, 7 in `artifact_capture_disposition`, 3 in `gc_preview_parity`, 12 in `host_telemetry`, 36 in `release_contract`, 6 in `shared_contract_ownership`, 0 in `installed_qualification` (all ignored), 0 in the `eggworkd` binary target | +| `cargo check --locked -p eggwork-server` | **Clean** — `Finished dev profile` | +| `python3 scripts/check_execution_ownership.py` | **Passed** — "execution ownership guard passed; approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)"; "negative scanner self-test passed; crate dependency direction passed" | +| `cargo run -p eggwork-server --bin eggworkd -- config print --config examples/eggworkd.example.json` | **Succeeded** — the printed document shows `"resource_id": "[REDACTED]"` for every scope, `"certificate_sha256": "[REDACTED]"`, and `"private_key": "[REDACTED]"` | +| `git diff --check` | **Clean** — no whitespace errors | + +**Not run by this agent** (the coordinator's full gate; the plan's §10 list): + +- `cargo fmt --all -- --check` — deliberately not run: `--all` would reformat + the parallel worker's in-flight files. `cargo fmt -p eggwork-server + -- --check` was run instead and is clean. +- `cargo clippy --locked --workspace --all-targets --all-features -- -D warnings` +- `cargo test --locked --workspace --all-targets` +- `cargo check --workspace` +- `python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release` + +The workspace-wide runs were not performed because the parallel worker had +`crates/eggwork-core` and `crates/eggwork-runner` in a temporarily +non-compiling state during part of this work; a workspace run at that moment +would have measured their in-flight edits, not this milestone. + +## 7. Compatibility review + +### Configuration compatibility + +- **An older configuration file still loads.** `ClientGrant.resource_scopes` + carries `#[serde(default)]`, so a document without the key deserializes + with an empty scope list. Proven by + `a_configuration_written_before_resource_scopes_still_loads` and + `a_configuration_written_before_resource_scopes_still_validates`. +- **An older node refuses a newer configuration that carries a scope.** This + is the deliberate `deny_unknown_fields` interaction the ADR names. The + refusal is correct: a node whose boundary is wider than its configuration + states is the defect this milestone exists to remove. The proof is + `an_older_node_refuses_a_configuration_that_carries_a_resource_scope`, and + it is a **simulation**, not an older binary: it deserializes the same + document with a local struct that has exactly the older `ClientGrant`'s + three fields and the same `#[serde(deny_unknown_fields)]` attribute, and + asserts that deserialization fails. No older `eggworkd` binary was built + or run. +- **A newer node accepts the newer configuration** — asserted in the same + test. +- **A typo inside a scope is refused**, not ignored + (`an_unknown_field_in_a_resource_scope_is_refused`), because `ResourceScope` + is itself `deny_unknown_fields`. + +### Public-API position + +Honest statement of what changed in the crate's public surface: + +| Item | Before | After | Breaking? | +|---|---|---|---| +| `GrantAuthorizer` | `pub struct GrantAuthorizer(HashMap>)` — a **private** tuple field | `pub struct GrantAuthorizer { grants: HashMap }` — a **private** named field | **Not breaking.** The tuple field was private before and the named field is private now, so no external caller could construct or destructure `GrantAuthorizer` either way. `GrantAuthorizer` has no public constructor, so an out-of-tree caller could only ever obtain one from `OperatorConfig::principals()`, whose signature did not change. The *shape* of the private field did change; its visibility did not | +| `ClientGrant` | `principal_id`, `certificate_sha256`, `operations` | plus `resource_scopes: Vec` (`#[serde(default)]`) | **Source-breaking for an out-of-tree struct-literal construction.** `ClientGrant` has public fields, so `ClientGrant { .. }` must now also set `resource_scopes`. This is a compile error, not a silent behaviour change. In-tree there is exactly one such construction, in `operations.rs`'s test helper, updated | +| `ResourceScope` | did not exist | new public struct with three public `String` fields | Additive | +| `ResourceKind` | did not exist | new public enum (`Execution`, `Blob`, `Workspace`, `Artifact`) | Additive | +| `ResourceId` | `Debug, Clone, PartialEq, Eq` | plus `Hash`, plus a `kind()` method | Additive | +| `Operation` | `Debug, Clone, Copy, PartialEq, Eq, Hash` | plus a `resource_kinds()` method | Additive | +| `Authorizer::authorize_request` | defaulted trait method | unchanged; `GrantAuthorizer` now overrides it | Additive behaviour for grant-based deployments that configure scopes; unchanged for those that do not | +| `OperatorConfig::principals`, `OperatorConfig::validate`, `OperatorConfig::redacted_json` | — | signatures unchanged | Not breaking | + +**In-tree consumer enumeration.** `GrantAuthorizer` has exactly two in-tree +production consumers: `operations.rs::principals`, which builds it, and +`operations.rs::start_server`, which passes it to `NodeServer::start` as +`Arc`. A repository-wide grep for `GrantAuthorizer` finds no +other production use; the only other reference is the new in-file test helper +in `src/lib.rs` that builds a grant table for the end-to-end test. + +**Out-of-tree position, stated honestly.** `eggwork-server` is not published +to a registry as a library in this repository's release process — the release +artifacts are the `eggworkd` binary and the release channel, not a +consumable crate API. So there is no downstream crate to break in-tree. An +out-of-tree consumer that constructs `ClientGrant` with a struct literal must +add the field; one that only *reads* a `ClientGrant` is unaffected; and one +that constructs a `GrantAuthorizer` directly was already unable to, because +the field was private. + +**Release-visibility consequence.** No wire shape, capability name, or +`API_SCHEMA_VERSION` changed, so this is not a protocol-visible release and +needs no control-plane version coordination. The *configuration* shape grew +an optional field: a node running this release accepts both the old and the +new configuration shape, and a node running an older release refuses the new +shape (§8). An operator rolling this out therefore configures the scope +*after* the node is upgraded, not before. + +## 8. Negative and adversarial evidence + +**A scope refuses a resource outside the scope.** `a_resource_scope_narrows_the_operation_grant_it_names` +asserts the operation grant alone would allow both digests and that the scope +refuses the unnamed one. The end-to-end counterpart +`a_resource_scoped_denial_is_indistinguishable_from_an_operation_level_denial` +drives it over mTLS: the scoped principal reads its in-scope digest +successfully and is refused the out-of-scope one with `403 forbidden`. + +**A foreign-owned resource remains refused.** +`a_resource_scope_cannot_reach_a_foreign_principal_resource` is the sharpest +evidence in this milestone, and it is deliberately two-sided: + +- the intruder's grant carries scopes naming the *owner's* execution, + workspace, and artifact; +- the test asserts the **authorizer allows** each of those requests — + `authorize_request` returns `true` for the intruder — because the scope + names the resource and the authorizer cannot know who owns it; +- the store then refuses: `404` for the execution, `409 workspace_identity_conflict` + for the workspace, an empty artifact list plus `404 artifact_not_found` for + the artifact; +- the owner's own reads succeed, so the difference is ownership and not a + broken path. + +**A misconfigured grant does not widen anything.** `a_scope_never_grants_an_operation_the_principal_does_not_hold` +builds a grant that names `blob-read` in its scope while its operation list +holds only `status` — the shape `validate` refuses — and asserts the +authorizer still refuses the blob read. + +**A denial discloses nothing.** The three denial shapes are asserted equal. + +**Configuration failures are refused, not tolerated.** +`a_malformed_resource_scope_is_refused_by_the_configuration` covers six +classes; the duplicate and both caps have their own tests; and +`the_grant_table_refuses_a_scope_it_cannot_parse` shows the second gate. + +## 9. Documentation status + +| Document | Status | Note | +|---|---|---| +| `architecture/overview.md` divergence #4 | **Coordinator-owned; not edited here.** The proposed replacement row is in §14 below | The ADR names this the single most important documentation consequence, and the file is explicitly outside this worker's ownership | +| `plans/security/threat-model.md` | Updated in this change | Invariant 5 and the "Authenticated unauthorized principal" row's remaining-boundary column. The blob boundary is **not** described as closed | +| `architecture/server-node.md` | Updated in this change | The `GrantAuthorizer` paragraph, a new "Resource-scoped grants" section with the decision rule, "The store stays authoritative for ownership", "Configuration fails closed at load time", and the `deny_unknown_fields` note; the residual-disclosure paragraph in "Authorization runs BEFORE resource resolution"; three new invariant rows; two new review-focus bullets; two new test-coverage bullets | +| `architecture/operations-cli.md` | Updated in this change | The grant configuration surface: the scope field, the error-class table, the caps, the redaction change, the rewritten "Authorization model" section, the compatibility note, three new invariant rows, and the test-coverage and honest-gaps paragraphs | +| `examples/eggworkd.example.json` | Updated in this change | A second client demonstrates the shape. The first client is unchanged in meaning, so the example still shows a broad controller | +| `plans/subsystems/security-isolation-resource-roadmap.md` | Updated in this change | The status line, the M005c entry's status, the deciding-ADR link, the closure-evidence pointer, and a "Decided disposition" paragraph | +| `plans/implementation/.../005c-...md` | Updated in this change | The `Status:` line is now `active`; the "blocked on ADR-0007" text in the header and in §15 is replaced with the accepted decision. The coordinator sets the final status | +| `plans/closure/security-isolation-resource/005c-status.md` | This file | — | +| `plans/registry.md` | **Coordinator-owned; not edited here** | §14 below gives the exact proposed edits | +| `AGENTS.md` | Not edited | Plan §11: the hard-invariant list needs no new entry. The existing "Node trust requires a verified mTLS client CA and explicit per-principal grants" line remains true — a resource scope narrows such a grant, it does not replace it. The proposed optional wording is in §14 | +| `docs/**` | Not edited | `docs/` is user- and operator-facing; the configuration surface this milestone adds is an operator concern that the deep dives and the example carry. The coordinator may want a `docs/` line for the new field — see §11 finding 4 | + +## 10. The residual boundary that remains + +Stated plainly, because the point of this milestone was honesty about +boundaries: + +1. **The blob boundary is not closed.** Blob storage is content-addressed and + shared: a blob has no owner, so there is no `principal_id` fence to hold. + The only boundary available for a blob is an operator-configured digest + list. A grant with **no** blob scope is still operation-wide, so a broad + `BlobRead` still reaches any known digest, and `POST /v1/blobs/missing` + still lets that principal probe digest presence. Scoping is opt-in and + the operator has to configure it. +2. **A scope is per `(operation, kind)`.** Scoping `Execute`/`Execution` does + not narrow `Execute`/`Workspace`. An operator who wants `execute` + constrained must write a scope for each kind that operation names. +3. **A scope is a static list.** It cannot express "every execution this + principal creates from now on", "every digest under a prefix", or "every + resource another principal shares". It is a list of identifiers. +4. **Artifact identifiers are assigned at capture time.** They are random + UUIDs, so an artifact scope can only name an artifact the operator already + knows the identifier of. "Learn the identifier, then write the scope" is + the workflow; there is no scope-by-creation rule. +5. **Ownership remains the store's job.** The authorizer narrows; the store + fences. Nothing in this milestone moved ownership into configuration. +6. **The scope does not reach the identity model.** A scope is a per-principal + grant narrowing. It is not a role, not an IAM subject, and it does not + change the mTLS identity model, the lease rules, or the generation + fencing. + +## 11. Unresolved findings, ranked by severity + +1. **Medium — the `(operation, kind)` granularity is a sharp edge.** An + operator who writes one scope for `execute`/`execution` may believe they + constrained `execute` generally; the `execute`/`workspace` half is + unconstrained. This follows the ADR's rule 3 read literally, and it is + documented in the threat model, in both deep dives, and in + `architecture/server-node.md`'s `Review focus`. **Not fixed here**: changing + the granularity would contradict the accepted ADR's decision rule. If the + coordinator considers the sharp edge unacceptable, it is a follow-up ADR, + not a code change. +2. **Medium — the blob boundary remains open for unscoped grants.** Inherent + to content-addressed shared storage; §10 states it. Closing it would mean + a different storage model, not a different policy. +3. **Low — `operation(name)` still uses `filter_map` for the grant's + *operation list*,** so an unrecognized operation name in a grant is + silently dropped by `principals()` rather than refused there. `validate()` + refuses it, and the daemon calls `validate()` before `start_server()`, so + the deployed path is fail-closed; but `principals()` on its own would drop + it. This is **pre-existing** and was deliberately not changed here — it is + the behaviour the existing deep dives describe, and the milestone's scope + is the resource-scope surface. The new scope list does **not** share this + weakness: `principals()` parses scopes strictly and refuses. +4. **Low — the user-facing documentation does not mention the new field.** + `docs/` is outside this milestone's ownership and the plan's §11 does not + list it. `architecture/operations-cli.md` and `examples/eggworkd.example.json` + carry it for operators who read the deep dives; a `docs/operations.md` or + `docs/quickstart.md` line would be better. Proposed for the coordinator. +5. **Informational — `architecture/server-node.md` says `Operation` has "11 + variants"** while the enum has twelve (the table omits `Telemetry`). That + inaccuracy is pre-existing and unrelated to this milestone; it was left + alone rather than folded into this change. + +## 12. Platform matrix actually exercised + +The authorization decision is host-independent: the grant table is built in +memory at startup and the decision is a lookup. The tests that exercise it +are therefore portable, and the new integration target +`tests/resource_scoped_authorization.rs` is written to compile and run on the +Windows job (no `/bin/sh`, no `std::os::unix`, no Unix-only modes). + +The two end-to-end tests live in `src/lib.rs`'s in-file test module, which is +Linux-shaped by construction — the server's own test harness starts +`/bin/sh` and uses Unix-only file modes, so it does not compile for a Windows +host. Those two tests were executed on **this Linux host only**. + +**No platform is claimed to be qualified by this milestone.** The change +alters no platform-specific code path, no capability advertisement, and no +wire shape, so no release-matrix exercise is required for the decision logic +itself — the plan says so explicitly. What has *not* been done is any hosted +run on macOS or Windows; the pre-existing limitation of the server's own +test harness still stands. + +## 13. Registry and roadmap disposition + +- **Roadmap** (`plans/subsystems/security-isolation-resource-roadmap.md`): + updated in this change — the status line, the M005c entry's status, the + deciding-ADR link, the closure-evidence pointer, and a "Decided + disposition" paragraph. +- **Registry** (`plans/registry.md`): **coordinator-owned; not edited here.** + The exact proposed edits are in §14. +- **Plan** (`plans/implementation/.../005c-...md`): `Status:` is `active`; + the coordinator sets the final status after the gate. + +## 14. Coordinator-owned text + +### `architecture/overview.md` — divergence #4 + +Replace the current row: + +```markdown +| 4 | `GrantAuthorizer` implements only `Authorizer::authorize`, **not** the resource-aware `authorize_request` hook. Resource-scoped authorization is therefore inert on the real deployment path; ownership is enforced only in the store, by `principal_id` comparison. | [operations-cli.md](operations-cli.md) · [server-node.md](server-node.md) | +``` + +with: + +```markdown +| 4 | ~~`GrantAuthorizer` implements only `Authorizer::authorize`, **not** the resource-aware `authorize_request` hook. Resource-scoped authorization is therefore inert on the real deployment path; ownership is enforced only in the store, by `principal_id` comparison.~~ **Closed 2026-10-25 by [ADR-0007](../plans/adrs/ADR-0007-resource-scoped-authorization.md) (Option A).** `GrantAuthorizer` now implements `authorize_request`: a grant may carry a bounded, optional list of resource scopes naming an operation, a resource kind, and a typed identifier, and the decision narrows the operation grant against that configuration-derived set. The scope is per `(operation, kind)`, so a scope for `Execute`/`Execution` does not narrow `Execute`/`Workspace`. The store's `principal_id` fences remain authoritative for ownership, so a scope naming another principal's execution, workspace, or artifact is still refused there. **Residual boundary:** a grant with no scope is still operation-wide, so a broad `BlobRead` still reaches any known digest — blob storage is content-addressed and shared, so a blob has no owner to fence it, and a blob scope is an explicit digest list the operator must configure. | [operations-cli.md](operations-cli.md) · [server-node.md](server-node.md) · [threat-model.md](../plans/security/threat-model.md) | +``` + +### `plans/registry.md` + +**This milestone did not edit `plans/registry.md`.** A *concurrent* uncommitted +edit in the shared working tree — not this milestone's — already updated three +of the five places that mention M005c (the addendum row at line 95, the +security row at line 114, and the batch paragraph at line 122) to say that +M005c is unblocked by the accepted ADR-0007. The coordinator should reconcile +that edit rather than apply the proposals below over it. + +Two places still read "blocked" and need the change: + +- **Line 183** (the milestone table row): + + ```markdown + | Security M005c resource-scoped authorization corrective | **blocked** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. Blocked on ADR-0007 (`plans/adrs/ADR-0007-resource-scoped-authorization.md`, **proposed, not accepted**), which must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. The gap itself is already recorded as divergence #4; this is a decision about a known gap, not a new defect. | + ``` + + becomes (with `Status:` set to the final status from + `plans/003-planning-process.md` §2 after the gate): + + ```markdown + | Security M005c resource-scoped authorization corrective | **active** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. ADR-0007 is **accepted** — Option A: implement resource-scoped grants. The hook is real: `GrantAuthorizer` implements `authorize_request` and a grant may carry a bounded, optional resource-scope list. The store's `principal_id` fences remain authoritative for ownership, and blobs are governed by an explicit digest list. No wire value, wire field, capability byte, or `API_SCHEMA_VERSION` changes. Closure evidence: `plans/closure/security-isolation-resource/005c-status.md`. | + ``` + +- **Line 230** (the dependency diagram): + + ```markdown + +--> Security M005c resource-scoped authorization [BLOCKED on ADR-0007] + ``` + + becomes: + + ```markdown + +--> Security M005c resource-scoped authorization [ADR-0007 ACCEPTED — IMPLEMENTING] + ``` + +- **Line 183's status cell and the roadmap's M005c status** should agree. The + roadmap entry in this change says "implemented"; the coordinator may prefer + "closing" until the gate is green. `plans/003-planning-process.md` §2's + vocabulary is the authority. + +### `AGENTS.md` + +Plan §11 says the hard-invariant list needs no new entry, and it does not need +one: the change adds a *narrowing* to an existing per-principal grant, and it +adds no new process owner, dependency edge, wire shape, or release-identity +rule. + +The only candidate is the Security section's line: + +> Node trust requires a verified mTLS client CA and explicit per-principal grants; + +which remains true. If the coordinator wants the narrowing recorded there, +the wording that keeps it true and in the same style is: + +> Node trust requires a verified mTLS client CA and explicit per-principal grants; a grant may narrow an operation to named resources, and the store's ownership fences remain authoritative. + +### `plans/subsystems/operations-distribution-roadmap.md` + +No change is required. This milestone touches no operations, distribution, or +release surface: no CLI verb, no configuration file placement, no release +artifact, and no wire value changed. `examples/eggworkd.example.json` grew an +optional field and a second client entry, which is a configuration example, +not a distribution change. + +## 15. What this milestone did not do + +- It did not change the store's ownership model, the artifact store's + retention, blob content-addressing, or the workspace derivation rules. + `crates/eggwork-server/src/store.rs` is **unmodified**. +- It did not change the execution-ownership boundary, the mTLS identity + model, the lease rules, or the generation fencing. +- It did not change `API_SCHEMA_VERSION`, any capability name, or any wire + shape, and it did not touch `crates/eggwork-core/**`, + `crates/eggwork-runner/**`, `crates/eggwork-client/**`, or + `crates/eggwork-sandbox-helper/**`. +- It did not add a policy language, a rule engine, a role system, or an IAM. + A scope is `(operation, kind, identifier)` and nothing else. +- It did not close the blob boundary. §10 states what remains. +- It did not edit `architecture/overview.md`, `plans/registry.md`, `AGENTS.md`, + `docs/**`, `scripts/**`, or any other plan or closure file. The exact + proposed text for the coordinator-owned files is in §14. +- It did not commit, branch, or stage anything. diff --git a/plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md b/plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md index 364e0d5..9bab0bd 100644 --- a/plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md +++ b/plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md @@ -1,8 +1,8 @@ # Security M005c — Resource-scoped authorization disposition corrective -Status: blocked +Status: active -Concrete blocker: `plans/adrs/ADR-0007-resource-scoped-authorization.md` — **proposed, not yet accepted**. The ADR must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. Per `plans/003-planning-process.md` §4, this plan MUST NOT be handed off as ready until that ADR is accepted, and it MUST NOT be handed off as ready merely because adjacent implementation exists. +Decision: `plans/adrs/ADR-0007-resource-scoped-authorization.md` is **accepted** — Option A, implement resource-scoped grants. The blocker that held this plan is discharged; §5 (Branch A) is the work in flight, and §4, §7, §8, §9, §11, §12, and §14 hold as written. Closure record: `plans/closure/security-isolation-resource/005c-status.md` @@ -315,7 +315,7 @@ Do not claim tests were run when they were only inspected. Do not claim a platfo ## 15. Handoff notes -- **This plan is blocked and must not be handed off as ready.** The blocker is concrete and named: `plans/adrs/ADR-0007-resource-scoped-authorization.md`, which is **proposed, not accepted**. It is written now, per `plans/003-planning-process.md` §4, to preserve the design intent so that the implementation is mechanical once the decision is made. +- **The blocking decision is made.** `plans/adrs/ADR-0007-resource-scoped-authorization.md` is **accepted** — Option A, implement resource-scoped grants. The plan was written while the decision was pending, per `plans/003-planning-process.md` §4, so that the implementation would be mechanical once the decision was made; §5 (Branch A) is that implementation. The status line above is `active` until the coordinator sets the final status after the pre-submit gate. - The plan is written so that **either** ADR outcome is executable without re-deriving the design. §5 is Branch A's work; §6 is Branch B's work; §4, §7, §8, §9, §10, §11, §12, and §14 hold in both. - The decision is durable and needs a human's judgement, not an implementer's. The two branches differ enormously in cost and in what they promise a caller: one adds a real per-resource boundary, the other removes a false promise. - The defect is **already recorded**. This milestone must not be reported as a newly discovered defect, and the closure record must say that the gap was known and is now decided. diff --git a/plans/registry.md b/plans/registry.md index a8cb385..88f9f0f 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -92,7 +92,7 @@ A repository-wide code interrogation pass over the reviewed baseline found no `t |---|---|---|---| | `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | M004 shared protocol contract | invariant | closed | | `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a conditionally closed; M005b closed | -| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a conditionally closed; M005b closed; **M005c blocked on ADR-0007** | +| `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a conditionally closed; M005b closed; **M005c active — ADR-0007 accepted, Option A** | | `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | | `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | proposed | @@ -111,7 +111,7 @@ Two findings in this batch were deliberately **not** given a milestone, because | Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | | Control-plane protocol | M001-M004 closed; no milestone in flight | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept — **implemented**: `eggwork-core` now owns the control-plane schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification, and the runner owns the capability names it produces. No wire value, wire field, or capability byte changed. Closure record: `plans/closure/control-plane-protocol/004-status.md` | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | | Workspace / artifacts | M001-M004 closed; M005a conditionally closed, M005b closed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) — **implemented**: a declared output that was not captured now ends the execution in a truthful non-success state with a first-class disposition and a diagnostic event, and a node whose platform cannot capture no longer advertises `artifact.declared.v1` — and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, `plans/closure/workspace-artifact-transport/005a-status.md`, `plans/closure/workspace-artifact-transport/005b-status.md` | -| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a conditionally closed, M005b closed, M005c blocked | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, which is **blocked on ADR-0007** and decides the disposition of the already-recorded inert resource-scoped authorization hook | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md` | +| Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a conditionally closed, M005b closed, M005c active | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, whose disposition of the already-recorded inert resource-scoped authorization hook was **decided by ADR-0007** (accepted 2026-10-25, Option A — implement resource-scoped grants) and is now being implemented as Branch A of its plan | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md`, `plans/adrs/ADR-0007-resource-scoped-authorization.md` | | Operations / distribution | M004 conditionally closed; M004a and M004b closed; M007 ready; M008a/M008b proposed | Foundation M004's Windows runner is implemented/native-qualified; M004 still needs immutable installed-release evidence and Windows SCM service qualification. M004a closed the fixture-ownership defect; M004b closed the residual `ETXTBSY` refusal it left open, by staging the helper as a link that is never written — no copy path, no barrier, and the mechanism confirmed against the kernel's own write-access accounting. M007 is the only substantive Phase-6 implementation capability still ready. A repository interrogation pass added M008a (five live metrics are never reported by the operator surface; one `active_executions` field name carries two meanings; every configuration fault collapses into one unhelpful message) and M008b (the release harness re-derives facts that already have an owner, and the design record's line citations and size figures are stale with no gate) | `plans/subsystems/operations-distribution-roadmap.md`, `plans/closure/operations-distribution/004-status.md`, `plans/closure/operations-distribution/004a-status.md`, `plans/closure/operations-distribution/004b-status.md`, `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | | CodeGG integration | Eggwork reference closed; downstream M001+C001+M002+M002a+M003 closed | CodeGG required-Landlock live qualification closed at `f5f8d96d`; downstream M003 closed at CodeGG `d51afe46` (implementation `1ce377ce`, hosted `36745285774`) against this repository's Workspace M004 contract; only downstream M004 remains, deferred. | `plans/subsystems/codegg-integration-roadmap.md` | @@ -119,7 +119,7 @@ Two findings in this batch were deliberately **not** given a milestone, because M007 is the only dependency-ready Eggwork implementation handoff. The optional Gregg telemetry line is closed and remains dependency history. Closed downstream CodeGG rows remain dependency history. -The repository interrogation corrective batch is registered but is **not** dependency-ready: the milestones in it that remain are `proposed`, and Security M005c is `blocked` on ADR-0007. It may be executed in parallel with M007, and the five correctives are mutually independent of one another. +The repository interrogation corrective batch is registered and is being worked. Security M005c was `blocked` on ADR-0007; that ADR was **accepted** on 2026-10-25 (Option A — implement resource-scoped grants), so M005c is no longer blocked and its plan's Branch A is the work being executed. The remaining milestones in the batch are `proposed`. The batch may be executed in parallel with M007, and the correctives are mutually independent of one another. | Workstream | Milestone | Status | Implementation plan | Handoff note | |---|---|---|---|---| diff --git a/plans/security/threat-model.md b/plans/security/threat-model.md index 8d1fa45..9e70149 100644 --- a/plans/security/threat-model.md +++ b/plans/security/threat-model.md @@ -1,7 +1,8 @@ # Eggwork Node Threat Model Status: current implementation baseline after Security M004 (includes -Operations M002 deployment/service surfaces) +Operations M002 deployment/service surfaces) and Security M005c +(resource-scoped authorization grants) Scope: the authenticated fixed-target node API, local execution admission, workspace and artifact storage, event/result exposure, secret-bearing @@ -39,9 +40,12 @@ recorded in the Security M004 closure. routes enforce their stored principal owner. 5. Blob digests are content identifiers, not credentials. Access to the raw Blob API is controlled by its `BlobRead`/`BlobWrite` authorization - capabilities. Deployments that require per-digest policy should implement - the resource-aware authorizer hook; principals granted broad BlobRead can - read any known digest. + capabilities. A grant may narrow those capabilities with a resource scope, + which for a blob is an explicit digest list: blob storage is + content-addressed and shared, so a blob has no owner to fence it. A + principal granted broad BlobRead with no blob scope can still read any + known digest; the scope is the only per-digest boundary available for it, + and it is opt-in. 6. Environment values, stdin bytes, argv, execution metadata values, client transport internals, and API error messages are redacted from ordinary `Debug` output. The API returns stable generic errors for malformed or @@ -58,7 +62,7 @@ recorded in the Security M004 closure. | Actor | Relevant attack | Mitigation in current baseline | Remaining boundary | |---|---|---|---| | Unauthenticated peer | Invoke API or enumerate execution state | Required mTLS; absent/unmapped verified identity rejected before route body handling | Certificate issuance and revocation are deployment responsibilities | -| Authenticated unauthorized principal | Execute, cancel, read, or mutate another principal's resources | Per-operation authorizer; principal fences on execution controls/events, workspace, artifact; observe returns not found for foreign ownership | Broad BlobRead capability permits any known digest unless resource-scoped policy is configured | +| Authenticated unauthorized principal | Execute, cancel, read, or mutate another principal's resources | Per-operation authorizer, optionally narrowed by a configured resource scope; principal fences on execution controls/events, workspace, artifact; observe returns not found for foreign ownership. A scope only narrows: the store's fences stay authoritative, so a scope naming another principal's resource is still refused there | A grant with no resource scope is still operation-wide, so a broad BlobRead capability permits any known digest; a blob scope is an explicit digest list, and blob storage has no owner to fence it | | Malicious/compromised controller | Forge principal fields, reuse identity, submit oversized or malformed values | Identity derives from certificate; wire DTOs reject unknown fields; bounded bodies, core validation, generation/lease/digest fencing | A controller authorized for Execute can request arbitrary commands within currently available host isolation | | Malicious executed process | Exfiltrate inherited secrets, flood output, leave descendants | Environment is cleared and rebuilt from a narrow baseline; sensitive runtime variables are denied; output and process-tree controls are bounded; user output is not logged by node; required Landlock `workspace_rw` confinement is enforced on qualified Linux and fails closed elsewhere; systemd/cgroup-v2 memory/CPU/PID controls are enforced where probed and fail closed when required | Network restriction (`Disabled`/`AllowListed`) remains intentionally unsupported and is rejected as `capability_mismatch`; macOS/Windows hard-enforcement backends do not exist and required requests fail closed there | | Foreign or tampered local service registration | Stop, replace, or uninstall another deployment's node service | Service ownership is proven by exact installed executable plus critical argv/config (`eggwork-node` spec); `Foreign`/`Unknown` registrations deny all destructive transitions before any mutation; destructive lifecycle flows only through Eggup adapters, never direct manager invocation | The operator must supply the exact registered executable/config paths; guessed paths fail closed by design | @@ -76,15 +80,15 @@ recorded in the Security M004 closure. |---|---|---| | `GET /v1/capabilities` | Capabilities | None | | `GET /v1/status` | Status | None | -| `POST /v1/executions` | Execute | Execution ID and optional workspace ID are passed to resource-aware policy; execution ID is reserved to the verified principal | +| `POST /v1/executions` | Execute | Execution ID and optional workspace ID are passed to the resource-scoped policy; execution ID is reserved to the verified principal | | `GET /v1/executions/{id}` | Observe | Snapshot lookup is fenced by principal and optional generation | | `POST /v1/executions/{id}/cancel` | Cancel | Principal, generation, and lease token | | `POST /v1/executions/{id}/renew` | Renew | Principal, generation, lease token, and renewal idempotency key | | `GET /v1/executions/{id}/events` | Events | Principal, generation, and lease token | -| `POST /v1/blobs/missing`, `GET /v1/blobs/{digest}` | BlobRead | Operation/resource authorization; raw digest access is capability-based | +| `POST /v1/blobs/missing`, `GET /v1/blobs/{digest}` | BlobRead | Operation authorization, narrowed by any configured blob digest scope; raw digest access is capability-based | | `POST /v1/blobs/prepare`, `PUT /v1/blobs/{digest}` | BlobWrite | Operation/resource authorization; digest and content integrity checked | -| `POST /v1/workspaces` | WorkspaceCreate | Workspace ID resource policy, then principal-bound workspace identity | -| `GET /v1/executions/{id}/artifacts`, `GET /v1/artifacts/{id}` | ArtifactRead | Execution/artifact resource policy and stored principal ownership | +| `POST /v1/workspaces` | WorkspaceCreate | Workspace ID resource scope, then principal-bound workspace identity | +| `GET /v1/executions/{id}/artifacts`, `GET /v1/artifacts/{id}` | ArtifactRead | Execution/artifact resource scope and stored principal ownership | Unknown routes are not dispatched. There are no network routes for drain, workspace deletion, artifact deletion, relay, or PTY in this API version. @@ -108,6 +112,9 @@ The implementation tests cover mapped and unmapped mTLS identities, operation denials before process spawn and storage mutation, unknown payload principal fields, principal-fenced observe behavior (foreign reads behave as missing), cross-principal cancel/renew/events fencing without a lease oracle, +resource-scope narrowing (a scope refuses a resource outside the scope, and a +scope naming another principal's execution, workspace, or artifact is still +refused by the store's owner fence), wrong-lease `invalid_lease` evidence, URL userinfo rejection, resource descriptors, hostile workspace manifests over the wire (traversal, absolute, backslash, dot-segment, empty, NUL, oversized paths rejected at diff --git a/plans/subsystems/security-isolation-resource-roadmap.md b/plans/subsystems/security-isolation-resource-roadmap.md index a376839..ff2d7b7 100644 --- a/plans/subsystems/security-isolation-resource-roadmap.md +++ b/plans/subsystems/security-isolation-resource-roadmap.md @@ -1,6 +1,6 @@ # Security, Isolation, and Resource Enforcement Roadmap -Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a conditionally closed, M005b closed, M005c blocked on ADR-0007 +Status: closed through M004 (remote-admission C001 and Operations M002 included); M005a conditionally closed, M005b closed, M005c implemented against accepted ADR-0007 Canonical authority: @@ -214,7 +214,13 @@ Exit conditions: Class: invariant -Status: **blocked** — concrete blocker is ADR-0007, `plans/adrs/ADR-0007-resource-scoped-authorization.md` (**proposed, not accepted**) +Status: **implemented** — ADR-0007 is **accepted** (`plans/adrs/ADR-0007-resource-scoped-authorization.md`, Option A: implement resource-scoped grants) and Branch A of the implementation plan is in the tree. + +Closure evidence: `plans/closure/security-isolation-resource/005c-status.md` + +Deciding ADR: + +- `plans/adrs/ADR-0007-resource-scoped-authorization.md` Corrective addendum: @@ -234,6 +240,10 @@ Exit conditions: - the node does not present a mechanism as available while it is inert; - the divergences-table entry is updated to the decided disposition. +Decided disposition (ADR-0007, Option A): + +The hook stays and becomes real. `GrantAuthorizer` implements `authorize_request`; `ClientGrant` gains an optional, additive, bounded `resource_scopes` list whose entries name an operation, a resource kind, and a typed resource identifier; the decision consults a configuration-derived set only, so it adds no lock and no ordering dependency to the request path; the store's `principal_id` fences stay authoritative for ownership, so a scope can only narrow and never widen; and a blob scope is an explicit digest list, because content-addressed blob storage has no owner. Configuration fails closed at load time on every malformed scope. No wire value, wire field, capability byte, or `API_SCHEMA_VERSION` changes. + ## 4. Capability semantics Requirements should encode whether a caller requests: From 496f4c865725c5900b442a02bb386606a3814bc9 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Sun, 25 Oct 2026 08:07:15 +0000 Subject: [PATCH 14/37] =?UTF-8?q?feat(core,runner):=20M005=20runner=20requ?= =?UTF-8?q?est=20validation=20parity=20=E2=80=94=20one=20owner=20for=20the?= =?UTF-8?q?=20rules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The runner re-spelled the eggwork-core domain validation rules in a private helper, and the two copies disagreed: the runner was stricter on empty argv entries and materially weaker on environment-entry syntax and duplicate environment names. The runner's copy is the one that gates the actual Command::env() call, and the public constructor and environment setter reached that gate without passing through core validation at all. - eggwork-core gains three public rule owners — validate_argv, validate_environment_entries, validate_timeout — and CommandSpec::validate delegates to them, so core keeps the single ownership. - The runner's duplicate checks are deleted; it consumes the core functions. Its own empty-argv-entry rule survives as a documented runner-level rule that is stricter than core, because it protects the child-process construction. - The runner's duplicate StdinPolicy enum is deleted; eggwork_core::StdinPolicy is imported directly and re-exported, keeping the public path alive. - The runner's re-stated output-policy bounds are replaced by the core OutputPolicy validation. - RunnerError::InvalidRequest now carries eggwork_core::ValidationError instead of String, so a validation failure stays attributable to the rule that produced it. - Option (b) of the plan was chosen over (a): the in-tree caller set is not empty — five callers across two crates, including the sandbox-helper integration tests — so removing the constructor would have broken the build rather than hardened it. The out-of-tree embedder position is unknown and is recorded as unknown. No wire protocol change, no stored-format change, no change to any core type's serde representation. --- architecture/core-domain.md | 34 +- architecture/runner-execution.md | 145 ++-- crates/eggwork-core/src/lib.rs | 120 ++-- .../tests/environment_rule_partition.rs | 274 +++++++ crates/eggwork-runner/src/lib.rs | 215 +++--- .../tests/request_validation_parity.rs | 680 ++++++++++++++++++ .../foundation-execution-core/005-status.md | 236 ++++++ ...er-request-validation-parity-corrective.md | 2 +- .../foundation-execution-core-roadmap.md | 10 +- 9 files changed, 1506 insertions(+), 210 deletions(-) create mode 100644 crates/eggwork-core/tests/environment_rule_partition.rs create mode 100644 crates/eggwork-runner/tests/request_validation_parity.rs create mode 100644 plans/closure/foundation-execution-core/005-status.md diff --git a/architecture/core-domain.md b/architecture/core-domain.md index ffe02bd..3aee0ff 100644 --- a/architecture/core-domain.md +++ b/architecture/core-domain.md @@ -43,7 +43,7 @@ All twenty constants live in one block at `lib.rs:10-29` and are the only number | Constant | Value | What it bounds | |---|---|---| | `MAX_ARG_COUNT` | `256` | Number of entries in `CommandSpec.argv`. | -| `MAX_ARG_BYTES` | `32768` (32 KiB) | Byte length of a single argv entry. Checked per entry at `lib.rs:498-506`; there is no bound on the *total* argv byte size. | +| `MAX_ARG_BYTES` | `32768` (32 KiB) | Byte length of a single argv entry. Checked per entry by `eggwork_core::validate_argv`; there is no bound on the *total* argv byte size. | | `MAX_ENV_COUNT` | `256` | Number of `EnvironmentEntry` values. | | `MAX_ENV_NAME_BYTES` | `256` | Byte length of one environment variable name. | | `MAX_ENV_VALUE_BYTES` | `16384` (16 KiB) | Byte length of one environment variable value. | @@ -113,7 +113,7 @@ The lowercase-only rule is the load-bearing part: it gives a content address **e `ProtocolVersion { major: u16, minor: u16 }` is a `Copy` data pair with derived ordering, major first; `ProtocolVersionRange { min, max }` is a plain pair with no validation of its own and no `Copy`. The only check that `min <= max` lives in `NodeCapabilities::validate` (`lib.rs:1068-1072`), not on the range. -`Versioned { schema_version: u16, value: T }` (`lib.rs:1097-1101`) is a generic versioned envelope. It is **declared and never used** — no type in the crate has a `Versioned` field, and no code in the crate constructs one. The crate's actual convention is a duplicated explicit field: `ExecuteRequest`, `ExecutionAccepted`, `ExecutionSnapshot`, and `ApiError` each carry `schema_version: u16` directly, and `ExecutionSpec` carries a *second*, independent one. A reviewer should decide whether `Versioned` is a reserved generic form or dead surface. +`Versioned { schema_version: u16, value: T }` (`struct Versioned`) is a generic versioned envelope. It is **declared and never used** — no type in the crate has a `Versioned` field, and no code in the crate constructs one. The crate's actual convention is a duplicated explicit field: `ExecuteRequest`, `ExecutionAccepted`, `ExecutionSnapshot`, and `ApiError` each carry `schema_version: u16` directly, and `ExecutionSpec` carries a *second*, independent one. A reviewer should decide whether `Versioned` is a reserved generic form or dead surface. Three different version axes coexist here, with three different openness rules — this is a real source of confusion: @@ -129,26 +129,28 @@ The model is a four-step nest, then three response shapes. ### `CommandSpec` — what to run -`lib.rs:458-541`. Ten public fields: `argv`, `cwd: Option`, `environment: Vec`, `stdin: StdinPolicy`, `timeout_millis: u64`, `output: OutputPolicy`, `declared_outputs: Vec`, `resources: ResourceRequirements`, `isolation: IsolationRequirement`, `network: NetworkRequirement`. +`struct CommandSpec`. Ten public fields: `argv`, `cwd: Option`, `environment: Vec`, `stdin: StdinPolicy`, `timeout_millis: u64`, `output: OutputPolicy`, `declared_outputs: Vec`, `resources: ResourceRequirements`, `isolation: IsolationRequirement`, `network: NetworkRequirement`. There is no shell string. `argv` is the executable plus arguments, matching `plans/001-terminology-and-domain-model.md` §9 (an explicit shell mode would be a separate requested capability, and no such field exists). `cwd` is an *optional relative path within the workspace* — a node-local locator, not workspace identity, which is why it is a `RelativePath` and not a `WorkspaceId`. -`CommandSpec::validate` (`lib.rs:488-540`) runs in a fixed order and delegates outward: +`CommandSpec::validate` runs in a fixed order and delegates outward: -1. `argv` non-empty, at most `MAX_ARG_COUNT`, each entry at most `MAX_ARG_BYTES` and free of NUL. -2. `environment` at most `MAX_ENV_COUNT`; **every** entry is re-validated by calling `EnvironmentEntry::new(&e.name, &e.value)` (`lib.rs:513-515`) — re-validation, not a trust of already-constructed entries. -3. `environment` names are unique, via a `HashSet<&str>` (`lib.rs:516-526`). +1. `argv` non-empty, at most `MAX_ARG_COUNT`, each entry at most `MAX_ARG_BYTES` and free of NUL — `eggwork_core::validate_argv`. +2. `environment` at most `MAX_ENV_COUNT`; **every** entry is re-validated by calling `EnvironmentEntry::new(&e.name, &e.value)` — re-validation, not a trust of already-constructed entries. The list rules live in `eggwork_core::validate_environment_entries`, which is the single owner of the count bound, the per-entry rule and the duplicate-name rule. +3. `environment` names are unique, via a `HashSet<&str>`. 4. `declared_outputs` at most `MAX_OUTPUTS`. 5. `timeout_millis` in `1..=MAX_TIMEOUT`. 6. `self.stdin.validate()`, `self.output.validate()`, `self.resources.validate()`. +The argv, environment-entry and timeout rules are not written inside `CommandSpec::validate`; they are three public functions — `eggwork_core::validate_argv`, `eggwork_core::validate_environment_entries` and `eggwork_core::validate_timeout` — and `validate` calls them. That is deliberate: these are the rules the runner consumes, and a rule the runner has to re-state is a rule that can drift. The runner now calls the same three functions rather than keeping a private copy (see [runner-execution.md](runner-execution.md)). Core is therefore the *single* owner of the environment-entry rules — name syntax, value bounds, the list count bound, and the duplicate-name rule — and a second copy of any of them anywhere else is a defect. + What `validate` does **not** do is as important: it does not check `argv[0]` is non-empty or path-like, does not bound total argv bytes, does not check `declared_outputs` paths for duplicates, and never validates `IsolationRequirement` or `NetworkRequirement` — neither type has a `validate` method at all. -`Debug` for `CommandSpec` is hand-written (`lib.rs:471-486`): `argv` is replaced with `"[REDACTED]"` outright (not just a length), while every other field is printed normally, delegating to the redacting `Debug` impls of `EnvironmentEntry`, `StdinPolicy`, and `ExecutionSpec`'s metadata. The test at `lib.rs:1264` pins this for argv, env, stdin, and metadata secrets. +`Debug` for `CommandSpec` is hand-written (`impl fmt::Debug for CommandSpec`): `argv` is replaced with `"[REDACTED]"` outright (not just a length), while every other field is printed normally, delegating to the redacting `Debug` impls of `EnvironmentEntry`, `StdinPolicy`, and `ExecutionSpec`'s metadata. The test `execution_spec_debug_redacts_credentials_and_command_arguments` pins this for argv, env, stdin, and metadata secrets. ### `ExecutionSpec` — the execution-defining description -`lib.rs:543-585`. Three fields: `schema_version: u16`, `command: CommandSpec`, `metadata: Vec<(String, String)>`. `validate` runs `command.validate()` first, then requires `schema_version != 0`, then bounds metadata: at most `MAX_METADATA_COUNT` pairs, each key non-empty and at most `MAX_METADATA_KEY_BYTES`, each value at most `MAX_METADATA_VALUE_BYTES`, no NUL in either. Metadata keys have no charset restriction beyond that (unlike environment names), and **duplicate metadata keys are not rejected** — unlike duplicate environment names, which are. +`struct ExecutionSpec`. Three fields: `schema_version: u16`, `command: CommandSpec`, `metadata: Vec<(String, String)>`. `validate` runs `command.validate()` first, then requires `schema_version != 0`, then bounds metadata: at most `MAX_METADATA_COUNT` pairs, each key non-empty and at most `MAX_METADATA_KEY_BYTES`, each value at most `MAX_METADATA_VALUE_BYTES`, no NUL in either. Metadata keys have no charset restriction beyond that (unlike environment names), and **duplicate metadata keys are not rejected** — unlike duplicate environment names, which are. `Debug` prints `metadata_count` and the redacted `command`, never metadata values (`lib.rs:549-557`). @@ -175,9 +177,9 @@ The custom serde encoding is deliberately backward-compatible with a legacy shap - `StdinPolicy { Null, Bytes(Vec) }` (`lib.rs:270-299`). `Null` and a bounded byte payload. `validate` checks only the length bound. `Debug` prints `Bytes { length, value: "[REDACTED]" }`. - `OverflowPolicy { Truncate, Terminate }` (`lib.rs:301-305`) — the declared behavior when output exceeds the capture budget. Two variants, no data, no validation, no rename attribute. - `OutputPolicy { capture_limit_bytes, event_chunk_bytes, overflow }` (`lib.rs:307-334`) with `Default` = `1 MiB` / `16 KiB` / `Truncate` — note these defaults are *not* expressions of `MAX_CAPTURE_BYTES` / `MAX_EVENT_CHUNK_BYTES`; they are independent literals that happen to be 1/16 and 1/4 of the maxima. `validate` requires `capture_limit_bytes <= MAX_CAPTURE_BYTES`, `event_chunk_bytes` in `1..=MAX_EVENT_CHUNK_BYTES`. It does **not** require `event_chunk_bytes <= capture_limit_bytes`, and it accepts `capture_limit_bytes == 0`. -- `DeclaredOutput { path: RelativePath, required: bool }` (`lib.rs:336-340`) — a declared capture target and whether its absence is a failure. This is the declaration mechanism from ADR-0004 decision 10: Eggwork captures only declared paths, and `ArtifactType` has exactly one variant (`File`) because nothing else is in scope. -- `EnvironmentEntry { name, value }` (`lib.rs:229-268`). `new` requires a name that is non-empty, at most `MAX_ENV_NAME_BYTES`, ASCII alphanumeric or `_` only, **not** starting with an ASCII digit (`is_some_and(u8::is_ascii_digit)` at `lib.rs:248`), and NUL-free; and a value at most `MAX_ENV_VALUE_BYTES` and NUL-free, with a NUL value reported as `Forbidden { field: "environment value NUL" }`. A leading underscore is allowed; a hyphen in a name is not. `Debug` prints the name and `"[REDACTED]"` for the value. -- `RelativePath` (`lib.rs:187-227`) is the single path type and its safety rules are: non-empty, at most `MAX_PATH_BYTES`, not starting with `/`, no `\`, no NUL, and no `/`-delimited component that is empty, `.`, or `..`. The empty-component rule subsumes trailing slashes and doubled slashes. It is **not** ASCII-restricted, has no trailing-dot or trailing-space rule, and no Windows reserved-name rule — those stricter rules exist only in `validate_portable_workspace_path` for workspace trees. The inner `String` is private, so every `RelativePath` in the system has passed these checks; `"C:/secret"` and `"café.txt"` are legal `RelativePath` values that the workspace validator rejects separately (asserted at `lib.rs:1431-1433`). +- `DeclaredOutput { path: RelativePath, required: bool }` (`struct DeclaredOutput`) — a declared capture target and whether its absence is a failure. This is the declaration mechanism from ADR-0004 decision 10: Eggwork captures only declared paths, and `ArtifactType` has exactly one variant (`File`) because nothing else is in scope. +- `EnvironmentEntry { name, value }` (`struct EnvironmentEntry`). `new` requires a name that is non-empty, at most `MAX_ENV_NAME_BYTES`, ASCII alphanumeric or `_` only, **not** starting with an ASCII digit (`is_some_and(u8::is_ascii_digit)` at `lib.rs:248`), and NUL-free; and a value at most `MAX_ENV_VALUE_BYTES` and NUL-free, with a NUL value reported as `Forbidden { field: "environment value NUL" }`. A leading underscore is allowed; a hyphen in a name is not. `Debug` prints the name and `"[REDACTED]"` for the value. +- `RelativePath` (`struct RelativePath`) is the single path type and its safety rules are: non-empty, at most `MAX_PATH_BYTES`, not starting with `/`, no `\`, no NUL, and no `/`-delimited component that is empty, `.`, or `..`. The empty-component rule subsumes trailing slashes and doubled slashes. It is **not** ASCII-restricted, has no trailing-dot or trailing-space rule, and no Windows reserved-name rule — those stricter rules exist only in `validate_portable_workspace_path` for workspace trees. The inner `String` is private, so every `RelativePath` in the system has passed these checks; `"C:/secret"` and `"café.txt"` are legal `RelativePath` values that the workspace validator rejects separately (asserted at `lib.rs:1431-1433`). ## Workspace model @@ -293,7 +295,7 @@ Three digests, three domain-separation prefixes, three version axes. `lib.rs:1155-1161`, paired with `CANONICAL_REQUEST_VERSION: u16 = 2` at `lib.rs:1150-1151` ("Version of the execution request canonicalization algorithm"). -1. `normalize_execution_spec(spec)` (`lib.rs:1187-1203`) clones the spec and sorts the three semantically unordered collections: `command.environment` by `name`; `metadata` by `(key, value)`; `command.declared_outputs` by `(path, required)`. `argv` is deliberately left in order, because argv order is semantic. All three sorts use `sort_by`, which is stable. +1. `normalize_execution_spec(spec)` clones the spec and sorts the three semantically unordered collections: `command.environment` by `name`; `metadata` by `(key, value)`; `command.declared_outputs` by `(path, required)`. `argv` is deliberately left in order, because argv order is semantic. All three sorts use `sort_by`, which is stable. 2. Bytes are built as `b"eggwork-execution-spec\0canonical-json-v2\0"` followed by `serde_json::to_vec(&normalized)`. 3. `BlobDigest::from_bytes` SHA-256s the whole thing into lowercase hex. @@ -375,9 +377,9 @@ Where it is produced: the five constructors (`id_type!::new`, `ExecutionGenerati | `EventSequence` — no invariant | none; `const fn new` accepts any `u64` | none (no test constructs one outside the event test) | | `BlobDigest` is 64 lowercase hex | `BlobDigest::parse` / `TryFrom`; `from_bytes` cannot violate | `typed_ids_and_digest_validate`: known SHA-256 vector for `b"abc"`, and `parse("ABC").is_err()` | | `RelativePath` relative, confined, no empty/`.`/`..` component, no `\`, no NUL, ≤`MAX_PATH_BYTES` | `RelativePath::new`; private inner field means no other construction route | `paths_env_metadata_outputs_and_roundtrip`: `/tmp` and `a/../b` rejected. No depth, NUL, or length case. | -| Env name charset, non-digit first byte, no NUL; value length and NUL | `EnvironmentEntry::new`; re-checked for every entry by `CommandSpec::validate` (`lib.rs:513-515`) | `paths_env_metadata_outputs_and_roundtrip`: `1BAD` and `a\0b` rejected | -| Environment names unique | `CommandSpec::validate` (`lib.rs:516-526`) | `duplicate_environment_names_are_rejected` | -| `argv` non-empty, ≤`MAX_ARG_COUNT`, each ≤`MAX_ARG_BYTES`, no NUL | `CommandSpec::validate` (`lib.rs:489-506`) | `spec_and_bounds_validate`: cleared argv, oversized `argv[0]`. Count bound untested. | +| Env name charset, non-digit first byte, no NUL; value length and NUL | `EnvironmentEntry::new`; re-checked for every entry by `eggwork_core::validate_environment_entries` | `paths_env_metadata_outputs_and_roundtrip`: `1BAD` and `a\0b` rejected; `environment_rule_partition` proves the accepted and rejected sets partition the candidate space | +| Environment names unique | `eggwork_core::validate_environment_entries` | `duplicate_environment_names_are_rejected`; `environment_rule_partition` | +| `argv` non-empty, ≤`MAX_ARG_COUNT`, each ≤`MAX_ARG_BYTES`, no NUL | `eggwork_core::validate_argv` | `spec_and_bounds_validate`: cleared argv, oversized `argv[0]`. Count bound untested at the core level; the runner's parity suite covers it. | | `timeout_millis` in `1..=MAX_TIMEOUT` | `CommandSpec::validate` (`lib.rs:533-535`) | none | | `stdin` ≤ `MAX_STDIN_BYTES` | `StdinPolicy::validate` | none | | `capture_limit_bytes` ≤ `MAX_CAPTURE_BYTES`; `event_chunk_bytes` in `1..=MAX_EVENT_CHUNK_BYTES` | `OutputPolicy::validate` | none (the default policy is only ever used valid) | diff --git a/architecture/runner-execution.md b/architecture/runner-execution.md index cb55bee..e4a2b6e 100644 --- a/architecture/runner-execution.md +++ b/architecture/runner-execution.md @@ -17,9 +17,9 @@ Source of truth: [`crates/eggwork-runner/src/lib.rs`](../crates/eggwork-runner/s **Deliberately does not own** -- Global scheduling, placement, node selection, retry, or queueing. The crate doc states this explicitly: "neither this API nor its result types carry scheduler placement, priority, or project fairness policy" (lines 8-10). ADR-0005 assigns those to the server. +- Global scheduling, placement, node selection, retry, or queueing. The crate doc states this explicitly: "neither this API nor its result types carry scheduler placement, priority, or project fairness policy" (the crate-level `//!` block). ADR-0005 assigns those to the server. - Local admission / concurrency permits. `run` has no notion of a slot, drain state, or storage headroom. -- Artifact capture, artifact retention, and finalization. `RunnerResult::execution_result` hardcodes `artifact_count: 0` and `finalization_failure: None` (lines 1016-1017). +- Artifact capture, artifact retention, and finalization. `RunnerResult::execution_result` hardcodes `artifact_count: 0` and `finalization_failure: None`. - Network policy. `eggwork_core::CommandSpec::network` is destructured away by `from_spec` with `..` and never consulted. - Declared outputs. `declared_outputs` is likewise discarded by `from_spec`; the server owns output capture. - Transport, auth, and leases. `CancellationToken` is the *only* lifetime signal the runner accepts; lease policy is the caller's. @@ -29,45 +29,49 @@ The normative statement lives in [execution-ownership.md](execution-ownership.md **What a caller cannot do** -Every validated field of `RunnerRequest` is private (lines 686-699). There is no public field, no public constructor that skips validation, and no way to obtain a `&mut` to any of them. The public surface is a builder (`RunnerRequest::new` plus `set_*`) and `RunnerRequest::from_spec`; accessors exist only for `sandbox_request()` and `resource_setup_request()`, and `resource_setup_request_mut()` is the single mutable door, scoped to the `Requirement` triple so it cannot weaken an unrelated field. +Every validated field of `RunnerRequest` is private (`struct RunnerRequest`). There is no public field and no way to obtain a `&mut` to any of them. The public surface is a builder (`RunnerRequest::new` plus `set_*`) and `RunnerRequest::from_spec`; accessors exist for `sandbox_request()` and `resource_setup_request()`, and `resource_setup_request_mut()` is the single mutable door, scoped to the `Requirement` triple so it cannot weaken an unrelated field. -This is a security property, not a style choice, for three reasons: +Private fields are necessary but not sufficient: a public constructor is a construction path too, and a request that never passes through the domain contract can be built through one. That is why the runner does not restate the contract at all — it *consumes* it: -1. **Bounds are re-checked at the trust boundary, not at construction.** `RunnerRequest::validate` (line 852) is private and is called at the top of `run`, before setup, before any helper, before `spawn`. A builder caller can assemble an over-long argv, an NUL in an environment value, a `capture_limit` above `MAX_CAPTURE_BYTES`, a zero timeout, or a `cwd` that escapes the root — and every one of those is rejected with a typed `RunnerError::InvalidRequest`/`InvalidWorkingDirectory` at `run`. There is no "already validated" flag to trust. -2. **The filesystem boundary is enforced by canonicalization, not by string prefix tests.** `validate` canonicalizes `root` and then canonicalizes `root.join(cwd)` and requires `canonical.starts_with(&root)`. A `..` traversal, a symlink, or a bind-like path is caught after resolution, not before. -3. **Making fields public would make the validated state a convention.** The crate-level doc's claim "Request fields remain private so callers cannot bypass protocol bounds" is only true while the fields are private; `#![forbid(unsafe_code)]` (line 1) plus workspace `unsafe_code = "deny"` means the same guarantee cannot be re-opened from inside either. +1. **The rules have one owner, in `eggwork-core`.** The argv bounds (`eggwork_core::validate_argv`), the environment-entry rules including the duplicate-name rule (`eggwork_core::validate_environment_entries`), the timeout (`eggwork_core::validate_timeout`), the stdin bound (`eggwork_core::StdinPolicy::validate`), the output bounds (`eggwork_core::OutputPolicy::validate`) and the resource bounds (`eggwork_core::ResourceRequirements::validate`) are all core functions. The runner calls them; it does not re-derive them. `eggwork_core::CommandSpec::validate` calls the same functions, so the protocol path and the runner path cannot disagree. +2. **Every public construction path is covered.** `RunnerRequest::contract_error()` reports the first violation in a request without running anything, and `RunnerRequest::validate` — the private enforcement point, called at the top of `run`, before setup, before any helper, before `spawn` — refuses with the same typed error. There is no "already validated" flag to trust and no door into a request that the contract does not cover. +3. **The filesystem boundary is enforced by canonicalization, not by string prefix tests.** `validate` canonicalizes `root` and then canonicalizes `root.join(cwd)` and requires `canonical.starts_with(&root)`. A `..` traversal, a symlink, or a bind-like path is caught after resolution, not before. These two rules — the root-directory and working-directory resolutions — are the runner's own; `eggwork-core` does not own them, because it never sees a filesystem. +4. **Making fields public would make the validated state a convention.** The crate-level doc's claim "Request fields remain private so callers cannot bypass protocol bounds" is only true while the fields are private; `#![forbid(unsafe_code)]` plus workspace `unsafe_code = "deny"` means the same guarantee cannot be re-opened from inside either. -The same discipline appears in the `Debug` implementations. `RunnerRequest`, `StdinPolicy`, `OutputChunk`, and `BoundedCapture` all have hand-written `Debug` impls that print `argv` as `[REDACTED]`, stdin bytes as `[REDACTED]`, output bytes as `[REDACTED]`, and only `environment_count` for the environment. A default derived `Debug` would have leaked argv, tokens, and child output into server logs. +The runner is allowed to be **stricter** than its owner, and it is exactly once stricter: it refuses an empty argv entry, which core permits. That rule is the runner's own — an empty argument is a child-process construction hazard rather than a protocol concern — it is written out as `RunnerRequest::argv_entry_violation` with that reasoning in the source, and it is pinned by `the_runner_refuses_an_empty_argv_entry_which_core_permits`. + +The same discipline appears in the `Debug` implementations. `RunnerRequest`, `OutputChunk`, and `BoundedCapture` have hand-written `Debug` impls that print `argv` as `[REDACTED]`, output bytes as `[REDACTED]`, and only `environment_count` for the environment; the stdin policy's `Debug` is core's, which redacts the bytes and prints only their length. A default derived `Debug` would have leaked argv, tokens, and child output into server logs. ## The embedding API -The crate doc (`//!` block, lines 3-10) is the four-step contract: +The crate doc (`//!` block) is the four-step contract: 1. Construct a validated `RunnerRequest` from an `eggwork_core::ExecutionSpec` with `RunnerRequest::from_spec`. 2. Run it through `LocalProcessRunner`. -3. Request fields remain private so callers cannot bypass protocol bounds. +3. Request fields remain private, and every public construction path is covered by the `eggwork_core` domain contract. 4. Platform setup is supplied through `ExecutionSetup`; neither this API nor its result types carry scheduler placement, priority, or project fairness policy. ### `RunnerRequest` -| Private field | Type | Source in `from_spec` | Validation in `RunnerRequest::validate` | -| --- | --- | --- | --- | -| `argv` | `Vec` | `CommandSpec::argv` | non-empty, `len <= MAX_ARG_COUNT` (256), no empty entry, each `<= MAX_ARG_BYTES` (32 KiB), no `\0` | -| `root` | `PathBuf` | caller argument (not from the spec) | canonicalizes, must be a directory | -| `cwd` | `Option` | `CommandSpec::cwd` | canonicalized under `root`, must start with `root` and be a directory; `None` means `root` itself | -| `environment` | `Vec<(String, String)>` | `CommandSpec::environment` (name/value pairs) | `<= MAX_ENV_COUNT` (256); name non-empty and `<= MAX_ENV_NAME_BYTES` (256); value `<= MAX_ENV_VALUE_BYTES` (16 KiB); no `\0` in either; no `=` in name | -| `stdin` | crate-local `StdinPolicy` | `CommandSpec::stdin` | `StdinPolicy::validate` rejects `Bytes` over `MAX_STDIN_BYTES` (4 MiB) | -| `timeout` | `Duration` | `Duration::from_millis(timeout_millis)` | non-zero and `<= MAX_TIMEOUT` (7 days) | -| `capture_limit` | `usize` | `output.capture_limit_bytes` | `<= MAX_CAPTURE_BYTES` (16 MiB) | -| `event_chunk_bytes` | `usize` | `output.event_chunk_bytes` | `1..=MAX_EVENT_CHUNK_BYTES` (64 KiB) | -| `overflow` | `eggwork_core::OverflowPolicy` | `output.overflow` | — (`Truncate` or `Terminate`; both valid) | -| `provenance` | `ExecutionProvenance` | caller argument | — | -| `sandbox` | `SandboxRequest` | `isolation` | — (profile checked in `ExecutionSetup::prepare` and `SandboxChannel::new`) | -| `resources` | `ResourceSetupRequest` | `resources.memory_bytes` / `.cpu_millis` / `.pids` | — (enforcement decided by `ExecutionSetup`) | +| Private field | Type | Source in `from_spec` | Rule owner | Checked by | +| --- | --- | --- | --- | --- | +| `argv` | `Vec` | `CommandSpec::argv` | `eggwork-core` — `validate_argv`: non-empty, `len <= MAX_ARG_COUNT` (256), each `<= MAX_ARG_BYTES` (32 KiB), no `\0` | `RunnerRequest::validate` | +| `argv` (extra) | `Vec` | — | **the runner's own rule** — an empty entry is a child-process construction hazard | `RunnerRequest::argv_entry_violation` | +| `root` | `PathBuf` | caller argument (not from the spec) | **the runner's own rule** — canonicalizes, must be a directory | `RunnerRequest::validate` | +| `cwd` | `Option` | `CommandSpec::cwd` | **the runner's own rule** — canonicalized under `root`, must start with `root` and be a directory; `None` means `root` itself | `RunnerRequest::validate` | +| `environment` | `Vec<(String, String)>` | `CommandSpec::environment` (name/value pairs) | `eggwork-core` — `validate_environment_entries`: `<= MAX_ENV_COUNT` (256); name non-empty, `<= MAX_ENV_NAME_BYTES` (256), ASCII alphanumerics and underscore only, not starting with a digit, no `\0`; value `<= MAX_ENV_VALUE_BYTES` (16 KiB), no `\0`; no duplicate name | `RunnerRequest::validate` | +| `stdin` | `eggwork_core::StdinPolicy` | `CommandSpec::stdin` | `eggwork-core` — `StdinPolicy::validate` rejects `Bytes` over `MAX_STDIN_BYTES` (4 MiB) | `RunnerRequest::validate` | +| `timeout` | `Duration` | `Duration::from_millis(timeout_millis)` | `eggwork-core` — `validate_timeout`: non-zero and `<= MAX_TIMEOUT` (7 days) | `RunnerRequest::validate` | +| `capture_limit` | `usize` | `output.capture_limit_bytes` | `eggwork-core` — `OutputPolicy::validate`: `<= MAX_CAPTURE_BYTES` (16 MiB) | `RunnerRequest::validate` | +| `event_chunk_bytes` | `usize` | `output.event_chunk_bytes` | `eggwork-core` — `OutputPolicy::validate`: `1..=MAX_EVENT_CHUNK_BYTES` (64 KiB) | `RunnerRequest::validate` | +| `overflow` | `eggwork_core::OverflowPolicy` | `output.overflow` | `eggwork-core` — both `Truncate` and `Terminate` are valid | `RunnerRequest::validate` | +| `provenance` | `ExecutionProvenance` | caller argument | — | — | +| `sandbox` | `SandboxRequest` | `isolation` | — (profile checked in `ExecutionSetup::prepare` and `SandboxChannel::new`) | — | +| `resources` | `ResourceSetupRequest` | `resources.memory_bytes` / `.cpu_millis` / `.pids` | `eggwork-core` — `ResourceRequirements::validate` bounds each dimension; enforcement is decided by `ExecutionSetup` | `RunnerRequest::validate` | `root` deserves emphasis: it is **not** derived from the spec. Authorization of the root is the caller's decision, passed alongside the spec. The runner's contribution is to canonicalize it and to make it the confinement boundary for `cwd`. -`RunnerRequest::new(argv, root)` (line 723) supplies conservative defaults for an embedder that is not going through `from_spec`: `cwd: None`, empty environment, `StdinPolicy::Null`, `timeout: 30s`, `capture_limit: MAX_CAPTURE_BYTES`, `event_chunk_bytes: MAX_EVENT_CHUNK_BYTES`, `overflow: Truncate`, `SandboxRequest::None`, and all three resource `Requirement`s `NotRequested`. The doc comment is explicit that "`run` validates every field before setup or child creation", so the defaults are convenience, not a bypass. +`RunnerRequest::new(argv, root)` supplies conservative defaults for an embedder that is not going through `from_spec`: `cwd: None`, empty environment, `StdinPolicy::Null`, `timeout: 30s`, `capture_limit: MAX_CAPTURE_BYTES`, `event_chunk_bytes: MAX_EVENT_CHUNK_BYTES`, `overflow: Truncate`, `SandboxRequest::None`, and all three resource `Requirement`s `NotRequested`. The defaults are convenience, not a bypass: the request they produce is covered by the same contract as one built from a spec, and `RunnerRequest::contract_error()` will say so before anything runs. ### `from_spec` @@ -79,21 +83,20 @@ pub fn from_spec( ) -> Result ``` -It runs `spec.validate()` first and maps a `ValidationError` to `RunnerError::InvalidRequest(e.to_string())`. Only then does it clone and destructure `spec.command`, so a spec that is invalid at the domain layer never becomes a runner request. The mapping is otherwise mechanical, with two decisions worth naming: +It runs `spec.validate()` first and maps a `ValidationError` to `RunnerError::InvalidRequest(e)` — the typed error, not a rendered string, so the rule that refused the request stays identifiable. Only then does it clone and destructure `spec.command`, so a spec that is invalid at the domain layer never becomes a runner request. The mapping is otherwise mechanical, with two decisions worth naming: - **Isolation becomes a profile string.** `IsolationRequirement::None → SandboxRequest::None`, `BestEffort → BestEffort { profile: WORKSPACE_RW_PROFILE }`, `Required → Required { profile: WORKSPACE_RW_PROFILE }`. `WORKSPACE_RW_PROFILE` (`"workspace_rw"`) is therefore the only profile the protocol can request; the runner independently rejects anything else as `"unsupported sandbox profile"`. The name is an exported constant rather than a literal, because the trusted helper is a standalone binary that keeps its own copy of the spelling — the helper's test pins the two together. - **Everything the runner does not own is dropped.** The destructure binds `argv, cwd, environment, stdin, timeout_millis, output, resources, isolation, ..` — so `declared_outputs` and `network` are discarded by construction, not by later ignoring. `RunnerRequest::validate` still runs at `run`, so `from_spec` validation is a fail-fast convenience layered on top of the enforcement point, not a replacement for it. -### Two `StdinPolicy` types +### One `StdinPolicy` -There are two `StdinPolicy` enums and the distinction is deliberate: +There is one `StdinPolicy` type, and it is core's: `eggwork_core::StdinPolicy`. It derives `Serialize`/`Deserialize`, has a public `validate() -> Result<(), ValidationError>`, is what an `ExecutionSpec` carries, and is what the runner's private `stdin` field holds. -- `eggwork_core::StdinPolicy` is the domain/wire type. It derives `Serialize`/`Deserialize`, has a public `validate() -> Result<(), ValidationError>`, and is what an `ExecutionSpec` carries. -- `eggwork_runner::StdinPolicy` (line 921) is the crate-local execution type: no serde derives, a private `validate() -> Result<(), RunnerError>`, and a redacting `Debug`. +The runner used to keep a second, crate-local enum with its own `Debug` and its own copy of the `MAX_STDIN_BYTES` bound, and converted between the two by hand in `from_spec`. That copy was a second owner of a rule core already owned, and it is gone. The public path `eggwork_runner::StdinPolicy` survives as a re-export of the core type, so an embedder that already imports it from the runner keeps compiling and gets the same type — the `Debug` impl is core's, which redacts the bytes and prints only their length, exactly as the local copy did. -The conversion exists exactly once, in `from_spec` (lines 834-837), and it is total — two variants to two variants, no default arm, so a future core variant is a compile error at the conversion site rather than a silent drop. The local type is also what the private `stdin` field holds, and `set_stdin_policy` accepts only the local type, so a caller outside the crate cannot inject a `CoreStdinPolicy` directly. The result is a two-layer bound: the core layer validates on the protocol path, and the runner layer re-validates at `run` on every path. +The bound is now enforced once, by `eggwork_core::StdinPolicy::validate`, and the runner consumes it like every other core rule. ## ExecutionSetup — the platform seam @@ -112,15 +115,15 @@ pub trait ExecutionSetup: Send + Sync { } ``` -Only `prepare` is required. `execution_capabilities` and `sandbox_helper_path` are defaulted, so a minimal implementation cannot accidentally advertise a feature or a helper. The doc on `execution_capabilities` is normative: "Each returned feature string must reflect a live probe — never a compile-time or configuration-time guess." `LocalProcessRunner::execution_capabilities` (line 1139) forwards it and adds the constraint that callers "MUST combine these with the static protocol/workspace/artifact feature list; the runner owns dynamic facts only." +Only `prepare` is required. `execution_capabilities` and `sandbox_helper_path` are defaulted, so a minimal implementation cannot accidentally advertise a feature or a helper. The doc on `execution_capabilities` is normative: "Each returned feature string must reflect a live probe — never a compile-time or configuration-time guess." `LocalProcessRunner::execution_capabilities` forwards it and adds the constraint that callers "MUST combine these with the static protocol/workspace/artifact feature list; the runner owns dynamic facts only." -`prepare` is a *reporting* hook, not a command builder. It returns what enforcement will be attempted; the actual argv composition happens later in `run` via `SandboxChannel::command`, `direct_command`, and `wrap_resource_command`. Note that both in-tree implementations bind the `root` parameter as `_root` and never read it — the spec's `root` is re-derived from `request.root.canonicalize()` inside `SandboxChannel::new` (line 1725). The parameter is currently a seam for future backends, not a used input. +`prepare` is a *reporting* hook, not a command builder. It returns what enforcement will be attempted; the actual argv composition happens later in `run` via `SandboxChannel::command`, `direct_command`, and `wrap_resource_command`. Note that both in-tree implementations bind the `root` parameter as `_root` and never read it — the spec's `root` is re-derived from `request.root.canonicalize()` inside `SandboxChannel::new`. The parameter is currently a seam for future backends, not a used input. ### `TrustedLandlockSetup` -`TrustedLandlockSetup::new(helper_path)` takes an explicit path; `discover_sibling()` (line 412) resolves `current_exe().canonicalize().parent()/eggwork-sandbox-helper`, falling back to the bare relative name `eggwork-sandbox-helper` if any step fails. `LocalProcessRunner::default()` uses `discover_sibling()` on Linux and `NoExecutionSetup` elsewhere. +`TrustedLandlockSetup::new(helper_path)` takes an explicit path; `discover_sibling()` resolves `current_exe().canonicalize().parent()/eggwork-sandbox-helper`, falling back to the bare relative name `eggwork-sandbox-helper` if any step fails. `LocalProcessRunner::default()` uses `discover_sibling()` on Linux and `NoExecutionSetup` elsewhere. -`prepare` (line 425) does three things, in this order: +`TrustedLandlockSetup::prepare` does three things, in this order: 1. **Probe OS resource controls.** If `resources.is_requested()`, call `SystemdCgroupBackend::probe`. Success yields `ResourceSetupOutcome::Applied { backend: "systemd-cgroup-v2" }`; failure yields `NotApplied { reason }`, or `Err(RunnerError::Setup(reason))` when `resources.has_required()`. No request yields `NotRequested`. 2. **Downgrade resources if the helper is untrusted.** If resources came back `Applied` *and* `verify_trusted_helper` fails, the resource outcome is downgraded to `NotApplied { reason }` (or the required case errors). This coupling is real: on Linux the helper is also the cgroup path (it self-applies `rlimit`s and reports limit breaches over the status socket), so advertising systemd limits while the helper is untrusted would be a claim the enforcement path cannot keep. @@ -140,7 +143,7 @@ Only `prepare` is required. `execution_capabilities` and `sandbox_helper_path` a `SandboxChannel::command` is then the actual child command: `Command::new(helper_path) --spec --status `, `current_dir` set to the spec's parent, all three stdio handles piped, `kill_on_drop(true)`, `env_clear()` followed by the node's own baseline. The helper must not inherit the daemon's `LD_*`, `GIT_*` or cloud variables while it is parsing a specification that a deny-list was supposed to keep clean. The environment the *target* will see is not the helper's environment — it is the `environment` array inside the spec, which the helper applies itself after `env_clear()`. -`SandboxChannel::wait` (line 1798) is the handshake, and it is the reason required isolation cannot be spoofed by target output. It selects on cancellation or `timeout(5s, listener.accept())`, then reads one status byte with a 5 s timeout: +`SandboxChannel::wait` is the handshake, and it is the reason required isolation cannot be spoofed by target output. It selects on cancellation or `timeout(5s, listener.accept())`, then reads one status byte with a 5 s timeout: | Status byte | Runner interpretation | | --- | --- | @@ -149,13 +152,13 @@ Only `prepare` is required. `execution_capabilities` and `sandbox_helper_path` a | `1` | Confined and about to spawn: read a second byte. `1` → `Ok(Some(SandboxSession))`; `0` → `AfterTarget(SunnerError::Spawn("sandbox target could not start"))`; anything else → `AfterTarget(Setup("sandbox status was invalid"))` | | other | `BeforeTarget(Setup("sandbox status was invalid"))` | -Cancellation is checked before the accept and before each status read, so a cancel arriving during the handshake cannot produce a target. The third status byte is read later, after the child exits, by `SandboxSession::resource_limits_exceeded` (line 1633) with a 2 s timeout: bit 1 → `ResourceDimension::Memory`, bit 2 → `ResourceDimension::Pids`. +Cancellation is checked before the accept and before each status read, so a cancel arriving during the handshake cannot produce a target. The third status byte is read later, after the child exits, by `SandboxSession::resource_limits_exceeded` with a 2 s timeout: bit 1 → `ResourceDimension::Memory`, bit 2 → `ResourceDimension::Pids`. **What `LANDLOCK_WORKSPACE_RW_CAPABILITY` means.** The constant is the frozen public feature name for the *closed* `workspace_rw` Landlock profile used by both `IsolationRequirement::BestEffort` and `IsolationRequirement::Required`. It is not a version of Landlock itself and not a claim about rlimits — it is a single feature identifier pinned so that a node's advertised feature list and the runner's enforcement decision refer to the same contract. It is asserted literally in `capability_feature_string_is_frozen_for_workspace_rw_profile` so a rename cannot silently break wire compatibility, and it is the same constant the server's `check_isolation_supported` compares against — the runner produces it, the server consumes it, and neither re-types it. ### `NoExecutionSetup` -`NoExecutionSetup` is a unit struct (`#[derive(Debug, Default)]`) meaning "no platform backend is configured". Its `prepare` (line 656) fails closed for anything required: +`NoExecutionSetup` is a unit struct (`#[derive(Debug, Default)]`) meaning "no platform backend is configured". Its `prepare` fails closed for anything required: - `SandboxRequest::Required { .. }` or `resources.has_required()` → `Err(RunnerError::RequiredSetupUnavailable)`. - `SandboxRequest::None` → `SandboxOutcome::NotRequested`. @@ -174,7 +177,7 @@ It does not override `execution_capabilities`, so it inherits the default `Vec:: Both are `Debug + Clone + PartialEq + Eq`, which is what lets `unsupported_resource_limits_are_reported_or_rejected_before_spawn` pattern-match on them directly. -`ResourceSetupRequest` carries three `eggwork_core::Requirement` dimensions and has three private helpers: `is_requested()` (any non-`NotRequested`), `has_required()` (any `Required`), and `properties()` (line 141), which renders systemd properties — `MemoryMax=` plus `MemorySwapMax=0` for memory, `CPUQuota=.%` for CPU (millis to a systemd percentage), `TasksMax=` for pids. +`ResourceSetupRequest` carries three `eggwork_core::Requirement` dimensions and has three private helpers: `is_requested()` (any non-`NotRequested`), `has_required()` (any `Required`), and `properties()`, which renders systemd properties — `MemoryMax=` plus `MemorySwapMax=0` for memory, `CPUQuota=.%` for CPU (millis to a systemd percentage), `TasksMax=` for pids. ### `#[cfg(target_os = "linux")]` gating and fail-closed fallbacks @@ -182,17 +185,17 @@ Landlock and systemd are Linux kernel interfaces, so the crate gates rather than | Linux-only item | Non-Linux fallback | | --- | --- | -| `SystemdCgroupBackend` (real: `discover`, `probe`, `base_command`, `wrap`, `unit_result`, `stop_unit`, `systemctl_path`) | unit struct with only `async fn probe` returning `Err("OS resource controls are unsupported on this platform")` (lines 357-365) | +| `SystemdCgroupBackend` (real: `discover`, `probe`, `base_command`, `wrap`, `unit_result`, `stop_unit`, `systemctl_path`) | unit struct with only `async fn probe` returning `Err("OS resource controls are unsupported on this platform")` | | `resource_unit_name()` | absent (only called from Linux code) | -| `probe_landlock_ruleset()` | `fn probe_landlock_ruleset() -> bool { false }` (lines 581-584) | -| `verify_trusted_helper(path)` | `Err("trusted Landlock is unsupported on this platform")` (lines 640-643) | +| `probe_landlock_ruleset()` | `fn probe_landlock_ruleset() -> bool { false }` | +| `verify_trusted_helper(path)` | `Err("trusted Landlock is unsupported on this platform")` | | `SandboxChannel`, `SandboxSession`, `SandboxLaunchSpec`, `SandboxWaitError`, `wrap_resource_command` | absent; `run` sets `channel: Option<()> = None`, `resource_unit: Option = None`, `resource_limits_exceeded: Vec<..> = Vec::new()`, `resource_cleanup_warning: Option = None` | Every fallback is a refusal or an empty result. None of them is a permissive default, so a non-Linux host cannot accidentally advertise or claim an enforcement capability. ## Helper trust boundary -`verify_trusted_helper` (line 596) is the entire Linux helper trust policy, and it is one function because a second, independently drifting copy is itself a defect. The doc comment explains the failure mode it prevents: "A duplicated stricter copy denies a user-owned helper that this function would accept, which makes an unprivileged user-scope installation permanently unable to advertise required filesystem isolation." +`verify_trusted_helper` is the entire Linux helper trust policy, and it is one function because a second, independently drifting copy is itself a defect. The doc comment explains the failure mode it prevents: "A duplicated stricter copy denies a user-owned helper that this function would accept, which makes an unprivileged user-scope installation permanently unable to advertise required filesystem isolation." **Exact checks, in order:** @@ -204,19 +207,19 @@ Every fallback is a refusal or an empty result. None of them is a permissive def The non-Linux variant is unconditional refusal: `Err("trusted Landlock is unsupported on this platform")`. It does not inspect the path at all, so there is no platform on which this function returns `Ok` without a Landlock-capable kernel. -**The single-delegation invariant.** Within the crate, all three call sites in `TrustedLandlockSetup` go through this one function: resource-downgrade at line 445, sandbox resolution at line 465, and capability advertisement at line 484. Outside the crate, the server's `operations::trusted_helper` is a one-line delegation — `eggwork_runner::verify_trusted_helper(path).is_ok()` at `crates/eggwork-server/src/operations.rs:530` — used by `doctor` so that diagnostics cannot report an answer the enforcement path would refuse. This is what makes "advisory and enforcement can never disagree" a structural property rather than a convention: there is no second implementation to drift. +**The single-delegation invariant.** Within the crate, all three call sites in `TrustedLandlockSetup` go through this one function: the resource downgrade and the sandbox resolution in `TrustedLandlockSetup::prepare`, and the capability advertisement in `TrustedLandlockSetup::execution_capabilities`. Outside the crate, the server's `operations::trusted_helper` is a one-line delegation — `eggwork_runner::verify_trusted_helper(path).is_ok()` in the server's `operations::trusted_helper` — used by `doctor` so that diagnostics cannot report an answer the enforcement path would refuse. This is what makes "advisory and enforcement can never disagree" a structural property rather than a convention: there is no second implementation to drift. `SystemdCgroupBackend` applies an analogous (but independent, and *stricter*) root-only trust pattern to its own binaries: `discover()` requires `/usr/bin/systemd-run` or `/bin/systemd-run` to canonicalize, be a regular file, have `uid() == 0`, have `mode & 0o022 == 0`, and be executable; `systemctl_path()` repeats the same four checks for `/usr/bin/systemctl` or `/bin/systemctl`. These are not the helper trust boundary and are not delegated to `verify_trusted_helper` — the helper is user-scope-installable, `systemd-run` is not. ## Process lifecycle -`LocalProcessRunner::run` (line 1143) is a single `async fn` on `&self` with three arguments: `RunnerRequest`, `CancellationToken`, `mpsc::Sender`. The sequence: +`LocalProcessRunner::run` is a single `async fn` on `&self` with three arguments: `RunnerRequest`, `CancellationToken`, `mpsc::Sender`. The sequence: **1. Cancellation gate.** `cancellation.is_cancelled()` → `Err(RunnerError::CancelledBeforeSpawn)`. Nothing has been touched. **2. Authorized root enforcement.** `let cwd = request.validate()?`. This canonicalizes `root` (requiring a directory), canonicalizes `root.join(cwd)` when a `RelativePath` is present (requiring containment and a directory), and returns the working directory to use. Every `RunnerError::InvalidRequest` / `InvalidRoot` / `InvalidWorkingDirectory` originates here. -**3. Platform gate.** `#[cfg(not(unix))]` returns `Err(RunnerError::UnsupportedPlatform)` immediately after validation — before `prepare`, before any helper, before `spawn`. The `let _ = (cwd, request, output_tx);` on line 1155 is there to keep the unused bindings from becoming warnings on that configuration. +**3. Platform gate.** `#[cfg(not(unix))]` returns `Err(RunnerError::UnsupportedPlatform)` immediately after validation — before `prepare`, before any helper, before `spawn`. The `let _ = (cwd, request, output_tx);` in that arm is there to keep the unused bindings from becoming warnings on that configuration. **4. Setup.** `self.setup.prepare(&request.sandbox, &request.resources, &request.root).await?`. The `?` means a required-sandbox or required-resource refusal is an `Err`, never a silent downgrade to direct execution. @@ -237,7 +240,7 @@ The non-Linux variant is unconditional refusal: `Err("trusted Landlock is unsupp - `Ok(None)` and the request is required — kill, wait, `Err(RunnerError::RequiredSetupUnavailable)`. - `Err(_)` — kill, wait, return the error. `BeforeTarget` errors are recoverable (respawn unwrapped) when nothing was required; `AfterTarget` errors are always terminal. A recoverable `BeforeTarget` error reports the degradation before the respawn, exactly as the `Ok(None)` arm does. -Note the ordering: `let process_group = child.id();` is taken at line 1290, *after* the handshake, so the group that gets signalled is the group of whichever child actually ended up running. +Note the ordering: `let process_group = child.id();` is taken *after* the handshake, so the group that gets signalled is the group of whichever child actually ended up running. **10. Stdin.** For `StdinPolicy::Bytes(bytes)`, a `tokio::spawn`ed task does `stdin.write_all(&bytes).await` then `drop(stdin)` to close the pipe. For `StdinPolicy::Null` the pipe is dropped immediately (child sees EOF). The `Bytes` arm also has a defensive third case (`StdinPolicy::Bytes(_)` with no piped handle) that drops the handle, so a child that never reads stdin cannot wedge on a full pipe. @@ -245,7 +248,7 @@ Note the ordering: `let process_group = child.id();` is taken at line 1290, *aft **12. Output monitor.** `let (overflow_tx, mut overflow_rx) = watch::channel(false);` — a single watcher shared by both readers so that either stream crossing the capture limit can terminate the execution. -**13. The wait race** (line 1346), `tokio::select! { biased; … }` in this precedence order: +**13. The wait race**, `tokio::select! { biased; … }` in this precedence order: ```rust _ = cancellation.cancelled() => Some((Cancelled, None, None)), @@ -254,9 +257,9 @@ _ = overflow_rx.changed() => monitor_termination(*overflow_rx.borrow()) result = child.wait() => Some((Exited, status?, error?)), ``` -`biased` is intentional and the ordering is a policy: cancellation outranks timeout, which outranks overflow, which outranks natural exit. A `None` result (the monitor settled *without* overflow — which can only happen after both readers hit EOF, which can only happen after the child exited) falls through to a second `child.wait()` at line 1364 so the real exit status is recovered instead of being discarded. The comment at lines 1337-1341 explains the code shape too: the `child.wait()` continuation lives *after* the `select!` rather than inside an arm because awaiting it inside an arm makes the future `!Send`, and this `select!` runs inside a spawned task. +`biased` is intentional and the ordering is a policy: cancellation outranks timeout, which outranks overflow, which outranks natural exit. A `None` result (the monitor settled *without* overflow — which can only happen after both readers hit EOF, which can only happen after the child exited) falls through to a second `child.wait()` after the `select!` so the real exit status is recovered instead of being discarded. The in-source comment above the `select!` explains the code shape too: the `child.wait()` continuation lives *after* the `select!` rather than inside an arm because awaiting it inside an arm makes the future `!Send`, and this `select!` runs inside a spawned task. -`monitor_termination(bool) -> Option` (line 1559) is the whole distinction in one line: `overflowed.then_some(TerminationReason::OutputLimit)`. `Some` is a termination; `None` is not. The in-source rationale is that the settled-but-not-overflowed case used to be reported as `Exited` with a `None` status, surfacing as `state: Failed, failure: Internal, exit_code: null` — a shape that reads as a product failure and is not one. +`monitor_termination(bool) -> Option` is the whole distinction in one line: `overflowed.then_some(TerminationReason::OutputLimit)`. `Some` is a termination; `None` is not. The in-source rationale is that the settled-but-not-overflowed case used to be reported as `Exited` with a `None` status, surfacing as `state: Failed, failure: Internal, exit_code: null` — a shape that reads as a product failure and is not one. **14. Resource attribution (Linux).** Only when `termination == Exited`: ask the session for its status byte (`Memory`/`Pids` bits), then independently re-discover the backend and check `systemctl show --property=Result --value` (1 s timeout) for `"oom-kill"`, which adds `Memory` if not already present. Two independent sources for the same fact, because a cgroup OOM kill and a helper-reported rlimit breach are not the same signal. @@ -301,7 +304,7 @@ The `#[cfg(windows)]` branch was originally unreachable: `run` refused on non-Un ### Bounded capture: head and tail -`BoundedCapture` (line 66) retains `head: Vec`, `tail: VecDeque`, `total_bytes: u64`, `omitted_bytes: u64`. `push(bytes, limit)` (line 84): +`BoundedCapture` retains `head: Vec`, `tail: VecDeque`, `total_bytes: u64`, `omitted_bytes: u64`. `BoundedCapture::push(bytes, limit)`: ```rust let head_limit = limit.div_ceil(2); @@ -315,7 +318,7 @@ Consequences worth checking as a reviewer: retention is exactly `limit` bytes fo ### Streaming: dropping chunks while draining continues -`spawn_reader` (line 1873) is the drain loop. Per read of at most `READ_BUFFER.min(chunk_limit)` bytes (8192 cap): +`spawn_reader` is the drain loop. Per read of at most `READ_BUFFER.min(chunk_limit)` bytes (8192 cap): 1. `capture.push(&buffer[..count], capture_limit)` — always, before anything else. 2. If `overflow == Terminate` and `total_bytes` crossed `capture_limit` on this read (`before <= capture_limit && after > capture_limit`), `overflow_tx.send(true)`. @@ -325,7 +328,7 @@ Why this is the right trade: the reader's job is to keep the pipe empty, because ## Termination and cleanup -`TERMINATION_GRACE = Duration::from_millis(300)` (line 39) is the single grace constant, used both as the `SIGTERM → SIGKILL` delay and as the bound on the post-`SIGKILL` `child.wait()`. +`TERMINATION_GRACE = Duration::from_millis(300)` is the single grace constant, used both as the `SIGTERM → SIGKILL` delay and as the bound on the post-`SIGKILL` `child.wait()`. | Trigger | `TerminationReason` | Mechanism | | --- | --- | --- | @@ -337,15 +340,15 @@ Why this is the right trade: the reader's job is to keep the pipe empty, because | cancellation during the sandbox handshake | *(no result)* | `Err(SandboxWaitError::{BeforeTarget, AfterTarget}(CancelledBeforeSpawn))` → `RunnerError::CancelledBeforeSpawn` | | leader exited normally, no descendants | `Exited` | `killpg` returns `ESRCH` → `Ok(false)` → immediate return, no grace sleep | -**Signalling.** `terminate_group` (line 1845) and `kill_group` (line 1857) are `#[cfg(unix)]` and both use `nix::sys::signal::killpg` on the pid captured from `child.id()`. `terminate_group` maps `ESRCH` to `Ok(false)` (nothing to signal) and any other errno to `Err(String)`; `kill_group` maps `ESRCH` to success and propagates other errnos. The group works because `command.process_group(0)` makes the direct child the group leader, so `killpg` reaches every descendant that stayed in the group. +**Signalling.** `terminate_group` and `kill_group` are `#[cfg(unix)]` and both use `nix::sys::signal::killpg` on the pid captured from `child.id()`. `terminate_group` maps `ESRCH` to `Ok(false)` (nothing to signal) and any other errno to `Err(String)`; `kill_group` maps `ESRCH` to success and propagates other errnos. The group works because `command.process_group(0)` makes the direct child the group leader, so `killpg` reaches every descendant that stayed in the group. **Grace, force, reap.** `SIGTERM` gives cooperative children a chance to flush and exit; `SIGKILL` after 300 ms bounds the wait; `timeout(TERMINATION_GRACE, child.wait())` bounds the reap so a pathological child cannot hold the caller's future. The leader is always reaped; descendants are killed but reaped by init/the subreaper, which is why the descendant tests assert `/proc//stat` is absent or state `Z`. -**The rule that cleanup never rewrites a known exit outcome.** In the `Some(status)` branch the group is cleaned *after* the status is known and the status is returned unchanged. The known reason survives every cleanup failure, and the only representation of that failure is `CleanupDiagnostics`. `CleanupDiagnostics` has three independent fields — `process_group_signal_error`, `wait_error`, `stdin_error` — and `execution_result` folds them into a single `cleanup_warning` by priority (`process_group_signal_error` → `wait_error` → `stdin_error`, lines 1010-1015) while `state`, `exit_code`, and `failure` are computed solely from `termination`, `exit_code`, and `resource_limits_exceeded`. `cleanup_warning_does_not_rewrite_process_outcome` pins this: an `Exited`/`Some(9)` result with a `process_group_signal_error` still reports `Failed` with `exit_code: Some(9)` and the warning attached. This is the crate-side implementation of ADR-0003's "Terminal state is single-assignment. Cleanup diagnostics may be appended without changing the chosen terminal outcome." +**The rule that cleanup never rewrites a known exit outcome.** In the `Some(status)` branch the group is cleaned *after* the status is known and the status is returned unchanged. The known reason survives every cleanup failure, and the only representation of that failure is `CleanupDiagnostics`. `CleanupDiagnostics` has three independent fields — `process_group_signal_error`, `wait_error`, `stdin_error` — and `execution_result` folds them into a single `cleanup_warning` by priority (`process_group_signal_error` → `wait_error` → `stdin_error`) while `state`, `exit_code`, and `failure` are computed solely from `termination`, `exit_code`, and `resource_limits_exceeded`. `cleanup_warning_does_not_rewrite_process_outcome` pins this: an `Exited`/`Some(9)` result with a `process_group_signal_error` still reports `Failed` with `exit_code: Some(9)` and the warning attached. This is the crate-side implementation of ADR-0003's "Terminal state is single-assignment. Cleanup diagnostics may be appended without changing the chosen terminal outcome." ## Result and error model -`RunnerResult` (line 962): +`RunnerResult`: | Field | Meaning | | --- | --- | @@ -414,7 +417,7 @@ server drains the output channel before it publishes the terminal state. itself: the payload and the terminal snapshot are derived from the same `SetupOutcome`, so the two cannot disagree. -`RunnerResult::execution_result()` (line 977) — also reachable via `impl From for ExecutionResult` (line 1924) — maps to the protocol-neutral result: +`RunnerResult::execution_result()` — also reachable via `impl From for ExecutionResult` — maps to the protocol-neutral result: | Condition | `ExecutionState` | `ExecutionFailure` | | --- | --- | --- | @@ -426,13 +429,13 @@ server drains the output channel before it publishes the terminal state. | `Cancelled` | `Cancelled` | `None` | | `OutputLimit` | `Failed` | `OutputLimit` | -`resource_limits_exceeded` outranks termination: a run that was killed by its own memory limit is `ResourceLimit`, not the incidental `TimedOut`/`Exited` that came with it. `Exited` with `exit_code: None` is the `Internal` shape — it covers both a leader that died from a signal and a `child.wait()` that returned an error (the latter also carrying `cleanup.wait_error`). `resource_result` (line 1039) then reports each resource dimension independently as `NotRequested` / `NotApplied { reason }` / `Applied { backend }` / `LimitExceeded { backend }`, so a partially satisfied resource request is visible per dimension rather than collapsed. +`resource_limits_exceeded` outranks termination: a run that was killed by its own memory limit is `ResourceLimit`, not the incidental `TimedOut`/`Exited` that came with it. `Exited` with `exit_code: None` is the `Internal` shape — it covers both a leader that died from a signal and a `child.wait()` that returned an error (the latter also carrying `cleanup.wait_error`). `RunnerResult::resource_result` then reports each resource dimension independently as `NotRequested` / `NotApplied { reason }` / `Applied { backend }` / `LimitExceeded { backend }`, so a partially satisfied resource request is visible per dimension rather than collapsed. -`RunnerError` (line 1086) is the refusal/failure channel, with these exact messages: +`RunnerError` is the refusal/failure channel, with these exact messages: | Variant | Meaning | | --- | --- | -| `InvalidRequest(String)` | argv, environment, output limits, timeout, or stdin violate bounds/syntax; no child existed | +| `InvalidRequest(eggwork_core::ValidationError)` | argv, environment, output limits, timeout, stdin, or resources violate the core domain contract; no child existed. The payload is the typed core error, so the rule that refused the request stays identifiable | | `InvalidRoot(String)` | root failed to canonicalize or is not a directory; no child existed | | `InvalidWorkingDirectory(String)` | cwd failed to canonicalize, escapes root, or is not a directory; no child existed | | `CancelledBeforeSpawn` | cancellation observed before the child ran; no child existed | @@ -450,17 +453,17 @@ server drains the output channel before it publishes the terminal state. - *Ran and classified* — `Ok(RunnerResult)`. The `TerminationReason` plus `exit_code` is the answer. - *Ran and broke* — `Io` / `Wait` mean a child existed but the result could not be assembled. Note that on this path the captured stdout/stderr are lost: `join_reader(...).await?` returns before the `RunnerResult` is constructed. -The server is the reference consumer. `failure_for_runner_error` at `crates/eggwork-server/src/lib.rs:2557` maps `Spawn` → `ExecutionFailure::Spawn`, `CancelledBeforeSpawn` → `Interrupted`, and everything else — including `UnsupportedPlatform` — → `Internal`, with lease expiry taking precedence over both. +The server is the reference consumer. `failure_for_runner_error` in the server maps `Spawn` → `ExecutionFailure::Spawn`, `CancelledBeforeSpawn` → `Interrupted`, and everything else — including `UnsupportedPlatform` — → `Internal`, with lease expiry taking precedence over both. ## Concurrency model -`LocalProcessRunner` is a thin newtype over `Box` (`Send + Sync`), holding no mutable state, so one instance can serve any number of concurrent `run` calls. Callers drive concurrency by spawning: the server wraps `runner.run(...)` in a `tokio::spawn`ed task and joins it in its own `select!` (`crates/eggwork-server/src/lib.rs:2406`). +`LocalProcessRunner` is a thin newtype over `Box` (`Send + Sync`), holding no mutable state, so one instance can serve any number of concurrent `run` calls. Callers drive concurrency by spawning: the server wraps `runner.run(...)` in a `tokio::spawn`ed task and joins it in its own `select!` (in the server's execute path). **Inside one `run`, at most three additional tasks exist:** | Task | Spawned by | Work | | --- | --- | --- | -| stdin writer | `tokio::spawn` (line 1294) | `write_all` on the piped stdin handle, then `drop` to close; only for `StdinPolicy::Bytes` | +| stdin writer | `tokio::spawn` | `write_all` on the piped stdin handle, then `drop` to close; only for `StdinPolicy::Bytes` | | stdout reader | `spawn_reader` → `tokio::spawn` | async pipe reads, `BoundedCapture` maintenance, `try_send` streaming, overflow signalling | | stderr reader | `spawn_reader` → `tokio::spawn` | same, with `stderr: true` | @@ -470,7 +473,7 @@ Plus the calling future, which drives the `select!` and then all the sequential **Permits.** The runner holds no permit. Per [execution-ownership.md](execution-ownership.md) and ADR-0005 §8, the server acquires its local-admission permit before invoking `run` and releases it exactly once after runner cleanup converges — which is why `run` performs its own process-group cleanup synchronously before returning, and why returning early with `Err` (spawn failure) is a path the server must still release on. -**Cancellation safety.** The token is observed at exactly four points: the pre-spawn check (line 1149), `listener.accept()` and each of the two status reads inside `SandboxChannel::wait`, and the main `select!`. After the `select!` the token is *never* consulted again: SIGTERM, grace, SIGKILL, and reap all run unconditionally. That is deliberate — a cancel arriving mid-cleanup must not be able to abandon a still-live process group. The consequence is that a request which is both cancelled and about to finish is classified by the `biased` precedence (cancellation wins over a concurrent natural exit) and gets exactly one terminal outcome, never two. +**Cancellation safety.** The token is observed at exactly four points: the pre-spawn check in `LocalProcessRunner::run`, `listener.accept()` and each of the two status reads inside `SandboxChannel::wait`, and the main `select!`. After the `select!` the token is *never* consulted again: SIGTERM, grace, SIGKILL, and reap all run unconditionally. That is deliberate — a cancel arriving mid-cleanup must not be able to abandon a still-live process group. The consequence is that a request which is both cancelled and about to finish is classified by the `biased` precedence (cancellation wins over a concurrent natural exit) and gets exactly one terminal outcome, never two. Drop-safety is partial by design. Every `Command` sets `.kill_on_drop(true)`, so aborting the `run` task kills the direct child. The process *group* is not reaped on drop, so an abort during the cleanup window can leave descendants for the OS to deal with. The in-source design assumption is that callers join the `run` task rather than aborting it. @@ -479,7 +482,7 @@ Drop-safety is partial by design. Every `Command` sets `.kill_on_drop(true)`, so | Invariant | Enforcement site | Test coverage | | --- | --- | --- | | Only approved crates create OS children | `scripts/check_execution_ownership.py` allowlist; `process_group(0)` + `spawn` in `direct_command`/`SandboxChannel::command` | guard script's own negative self-test; `cancellation_before_spawn_and_spawn_failure_are_typed` (typed `Spawn`) | -| A request cannot bypass protocol bounds | private fields; `RunnerRequest::validate` called at the top of `run` (line 1152) | indirect only — see Test coverage | +| A request cannot bypass protocol bounds | private fields; the core rules consumed by `RunnerRequest::contract_violation`; `RunnerRequest::validate` called at the top of `run` | `crates/eggwork-runner/tests/request_validation_parity.rs` — every public construction path reaches the same verdict as `from_spec`, and a refused request never reaches a child | | cwd is confined to the authorized root | `validate`: canonicalize + `starts_with(&root)` | `cwd_is_confined_and_output_limit_terminates` (positive `pwd`); negative symlink case lives in `crates/eggwork-sandbox-helper/tests/landlock_runner.rs` | | Child environment is cleared and rebuilt | `env_clear()` in `direct_command`; `build_child_environment`; `baseline_child_environment`; the shared `environment_policy` module | `captures_exit_stdin_and_sanitizes_environment` asserts `LD_PRELOAD` arrives unset; `crates/eggwork-runner/tests/environment_policy.rs` asserts the node-owned keys and the deny-list | | Stdin is bounded and then closed | `StdinPolicy::validate` + `MAX_STDIN_BYTES`; `write_all` then `drop` | `captures_exit_stdin_and_sanitizes_environment` (bytes path) | @@ -502,11 +505,11 @@ Drop-safety is partial by design. Every `Command` sets `.kill_on_drop(true)`, so | Platform | What works | What fails closed | Cited source | | --- | --- | --- | --- | -| Linux (x86_64, the exercised path) | Full lifecycle: `process_group(0)`, `killpg` termination and reaping, direct or helper-wrapped launch, Landlock `workspace_rw` via the trusted helper, systemd cgroup-v2 resource wrapping, helper status-byte and `Result=oom-kill` limit attribution, `systemctl stop` unit cleanup. Default setup is `TrustedLandlockSetup::discover_sibling()`. | Untrusted/missing helper → no `isolation.landlock.workspace-rw.v1`; required sandbox → `Err(Setup)`; required resources with an unavailable backend → `Err(Setup)`; `#[cfg]`-gated deps keep everything else out of the build | lines 159-365, 537-643, 1164-1211, 1369-1397 | -| macOS / other Unix | Process lifecycle only: `direct_command`, `process_group(0)`, `killpg` SIGTERM/SIGKILL, bounded capture, timeout/cancellation/overflow, `UnsupportedPlatform` not applicable. Default setup is `NoExecutionSetup`. | `verify_trusted_helper` → `Err("trusted Landlock is unsupported on this platform")`; `probe_landlock_ruleset` → `false`; `SystemdCgroupBackend::probe` → `Err("OS resource controls are unsupported on this platform")`; required sandbox or resources → `Err(RequiredSetupUnavailable)`; capability advertisement is empty | lines 357-365, 581-584, 640-643, 654-683, 1115-1126 | +| Linux (x86_64, the exercised path) | Full lifecycle: `process_group(0)`, `killpg` termination and reaping, direct or helper-wrapped launch, Landlock `workspace_rw` via the trusted helper, systemd cgroup-v2 resource wrapping, helper status-byte and `Result=oom-kill` limit attribution, `systemctl stop` unit cleanup. Default setup is `TrustedLandlockSetup::discover_sibling()`. | Untrusted/missing helper → no `isolation.landlock.workspace-rw.v1`; required sandbox → `Err(Setup)`; required resources with an unavailable backend → `Err(Setup)`; `#[cfg]`-gated deps keep everything else out of the build | `TrustedLandlockSetup`, `verify_trusted_helper`, `SandboxChannel`, `SystemdCgroupBackend` | +| macOS / other Unix | Process lifecycle only: `direct_command`, `process_group(0)`, `killpg` SIGTERM/SIGKILL, bounded capture, timeout/cancellation/overflow, `UnsupportedPlatform` not applicable. Default setup is `NoExecutionSetup`. | `verify_trusted_helper` → `Err("trusted Landlock is unsupported on this platform")`; `probe_landlock_ruleset` → `false`; `SystemdCgroupBackend::probe` → `Err("OS resource controls are unsupported on this platform")`; required sandbox or resources → `Err(RequiredSetupUnavailable)`; capability advertisement is empty | `SystemdCgroupBackend`, `probe_landlock_ruleset`, `verify_trusted_helper`, `NoExecutionSetup` | | Windows | Full lifecycle through the Job Object backend: pre-run job assignment (`CREATE_SUSPENDED` → assign → resume), `TerminateJobObject` convergence for leader exit, timeout, cancellation, and output limit, bounded capture, stdin delivery, the `#[cfg(windows)]` environment baseline. Default setup is `NoExecutionSetup`. | Required sandbox or resources → `Err(RequiredSetupUnavailable)` (Windows has no Landlock and no cgroup backend), capability advertisement is empty, and the receipt reports `sandbox: NotRequested` rather than claiming confinement. | `process_tree.rs` (`cfg(windows)`), `windows_process_tree.rs` | | Any other non-Unix compile target | Request validation only — `RunnerRequest::validate` still runs, so bounds and root/cwd confinement are enforced. | `Err(RunnerError::UnsupportedPlatform)` ("process-tree control is unsupported on this platform") raised by `ProcessTree::spawn_platform`; the server maps it to `ExecutionFailure::Internal`. | `process_tree.rs` (`cfg(not(any(unix, windows)))`) | -| Any platform, `NoExecutionSetup` | Direct launch, full lifecycle | `Err(RequiredSetupUnavailable)` for required sandbox or required resources; empty dynamic capability list | lines 654-683, 1115-1126 | +| Any platform, `NoExecutionSetup` | Direct launch, full lifecycle | `Err(RequiredSetupUnavailable)` for required sandbox or required resources; empty dynamic capability list | `NoExecutionSetup` | Per the closure evidence in `plans/closure/security-isolation-resource/004-status.md`, only the Linux host class is isolation-qualified. Foundation M004 (see `plans/closure/foundation-execution-core/004-status.md`) qualified the Windows *execution* path on a hosted `windows-latest` runner; Windows remains isolation-free by construction, because the only isolation backend in this repository is Landlock, and that backend fails closed there rather than degrading. `landlock` is a Linux-only kernel API and the `Cargo.toml` comment says so: "every required release target that is not Linux builds this crate, and all `landlock::` uses are already `#[cfg(target_os = "linux")]`-gated with fail-closed fallbacks." @@ -529,7 +532,7 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu ## Test coverage -`mod tests` (line 1930) contains 17 test functions plus two helpers. It constructs `RunnerRequest` by *literal struct expression*, which only compiles because the tests are inside the module that owns the private fields — itself a small proof that privacy is enforced by the compiler rather than by lint. +`mod tests` contains 29 test functions plus a request helper; the table below is a selection of them, not the whole suite. It constructs `RunnerRequest` by *literal struct expression*, which only compiles because the tests are inside the module that owns the private fields — itself a small proof that privacy is enforced by the compiler rather than by lint. | Test | Asserts | | --- | --- | @@ -559,11 +562,13 @@ Per the closure evidence in `plans/closure/security-isolation-resource/004-statu `SandboxChannel` internals are covered from the helper crate's integration test, `crates/eggwork-sandbox-helper/tests/landlock_runner.rs`, which drives the runner's public API: outside read/write denial, helper trust rejections (missing/wrong/symlinked), workspace and cwd symlink escapes, timeout and cancellation reaping the helper's own process group, required memory/PID/CPU enforcement and classification, concurrent cgroup scope isolation, and `malformed_private_spec_and_unavailable_status_channel_do_not_launch_target`. +`crates/eggwork-runner/tests/request_validation_parity.rs` is the request-contract suite. It drives the runner through its **public** API only — the builder path (`RunnerRequest::new` plus the setters) and the protocol path (`from_spec`) — because a test that only exercised `eggwork_core` would have passed before the corrective and would have proved nothing about the runner. The proofs are: every public construction path reaches the same verdict as `from_spec` for the same input, with the same typed error; every environment-name form core rejects is refused through the runner, with the refusal attributable to the name rule; a repeated environment name is refused by the duplicate-name rule specifically; the runner refuses an empty argv entry that core permits, which is the one place it is stricter; the stdin and output bounds are core's bounds; the mutable resource door is covered even though it cannot validate on the way in; a refused request never reaches a child (proved with a marker file); and the public surface of `RunnerRequest` is pinned by a test that fails if a new public entry point is added. `crates/eggwork-core/tests/environment_rule_partition.rs` is the other half: it re-derives the documented environment-entry rule independently of the implementation and proves that the accepted and rejected sets partition the candidate space, so a rule change cannot silently open a gap. + `crates/eggwork-runner/tests/environment_policy.rs` is the environment-policy suite on the runner's side: it asserts that the shared policy is reachable from the runner's public API, that the node-owned class and the node-owned baseline are the same list, that the baseline the runner installs is the policy's baseline, and — through a real child — that a caller's value for a node-owned key does not reach the child while a denied key does not either and a caller-controlled key does. The other half of that proof is `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs`, which drives the real helper binary: it compares the two generated copies of the policy element by element, drives the helper with a launch specification for every probe key and compares its accept/refuse decision with what the runner's copy of the policy says, proves that a caller-supplied node-owned key keeps the execution confined, and proves that the direct path and the helper path build the same environment. **Thin areas, honestly:** -- **No unit test rejects a bad `RunnerRequest`.** Every `RunnerError::InvalidRequest` branch — empty/NUL/oversized argv, environment count and size bounds, `=` in an environment name, `capture_limit` over 16 MiB, `event_chunk_bytes` of 0, zero or over-maximum timeout, stdin over 4 MiB — is unexercised. The only escaping test is `cwd` under a valid root. +- **The `RunnerError::InvalidRequest` branches are now exercised; the root/cwd rules still are not.** `crates/eggwork-runner/tests/request_validation_parity.rs` covers every core-owned rule the runner consumes — empty/NUL/oversized argv, the argv count bound, the environment count/name/value/duplicate rules, `capture_limit` over 16 MiB, `event_chunk_bytes` of 0 or over 64 KiB, a zero or over-maximum timeout, stdin over 4 MiB, and an out-of-range resource requirement — through the runner's public API, and asserts that a refused request never reaches a child. The root/cwd resolution is the remaining gap, and it is the bullet below. - **No test covers a cwd that escapes root** (`..`, absolute, or a symlink) at the runner level; that assertion lives in the helper crate's test, and only for the symlink form. - **No test covers `RunnerError::UnsupportedPlatform`.** The path is now `cfg(not(any(unix, windows)))`, which is not a release target, so the refusal stays asserted only by code reading. Windows no longer takes this path. - **Pre-run Job Object assignment is a property of the dependency, not of a test.** `process-wrap` adds `CREATE_SUSPENDED`, assigns, and resumes inside `spawn`; the suite can observe the consequences (a descendant created in the target's first moments is owned, a spawn failure leaves nothing running) but cannot observe the assignment itself from outside the process without Win32 tracing. That is stated rather than glossed: the evidence is "no descendant ever escaped", not "the kernel was entered in this state". diff --git a/crates/eggwork-core/src/lib.rs b/crates/eggwork-core/src/lib.rs index be6abae..116f552 100644 --- a/crates/eggwork-core/src/lib.rs +++ b/crates/eggwork-core/src/lib.rs @@ -763,55 +763,93 @@ impl fmt::Debug for CommandSpec { .finish() } } +/// Validate an argv vector against the core contract. +/// +/// This is the single owner of the argv rules: the vector is non-empty, its +/// length is bounded by [`MAX_ARG_COUNT`], and every entry is bounded by +/// [`MAX_ARG_BYTES`] and free of NUL. [`CommandSpec::validate`] and the +/// runner both consume this function, so the two cannot drift apart. +/// +/// The runner is permitted to be *stricter* than this — it rejects an empty +/// argv entry, which this contract permits, because an empty entry is a +/// child-process construction hazard rather than a protocol concern. That +/// addition is the runner's own rule and it is documented and tested there. +pub fn validate_argv(argv: &[String]) -> Result<(), ValidationError> { + if argv.is_empty() { + return Err(ValidationError::Empty { field: "argv" }); + } + if argv.len() > MAX_ARG_COUNT { + return Err(ValidationError::TooMany { + field: "argv", + max: MAX_ARG_COUNT, + }); + } + if argv + .iter() + .any(|a| a.len() > MAX_ARG_BYTES || a.as_bytes().contains(&0)) + { + return Err(ValidationError::OutOfRange { + field: "argv entry", + }); + } + Ok(()) +} + +/// Validate a complete environment list against the core contract. +/// +/// This is the single owner of the environment-entry rules: the list length is +/// bounded by [`MAX_ENV_COUNT`], every entry's name and value satisfy +/// [`EnvironmentEntry::new`], and no two entries share a name. +/// +/// The entries are re-validated rather than trusted, because +/// [`EnvironmentEntry`] has public fields: a caller can build one that +/// [`EnvironmentEntry::new`] would have refused. [`CommandSpec::validate`] and +/// the runner both consume this function. +pub fn validate_environment_entries(entries: &[EnvironmentEntry]) -> Result<(), ValidationError> { + if entries.len() > MAX_ENV_COUNT { + return Err(ValidationError::TooMany { + field: "environment", + max: MAX_ENV_COUNT, + }); + } + for entry in entries { + EnvironmentEntry::new(&entry.name, &entry.value)?; + } + let mut environment_names = std::collections::HashSet::with_capacity(entries.len()); + if entries + .iter() + .any(|entry| !environment_names.insert(entry.name.as_str())) + { + return Err(ValidationError::InvalidSyntax { + field: "duplicate environment name", + }); + } + Ok(()) +} + +/// Validate an execution timeout against the core contract. +/// +/// This is the single owner of the timeout rule: the timeout is non-zero and +/// no longer than [`MAX_TIMEOUT`]. [`CommandSpec::validate`] and the runner +/// both consume this function. +pub fn validate_timeout(timeout: Duration) -> Result<(), ValidationError> { + if timeout.is_zero() || timeout > MAX_TIMEOUT { + return Err(ValidationError::OutOfRange { field: "timeout" }); + } + Ok(()) +} + impl CommandSpec { pub fn validate(&self) -> Result<(), ValidationError> { - if self.argv.is_empty() { - return Err(ValidationError::Empty { field: "argv" }); - } - if self.argv.len() > MAX_ARG_COUNT { - return Err(ValidationError::TooMany { - field: "argv", - max: MAX_ARG_COUNT, - }); - } - if self - .argv - .iter() - .any(|a| a.len() > MAX_ARG_BYTES || a.as_bytes().contains(&0)) - { - return Err(ValidationError::OutOfRange { - field: "argv entry", - }); - } - if self.environment.len() > MAX_ENV_COUNT { - return Err(ValidationError::TooMany { - field: "environment", - max: MAX_ENV_COUNT, - }); - } - for e in &self.environment { - EnvironmentEntry::new(&e.name, &e.value)?; - } - let mut environment_names = - std::collections::HashSet::with_capacity(self.environment.len()); - if self - .environment - .iter() - .any(|entry| !environment_names.insert(entry.name.as_str())) - { - return Err(ValidationError::InvalidSyntax { - field: "duplicate environment name", - }); - } + validate_argv(&self.argv)?; + validate_environment_entries(&self.environment)?; if self.declared_outputs.len() > MAX_OUTPUTS { return Err(ValidationError::TooMany { field: "declared outputs", max: MAX_OUTPUTS, }); } - if self.timeout_millis == 0 || self.timeout_millis > MAX_TIMEOUT.as_millis() as u64 { - return Err(ValidationError::OutOfRange { field: "timeout" }); - } + validate_timeout(Duration::from_millis(self.timeout_millis))?; self.stdin.validate()?; self.output.validate()?; self.resources.validate()?; diff --git a/crates/eggwork-core/tests/environment_rule_partition.rs b/crates/eggwork-core/tests/environment_rule_partition.rs new file mode 100644 index 0000000..5cd8d26 --- /dev/null +++ b/crates/eggwork-core/tests/environment_rule_partition.rs @@ -0,0 +1,274 @@ +//! The core environment-entry rules partition the input space. +//! +//! The environment-entry contract is the rule set the runner consumes, so it +//! has to be *total*: for every name, value and list there is exactly one +//! answer, and that answer is the documented one. A rule change that widened +//! the accepted set or narrowed it would silently open a gap between what the +//! contract says and what it enforces, and the gap would only be visible to a +//! reader who happened to know the old rule. +//! +//! This suite therefore does two things at once: +//! +//! 1. It re-derives the documented rule *independently* of the implementation +//! -- the predicate below is written from the rule's prose, not from the +//! code -- and asserts that the implementation agrees with it on every +//! candidate. +//! 2. It computes the accepted set and the rejected set as sets and asserts +//! that they are disjoint and that their union is the whole candidate +//! space. A rule change that moved a name from one set to the other +//! therefore has to be accompanied by a change to the documented predicate, +//! and the test fails if it is not. +//! +//! The name rule, as documented: +//! +//! - the name is not empty; +//! - the name is at most `MAX_ENV_NAME_BYTES` bytes long; +//! - the name is composed only of ASCII alphanumerics and underscore; +//! - the name does not start with a digit; +//! - the name contains no NUL byte. + +use eggwork_core::{ + EnvironmentEntry, MAX_ENV_COUNT, MAX_ENV_NAME_BYTES, MAX_ENV_VALUE_BYTES, ValidationError, + validate_environment_entries, +}; + +/// The documented environment-name rule, re-derived independently. +fn documented_name_is_accepted(name: &str) -> bool { + !name.is_empty() + && name.len() <= MAX_ENV_NAME_BYTES + && name + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_') + && !name.as_bytes().first().is_some_and(u8::is_ascii_digit) + && !name.as_bytes().contains(&0) +} + +/// Every candidate name the partition is proved over. +fn candidate_names() -> Vec { + let mut names = vec![ + // The shortest and the most ordinary shapes. + String::new(), + "A".to_owned(), + "Z".to_owned(), + "a".to_owned(), + "z".to_owned(), + "_".to_owned(), + "A0".to_owned(), + "A_".to_owned(), + "_A".to_owned(), + "API_TOKEN".to_owned(), + // A leading digit is refused even though the rest of the name is legal. + "0".to_owned(), + "9".to_owned(), + "1BAD".to_owned(), + "0A".to_owned(), + // Characters outside ASCII alphanumerics and underscore. + "A-B".to_owned(), + "A.B".to_owned(), + "A B".to_owned(), + "A+B".to_owned(), + "A/B".to_owned(), + "A:B".to_owned(), + // `=` would split the name from the value in the child's environment. + "A=B".to_owned(), + // NUL cannot survive into an environment vector at all. + "A\0B".to_owned(), + // Non-ASCII bytes are not ASCII alphanumerics. + "Aé".to_owned(), + "Ä".to_owned(), + "Ω".to_owned(), + ]; + // The length bound, on both sides. + names.push("A".repeat(MAX_ENV_NAME_BYTES)); + names.push("A".repeat(MAX_ENV_NAME_BYTES + 1)); + names.push("_".repeat(MAX_ENV_NAME_BYTES)); + names.push("_".repeat(MAX_ENV_NAME_BYTES + 1)); + names +} + +#[test] +fn the_accepted_and_rejected_name_sets_partition_the_candidate_space() { + let candidates = candidate_names(); + let mut accepted = Vec::new(); + let mut rejected = Vec::new(); + + for name in &candidates { + let entry = EnvironmentEntry { + name: name.clone(), + value: "value".to_owned(), + }; + let verdict = validate_environment_entries(std::slice::from_ref(&entry)); + let implemented_accepts = verdict.is_ok(); + let documented_accepts = documented_name_is_accepted(name); + + assert_eq!( + implemented_accepts, documented_accepts, + "the implementation and the documented rule disagree about {name:?}: \ + implemented accepted = {implemented_accepts}, documented accepted = {documented_accepts}" + ); + + if implemented_accepts { + accepted.push(name.clone()); + } else { + rejected.push(name.clone()); + assert!( + matches!( + verdict, + Err(ValidationError::InvalidSyntax { + field: "environment name" + }) + ), + "a refused name must be refused by the name rule: {name:?} -> {verdict:?}" + ); + } + } + + // The two sets are disjoint, and together they are the whole candidate + // space. Stated explicitly, because "the implementation agreed with the + // predicate" alone would not catch a candidate that was never classified. + for name in &accepted { + assert!( + !rejected.contains(name), + "{name:?} is in both the accepted and the rejected set" + ); + } + for name in &rejected { + assert!( + !accepted.contains(name), + "{name:?} is in both the accepted and the rejected set" + ); + } + assert_eq!( + accepted.len() + rejected.len(), + candidates.len(), + "every candidate must land in exactly one set" + ); + + // The sets are not trivially one-sided: the partition says something about + // a real boundary, so both sides must be populated. + assert!(!accepted.is_empty(), "no candidate name is accepted"); + assert!(!rejected.is_empty(), "no candidate name is rejected"); + assert!( + accepted.contains(&"A".repeat(MAX_ENV_NAME_BYTES)), + "a name exactly at the bound must be accepted" + ); + assert!( + rejected.contains(&"A".repeat(MAX_ENV_NAME_BYTES + 1)), + "a name one byte over the bound must be rejected" + ); +} + +#[test] +fn the_accepted_and_rejected_value_sets_partition_the_candidate_space() { + let mut accepted = Vec::new(); + let mut rejected = Vec::new(); + + let candidates = vec![ + String::new(), + "value".to_owned(), + "a value with spaces".to_owned(), + "a\0value".to_owned(), + "v".repeat(MAX_ENV_VALUE_BYTES), + "v".repeat(MAX_ENV_VALUE_BYTES + 1), + ]; + + for value in &candidates { + let entry = EnvironmentEntry { + name: "NAME".to_owned(), + value: value.clone(), + }; + let verdict = validate_environment_entries(std::slice::from_ref(&entry)); + // The documented value rule: bounded, and free of NUL. + let documented_accepts = + value.len() <= MAX_ENV_VALUE_BYTES && !value.as_bytes().contains(&0); + + assert_eq!( + verdict.is_ok(), + documented_accepts, + "the implementation and the documented rule disagree about a value of length {}", + value.len() + ); + + if documented_accepts { + accepted.push(value.clone()); + } else { + rejected.push(value.clone()); + } + } + + assert_eq!(accepted.len() + rejected.len(), candidates.len()); + for value in &accepted { + assert!(!rejected.contains(value)); + } + for value in &rejected { + assert!(!accepted.contains(value)); + } + assert!(!accepted.is_empty() && !rejected.is_empty()); +} + +#[test] +fn the_accepted_and_rejected_list_sets_partition_the_candidate_space() { + // The list bound and the duplicate-name rule are the two list-level rules. + let at_bound: Vec = (0..MAX_ENV_COUNT) + .map(|index| EnvironmentEntry { + name: format!("NAME_{index}"), + value: "v".to_owned(), + }) + .collect(); + assert!( + validate_environment_entries(&at_bound).is_ok(), + "a list exactly at the count bound must be accepted" + ); + + let over_bound: Vec = (0..=MAX_ENV_COUNT) + .map(|index| EnvironmentEntry { + name: format!("NAME_{index}"), + value: "v".to_owned(), + }) + .collect(); + assert!( + matches!( + validate_environment_entries(&over_bound), + Err(ValidationError::TooMany { + field: "environment", + max: MAX_ENV_COUNT + }) + ), + "a list one entry over the count bound must be refused by the count rule" + ); + + let duplicate = vec![ + EnvironmentEntry { + name: "DUPLICATE".to_owned(), + value: "first".to_owned(), + }, + EnvironmentEntry { + name: "DUPLICATE".to_owned(), + value: "second".to_owned(), + }, + ]; + assert!( + matches!( + validate_environment_entries(&duplicate), + Err(ValidationError::InvalidSyntax { + field: "duplicate environment name" + }) + ), + "two entries with the same name must be refused by the duplicate rule" + ); + + // The duplicate rule is a distinct rule from the per-entry rule: a name + // that is individually legal is still refused when it repeats, and the + // refusal names the duplicate rule rather than the syntax rule. + let distinct = vec![ + EnvironmentEntry { + name: "FIRST".to_owned(), + value: "first".to_owned(), + }, + EnvironmentEntry { + name: "SECOND".to_owned(), + value: "second".to_owned(), + }, + ]; + assert!(validate_environment_entries(&distinct).is_ok()); +} diff --git a/crates/eggwork-runner/src/lib.rs b/crates/eggwork-runner/src/lib.rs index a2f5d9c..cf31794 100644 --- a/crates/eggwork-runner/src/lib.rs +++ b/crates/eggwork-runner/src/lib.rs @@ -4,17 +4,28 @@ //! //! Embedding API: construct a validated [`RunnerRequest`] from an //! [`eggwork_core::ExecutionSpec`] with [`RunnerRequest::from_spec`], then run -//! it through [`LocalProcessRunner`]. Request fields remain private so callers -//! cannot bypass protocol bounds. Platform setup is supplied through +//! it through [`LocalProcessRunner`]. Request fields remain private, and every +//! public construction path is covered by the `eggwork_core` domain contract: +//! [`RunnerRequest::contract_error`] reports a violation without running +//! anything, and [`LocalProcessRunner::run`] refuses one before setup and +//! before any child exists. Platform setup is supplied through //! [`ExecutionSetup`]; neither this API nor its result types carry scheduler //! placement, priority, or project fairness policy. use eggwork_core::{ - CommandSpec, ExecutionFailure, ExecutionGeneration, ExecutionId, ExecutionResult, - ExecutionSpec, ExecutionState, MAX_CAPTURE_BYTES, MAX_ENV_COUNT, MAX_ENV_NAME_BYTES, - MAX_ENV_VALUE_BYTES, MAX_EVENT_CHUNK_BYTES, OverflowPolicy as CoreOverflowPolicy, RelativePath, - Requirement, StdinPolicy as CoreStdinPolicy, + CommandSpec, EnvironmentEntry, ExecutionFailure, ExecutionGeneration, ExecutionId, + ExecutionResult, ExecutionSpec, ExecutionState, MAX_CAPTURE_BYTES, MAX_EVENT_CHUNK_BYTES, + OutputPolicy, OverflowPolicy as CoreOverflowPolicy, RelativePath, Requirement, + ResourceRequirements, ValidationError, validate_argv, validate_environment_entries, + validate_timeout, }; +// The runner consumes the core domain type rather than keeping a local copy of +// it. The public path `eggwork_runner::StdinPolicy` is retained as a re-export +// so that embedders and the in-tree suites keep compiling against the path they +// already use; the type that path names is `eggwork_core::StdinPolicy`, and the +// runner's former local duplicate -- with its own `Debug` and its own copy of +// the stdin bound -- is gone. +pub use eggwork_core::StdinPolicy; #[cfg(target_os = "linux")] use serde::Serialize; #[cfg(target_os = "linux")] @@ -1104,8 +1115,12 @@ impl std::fmt::Debug for RunnerRequest { } impl RunnerRequest { - /// Create an embedding request with conservative defaults. [`run`](LocalProcessRunner::run) - /// validates every field before setup or child creation. + /// Create an embedding request with conservative defaults. + /// + /// The request is covered by the `eggwork_core` domain contract like every + /// other construction path: [`RunnerRequest::contract_error`] reports a + /// violation without running anything, and [`run`](LocalProcessRunner::run) + /// refuses one before setup and before any child creation. pub fn new(argv: Vec, root: impl Into) -> Self { Self { argv, @@ -1135,6 +1150,12 @@ impl RunnerRequest { self.cwd = cwd; } + /// Replace the request's environment. + /// + /// The entries are the caller's raw name/value pairs; the environment-entry + /// rules themselves are owned by `eggwork_core` and are applied by + /// [`RunnerRequest::contract_error`] and by + /// [`run`](LocalProcessRunner::run), not restated here. pub fn set_environment(&mut self, environment: Vec<(String, String)>) { self.environment = environment; } @@ -1190,8 +1211,7 @@ impl RunnerRequest { root: impl Into, provenance: ExecutionProvenance, ) -> Result { - spec.validate() - .map_err(|e| RunnerError::InvalidRequest(e.to_string()))?; + spec.validate().map_err(RunnerError::InvalidRequest)?; let CommandSpec { argv, cwd, @@ -1217,10 +1237,7 @@ impl RunnerRequest { root: root.into(), cwd, environment: environment.into_iter().map(|e| (e.name, e.value)).collect(), - stdin: match stdin { - CoreStdinPolicy::Null => StdinPolicy::Null, - CoreStdinPolicy::Bytes(bytes) => StdinPolicy::Bytes(bytes), - }, + stdin, timeout: Duration::from_millis(timeout_millis), capture_limit: output.capture_limit_bytes, event_chunk_bytes: output.event_chunk_bytes, @@ -1235,48 +1252,106 @@ impl RunnerRequest { }) } - fn validate(&self) -> Result { - if self.argv.is_empty() - || self.argv.len() > eggwork_core::MAX_ARG_COUNT - || self - .argv - .iter() - .any(|a| a.is_empty() || a.len() > eggwork_core::MAX_ARG_BYTES || a.contains('\0')) - { - return Err(RunnerError::InvalidRequest( - "argv is empty or contains an empty/NUL entry".into(), - )); - } - if self.environment.len() > MAX_ENV_COUNT - || self.environment.iter().any(|(k, v)| { - k.is_empty() - || k.len() > MAX_ENV_NAME_BYTES - || v.len() > MAX_ENV_VALUE_BYTES - || k.contains('\0') - || k.contains('=') - || v.contains('\0') + /// The first violation of the request contract, if this request has one. + /// + /// The request contract is the `eggwork_core` domain contract -- the argv, + /// environment-entry, output-policy, timeout, stdin and resource rules -- + /// plus the runner's own stricter argv-entry rule. It is checked here + /// without touching the filesystem, so an embedder can ask whether what it + /// built is acceptable before it runs anything. + /// + /// [`LocalProcessRunner::run`] refuses a request that has a violation, + /// before setup and before any child exists, with the same error. The + /// root-directory and working-directory rules are deliberately not part of + /// this answer: they are the runner's own, they need filesystem access, and + /// they are enforced at the same point. + pub fn contract_error(&self) -> Option { + self.contract_violation() + } + + /// The request's environment as core environment entries. + /// + /// The runner stores raw name/value pairs because that is what the child's + /// environment is built from, but the *rules* that govern an entry are + /// owned by `eggwork_core`. The entries are handed over as plain values so + /// that `eggwork_core` re-validates them rather than trusting them. + fn environment_entries(&self) -> Vec { + self.environment + .iter() + .map(|(name, value)| EnvironmentEntry { + name: name.clone(), + value: value.clone(), }) - { - return Err(RunnerError::InvalidRequest( - "environment violates bounds or syntax".into(), - )); - } - if self.capture_limit > MAX_CAPTURE_BYTES - || self.event_chunk_bytes == 0 - || self.event_chunk_bytes > MAX_EVENT_CHUNK_BYTES - { - return Err(RunnerError::InvalidRequest( - "output limits are outside supported bounds".into(), - )); + .collect() + } + + /// The request's output policy as the core output policy. + fn output_policy(&self) -> OutputPolicy { + OutputPolicy { + capture_limit_bytes: self.capture_limit, + event_chunk_bytes: self.event_chunk_bytes, + overflow: self.overflow.clone(), } - if self.timeout.is_zero() || self.timeout > eggwork_core::MAX_TIMEOUT { - return Err(RunnerError::InvalidRequest( - "timeout must be positive".into(), - )); + } + + /// The request's resource requirements as the core resource requirements. + fn resource_requirements(&self) -> ResourceRequirements { + ResourceRequirements { + memory_bytes: self.resources.memory_bytes, + cpu_millis: self.resources.cpu_millis, + pids: self.resources.pids, } - self.stdin - .validate() - .map_err(|e| RunnerError::InvalidRequest(e.to_string()))?; + } + + /// The first contract violation in the request, in the canonical order. + /// + /// The order is the one `eggwork_core::CommandSpec::validate` uses -- argv, + /// environment, timeout, stdin, output, resources -- with the runner's own + /// argv-entry rule immediately after the argv bounds, so that a request + /// built through the builder path and the same request built through + /// `from_spec` report the *same* rule for the same input. + /// + /// Every rule below is owned by `eggwork_core` except the argv-entry rule, + /// which is the runner's own and is stricter than the core contract. + fn contract_violation(&self) -> Option { + validate_argv(&self.argv) + .err() + .or_else(|| self.argv_entry_violation()) + .or_else(|| validate_environment_entries(&self.environment_entries()).err()) + .or_else(|| validate_timeout(self.timeout).err()) + .or_else(|| self.stdin.validate().err()) + .or_else(|| self.output_policy().validate().err()) + .or_else(|| self.resource_requirements().validate().err()) + } + + /// The runner's own argv-entry rule. + /// + /// `eggwork_core` permits an empty argv entry; the runner does not. An + /// empty argument is not a protocol problem -- it is a child-process + /// construction hazard: the runner hands the argv to the operating system + /// as an argument vector, where an empty element is either a silent no-op + /// argument or an ambiguity the caller cannot see. The runner is therefore + /// deliberately *stricter* than its owner here, and this is the only rule + /// it adds on top of the core contract. + fn argv_entry_violation(&self) -> Option { + self.argv + .iter() + .any(|argument| argument.is_empty()) + .then_some(ValidationError::InvalidSyntax { + field: "argv entry", + }) + } + + fn validate(&self) -> Result { + // Every core-owned rule is consumed from `eggwork_core` rather than + // restated here, so the runner cannot drift from the contract it + // claims to enforce. + if let Some(violation) = self.contract_violation() { + return Err(RunnerError::InvalidRequest(violation)); + } + // The runner's own contract rules: the root-directory and + // working-directory resolution. `eggwork_core` does not own them, + // because they are about a filesystem the domain layer never sees. let root = self .root .canonicalize() @@ -1304,32 +1379,6 @@ impl RunnerRequest { } } -#[derive(Clone, PartialEq, Eq)] -pub enum StdinPolicy { - Null, - Bytes(Vec), -} -impl std::fmt::Debug for StdinPolicy { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Null => f.write_str("Null"), - Self::Bytes(bytes) => f - .debug_struct("Bytes") - .field("length", &bytes.len()) - .field("value", &"[REDACTED]") - .finish(), - } - } -} -impl StdinPolicy { - fn validate(&self) -> Result<(), RunnerError> { - if matches!(self, Self::Bytes(v) if v.len() > eggwork_core::MAX_STDIN_BYTES) { - return Err(RunnerError::InvalidRequest("stdin exceeds limit".into())); - } - Ok(()) - } -} - #[derive(Debug, Clone, PartialEq, Eq)] pub enum TerminationReason { Exited, @@ -1475,8 +1524,14 @@ fn resource_result( #[derive(Debug, Error)] pub enum RunnerError { + /// The request violates the `eggwork_core` domain contract. + /// + /// The payload is the core [`ValidationError`], so the failure stays + /// attributable to the rule that produced it: an environment name with + /// invalid syntax and a duplicate environment name are two different + /// rules, and a caller can tell them apart without parsing a message. #[error("invalid execution request: {0}")] - InvalidRequest(String), + InvalidRequest(ValidationError), #[error("execution root is invalid: {0}")] InvalidRoot(String), #[error("working directory is invalid: {0}")] diff --git a/crates/eggwork-runner/tests/request_validation_parity.rs b/crates/eggwork-runner/tests/request_validation_parity.rs new file mode 100644 index 0000000..8653fb7 --- /dev/null +++ b/crates/eggwork-runner/tests/request_validation_parity.rs @@ -0,0 +1,680 @@ +//! The runner's request validation is a projection of the `eggwork_core` +//! domain contract, not a second copy of it. +//! +//! The defect this suite closes is a drift between two copies of one rule set. +//! The runner used to re-spell the environment-entry rules in a private helper, +//! and its copy was *weaker* than core's: it accepted a name containing `-` or +//! `.`, accepted a name beginning with a digit, and did not detect duplicate +//! names at all. The runner's public constructor and its public environment +//! setter reached that weaker gate without passing through core validation at +//! all, while the crate documentation claimed that callers could not bypass +//! protocol bounds. +//! +//! Every assertion here goes through the runner's **public** API. A test that +//! only exercised `eggwork_core` would have passed before the corrective and +//! would have proved nothing about the runner. +//! +//! The properties proved are: +//! +//! 1. Every public construction path reaches the same verdict as +//! `from_spec`, for the same input, with the same typed error. +//! 2. The runner rejects every environment-name form core rejects. +//! 3. A duplicate environment name is refused by the duplicate-name rule, and +//! the refusal is attributable to that rule specifically. +//! 4. The runner stays *stricter* than core on exactly one rule -- an empty +//! argv entry -- and that rule is explicit. +//! 5. The stdin and output bounds are core's bounds. +//! 6. A request that violates the contract never reaches a child. + +use eggwork_core::{ + CommandSpec, EnvironmentEntry, ExecutionSpec, IsolationRequirement, MAX_ARG_BYTES, + MAX_ARG_COUNT, MAX_CAPTURE_BYTES, MAX_ENV_COUNT, MAX_ENV_NAME_BYTES, MAX_ENV_VALUE_BYTES, + MAX_EVENT_CHUNK_BYTES, MAX_STDIN_BYTES, MAX_TIMEOUT, NetworkRequirement, OutputPolicy, + OverflowPolicy, Requirement, ResourceRequirements, StdinPolicy, ValidationError, +}; +use eggwork_runner::{ + ExecutionProvenance, LocalProcessRunner, NoExecutionSetup, ResourceSetupRequest, RunnerError, + RunnerRequest, +}; +use std::path::Path; +use tokio::sync::mpsc; +use tokio_util::sync::CancellationToken; + +/// A valid command, used as the base for every case. +fn command() -> CommandSpec { + CommandSpec { + argv: vec!["/bin/echo".to_owned(), "hello".to_owned()], + cwd: None, + environment: Vec::new(), + stdin: StdinPolicy::Null, + timeout_millis: 5_000, + output: OutputPolicy::default(), + declared_outputs: Vec::new(), + resources: ResourceRequirements { + memory_bytes: Requirement::NotRequested, + cpu_millis: Requirement::NotRequested, + pids: Requirement::NotRequested, + }, + isolation: IsolationRequirement::None, + network: NetworkRequirement::Unrestricted, + } +} + +fn spec(command: CommandSpec) -> ExecutionSpec { + ExecutionSpec { + schema_version: 1, + command, + metadata: Vec::new(), + } +} + +/// Build the same request through the runner's *builder* path. +/// +/// This is the path the corrective is about: `RunnerRequest::new` plus the +/// public setters, with no `eggwork_core` validation in between. It is the +/// only way an embedder can build a request without a protocol spec, so it is +/// the path that has to reach the same verdict. +fn build_through_the_builder(command: &CommandSpec, root: &Path) -> RunnerRequest { + let mut request = RunnerRequest::new(command.argv.clone(), root); + request.set_argv(command.argv.clone()); + request.set_working_directory(command.cwd.clone()); + request.set_environment( + command + .environment + .iter() + .map(|entry| (entry.name.clone(), entry.value.clone())) + .collect(), + ); + request.set_stdin_policy(command.stdin.clone()); + request.set_timeout(std::time::Duration::from_millis(command.timeout_millis)); + request.set_output_policy( + command.output.capture_limit_bytes, + command.output.event_chunk_bytes, + command.output.overflow.clone(), + ); + request.set_resource_setup_request(ResourceSetupRequest { + memory_bytes: command.resources.memory_bytes, + cpu_millis: command.resources.cpu_millis, + pids: command.resources.pids, + }); + request +} + +/// Run a request and assert that it is refused before any child exists. +/// +/// The marker file is the proof that the refusal happened *before* the spawn: +/// the target's only job would be to leave the marker behind. +async fn assert_refused_before_spawn(request: RunnerRequest, root: &Path) -> RunnerError { + let marker = root.join("target-ran"); + let argv = vec![ + "/bin/sh".to_owned(), + "-c".to_owned(), + format!("touch {}", marker.display()), + ]; + assert_refused_before_spawn_with_argv(request, root, argv).await +} + +/// The same, for a request whose argv is itself under test. +async fn assert_refused_before_spawn_with_argv( + request: RunnerRequest, + root: &Path, + argv: Vec, +) -> RunnerError { + let marker = root.join("target-ran"); + let mut request = request; + request.set_argv(argv); + let (tx, _rx) = mpsc::channel(8); + let error = LocalProcessRunner::new(NoExecutionSetup) + .run(request, CancellationToken::new(), tx) + .await + .expect_err("the request must be refused"); + assert!( + !marker.exists(), + "a refused request must not reach a child: {error:?}" + ); + error +} + +fn environment(name: &str, value: &str) -> EnvironmentEntry { + EnvironmentEntry { + name: name.to_owned(), + value: value.to_owned(), + } +} + +/// The names core refuses, and the reason each one is refused. +fn refused_environment_names() -> Vec<(&'static str, String)> { + vec![ + ("a dash", "WITH-DASH".to_owned()), + ("a dot", "WITH.DOT".to_owned()), + ("a space", "WITH SPACE".to_owned()), + ("an equals sign", "WITH=EQUALS".to_owned()), + ("a leading digit", "1LEADING".to_owned()), + ("a leading zero", "0LEADING".to_owned()), + ("an empty name", String::new()), + ("a NUL byte", "WITH\0NUL".to_owned()), + ( + "a name one byte over the bound", + "A".repeat(MAX_ENV_NAME_BYTES + 1), + ), + ] +} + +/// The runner rejects every environment-name form core rejects. +/// +/// This is the rule the runner's private copy used to get wrong, so the +/// assertion has to be made through the runner's public API and has to be +/// made about the *typed* error, not about a message. +#[tokio::test] +async fn the_runner_rejects_every_environment_name_form_core_rejects() { + let root = tempfile::tempdir().expect("temp dir"); + + for (label, name) in refused_environment_names() { + // The builder path: the one an embedder uses. + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.set_environment(vec![(name.clone(), "value".to_owned())]); + assert!( + matches!( + request.contract_error(), + Some(ValidationError::InvalidSyntax { + field: "environment name" + }) + ), + "{label}: the builder path must refuse {name:?} by the name rule; got {:?}", + request.contract_error() + ); + + let error = assert_refused_before_spawn(request, root.path()).await; + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::InvalidSyntax { + field: "environment name" + }) + ), + "{label}: the run must be refused by the name rule; got {error:?}" + ); + + // The protocol path: the same name, refused by core. + let mut offending = command(); + offending.environment = vec![environment(&name, "value")]; + let error = RunnerRequest::from_spec( + &spec(offending), + root.path(), + ExecutionProvenance::default(), + ) + .expect_err("core must refuse the same name"); + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::InvalidSyntax { + field: "environment name" + }) + ), + "{label}: core must refuse {name:?} by the name rule; got {error:?}" + ); + } +} + +/// A name the contract accepts reaches the child. +#[tokio::test] +async fn a_legal_environment_name_is_accepted_by_the_runner() { + let root = tempfile::tempdir().expect("temp dir"); + for name in ["NAME", "lower_case", "Mixed_Case_9", "_LEADING_UNDERSCORE"] { + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.set_environment(vec![(name.to_owned(), "value".to_owned())]); + assert!( + request.contract_error().is_none(), + "{name:?} is legal and must be accepted; got {:?}", + request.contract_error() + ); + } +} + +/// A duplicate environment name is refused by the duplicate-name rule. +/// +/// The attribution matters: a duplicate name is a *different* rule from a name +/// with invalid syntax, and the two must not collapse into one answer. Core +/// distinguishes them with distinct `field` labels, and the runner preserves +/// that distinction rather than flattening it into one message. +#[tokio::test] +async fn a_duplicate_environment_name_is_refused_by_the_duplicate_rule() { + let root = tempfile::tempdir().expect("temp dir"); + + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.set_environment(vec![ + ("DUPLICATE".to_owned(), "first".to_owned()), + ("DUPLICATE".to_owned(), "second".to_owned()), + ]); + assert!( + matches!( + request.contract_error(), + Some(ValidationError::InvalidSyntax { + field: "duplicate environment name" + }) + ), + "a repeated name must be refused by the duplicate rule; got {:?}", + request.contract_error() + ); + + let error = assert_refused_before_spawn(request, root.path()).await; + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::InvalidSyntax { + field: "duplicate environment name" + }) + ), + "the refusal must be attributable to the duplicate-name rule; got {error:?}" + ); + + // The same duplicate, through the protocol path, is refused by the same + // rule -- so the runner is not applying a rule of its own here. + let mut offending = command(); + offending.environment = vec![ + environment("DUPLICATE", "first"), + environment("DUPLICATE", "second"), + ]; + let error = RunnerRequest::from_spec( + &spec(offending), + root.path(), + ExecutionProvenance::default(), + ) + .expect_err("core must refuse the duplicate"); + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::InvalidSyntax { + field: "duplicate environment name" + }) + ), + "core must refuse the duplicate by the duplicate rule; got {error:?}" + ); +} + +/// The runner stays stricter than core on exactly one rule: an empty argv +/// entry. +/// +/// `eggwork_core` permits an empty argv entry. The runner does not, because an +/// empty argument is a child-process construction hazard rather than a +/// protocol concern. The rule is the runner's own, it is documented in the +/// code, and it is the *only* place the runner may exceed its owner. +#[tokio::test] +async fn the_runner_refuses_an_empty_argv_entry_which_core_permits() { + let root = tempfile::tempdir().expect("temp dir"); + + let mut offending = command(); + offending.argv = vec!["/bin/echo".to_owned(), String::new()]; + + // Core permits it. + let accepted = RunnerRequest::from_spec( + &spec(offending.clone()), + root.path(), + ExecutionProvenance::default(), + ); + assert!( + accepted.is_ok(), + "core permits an empty argv entry; the runner's rule is stricter than core" + ); + + // The runner refuses it, and says which rule refused it. + let request = build_through_the_builder(&offending, root.path()); + assert!( + matches!( + request.contract_error(), + Some(ValidationError::InvalidSyntax { + field: "argv entry" + }) + ), + "the runner must refuse an empty argv entry by its own rule; got {:?}", + request.contract_error() + ); + + let error = assert_refused_before_spawn_with_argv( + request, + root.path(), + vec![ + "/bin/sh".to_owned(), + "-c".to_owned(), + format!("touch {}", root.path().join("target-ran").display()), + String::new(), + ], + ) + .await; + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::InvalidSyntax { + field: "argv entry" + }) + ), + "the refusal must name the argv-entry rule; got {error:?}" + ); +} + +/// Every public construction path reaches the same verdict as `from_spec`. +/// +/// This is the parity property the milestone is named for. For the same +/// input, the protocol path and the builder path must agree on the verdict +/// *and* on the typed error, so a caller cannot be told one thing by the +/// protocol and another by the builder. +#[tokio::test] +async fn every_public_construction_path_reaches_the_same_contract_verdict() { + let root = tempfile::tempdir().expect("temp dir"); + + let mut cases: Vec<(&'static str, CommandSpec)> = Vec::new(); + + cases.push(("a valid command", command())); + + let mut empty_argv = command(); + empty_argv.argv = Vec::new(); + cases.push(("an empty argv", empty_argv)); + + let mut long_argv_entry = command(); + long_argv_entry.argv = vec!["A".repeat(MAX_ARG_BYTES + 1)]; + cases.push(("an oversized argv entry", long_argv_entry)); + + let mut many_args = command(); + many_args.argv = (0..=MAX_ARG_COUNT) + .map(|index| format!("arg{index}")) + .collect(); + cases.push(("too many argv entries", many_args)); + + let mut bad_env_name = command(); + bad_env_name.environment = vec![environment("WITH-DASH", "value")]; + cases.push(("an environment name with a dash", bad_env_name)); + + let mut duplicate_env = command(); + duplicate_env.environment = vec![ + environment("DUPLICATE", "first"), + environment("DUPLICATE", "second"), + ]; + cases.push(("a duplicate environment name", duplicate_env)); + + let mut long_env_value = command(); + long_env_value.environment = vec![EnvironmentEntry { + name: "NAME".to_owned(), + value: "v".repeat(MAX_ENV_VALUE_BYTES + 1), + }]; + cases.push(("an oversized environment value", long_env_value)); + + let mut nul_env_value = command(); + nul_env_value.environment = vec![environment("NAME", "value\0with-nul")]; + cases.push(("a NUL in an environment value", nul_env_value)); + + let mut too_many_env = command(); + too_many_env.environment = (0..=MAX_ENV_COUNT) + .map(|index| environment(&format!("NAME_{index}"), "value")) + .collect(); + cases.push(("too many environment entries", too_many_env)); + + let mut zero_timeout = command(); + zero_timeout.timeout_millis = 0; + cases.push(("a zero timeout", zero_timeout)); + + let mut long_timeout = command(); + long_timeout.timeout_millis = MAX_TIMEOUT.as_millis() as u64 + 1; + cases.push(("an over-long timeout", long_timeout)); + + let mut big_stdin = command(); + big_stdin.stdin = StdinPolicy::Bytes(vec![0; MAX_STDIN_BYTES + 1]); + cases.push(("oversized stdin", big_stdin)); + + let mut big_capture = command(); + big_capture.output.capture_limit_bytes = MAX_CAPTURE_BYTES + 1; + cases.push(("an over-large capture limit", big_capture)); + + let mut zero_chunk = command(); + zero_chunk.output.event_chunk_bytes = 0; + cases.push(("a zero event chunk", zero_chunk)); + + let mut big_chunk = command(); + big_chunk.output.event_chunk_bytes = MAX_EVENT_CHUNK_BYTES + 1; + cases.push(("an over-large event chunk", big_chunk)); + + for (label, offending) in cases { + let via_protocol = RunnerRequest::from_spec( + &spec(offending.clone()), + root.path(), + ExecutionProvenance::default(), + ); + let via_builder = build_through_the_builder(&offending, root.path()); + let builder_verdict = via_builder.contract_error(); + + match via_protocol { + Ok(_) => assert!( + builder_verdict.is_none(), + "{label}: the protocol path accepts, so the builder path must accept too; \ + the builder reported {builder_verdict:?}" + ), + Err(RunnerError::InvalidRequest(expected)) => assert_eq!( + builder_verdict.as_ref(), + Some(&expected), + "{label}: the two construction paths must report the same typed error" + ), + Err(other) => panic!("{label}: unexpected error {other:?}"), + } + } +} + +/// The mutable resource door is a construction path too, and it is covered. +/// +/// `resource_setup_request_mut` hands out a mutable reference, so it cannot +/// validate on the way in. The enforcement point has to catch what it let +/// through, which is exactly the case that would otherwise be a bypass. +#[tokio::test] +async fn the_mutable_resource_door_is_covered_by_the_contract() { + let root = tempfile::tempdir().expect("temp dir"); + + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.resource_setup_request_mut().memory_bytes = Requirement::Required(u64::MAX); + assert!( + matches!( + request.contract_error(), + Some(ValidationError::OutOfRange { + field: "resource requirements" + }) + ), + "an out-of-range resource requirement must be caught; got {:?}", + request.contract_error() + ); + + let error = assert_refused_before_spawn(request, root.path()).await; + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::OutOfRange { + field: "resource requirements" + }) + ), + "the run must be refused by the resource rule; got {error:?}" + ); +} + +/// The stdin bound is core's bound, and the runner still forwards the bytes. +/// +/// The runner's local `StdinPolicy` duplicate is gone: the public path +/// `eggwork_runner::StdinPolicy` now names `eggwork_core::StdinPolicy`. The +/// assignment below is a compile-time proof of that, so the test cannot pass +/// against a runner that kept a second type. +#[tokio::test] +async fn the_runner_forwards_stdin_bytes_and_enforces_the_core_stdin_bound() { + let core_policy: StdinPolicy = eggwork_runner::StdinPolicy::Null; + assert!(matches!(core_policy, StdinPolicy::Null)); + + let root = tempfile::tempdir().expect("temp dir"); + + // The bound is core's bound, enforced through the runner's public API. + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.set_stdin_policy(eggwork_runner::StdinPolicy::Bytes(vec![ + 0; + MAX_STDIN_BYTES + 1 + ])); + assert!( + matches!( + request.contract_error(), + Some(ValidationError::TooLong { + field: "stdin", + max: MAX_STDIN_BYTES + }) + ), + "stdin over the core bound must be refused; got {:?}", + request.contract_error() + ); + let error = assert_refused_before_spawn(request, root.path()).await; + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::TooLong { + field: "stdin", + max: MAX_STDIN_BYTES + }) + ), + "the refusal must name the stdin bound; got {error:?}" + ); + + // A stdin at the bound is accepted. + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.set_stdin_policy(eggwork_runner::StdinPolicy::Bytes(vec![0; MAX_STDIN_BYTES])); + assert!( + request.contract_error().is_none(), + "stdin exactly at the core bound must be accepted; got {:?}", + request.contract_error() + ); +} + +/// The bytes still reach the child. +#[cfg(unix)] +#[tokio::test] +async fn stdin_bytes_are_forwarded_to_the_child() { + let root = tempfile::tempdir().expect("temp dir"); + let mut request = RunnerRequest::new(vec!["/bin/cat".to_owned()], root.path()); + request.set_stdin_policy(eggwork_runner::StdinPolicy::Bytes( + b"forwarded-stdin\n".to_vec(), + )); + let (tx, mut rx) = mpsc::channel(8); + let result = LocalProcessRunner::new(NoExecutionSetup) + .run(request, CancellationToken::new(), tx) + .await + .expect("the target runs"); + let mut captured = Vec::new(); + while let Ok(chunk) = rx.try_recv() { + if let eggwork_runner::OutputChunk::Stdout(bytes) = chunk { + captured.extend_from_slice(&bytes); + } + } + assert_eq!(captured, b"forwarded-stdin\n"); + assert_eq!(result.exit_code, Some(0)); +} + +/// The output bounds are core's bounds. +#[tokio::test] +async fn the_runner_enforces_the_core_output_bounds() { + let root = tempfile::tempdir().expect("temp dir"); + + let cases: Vec<(&'static str, usize, usize)> = vec![ + ("an over-large capture limit", MAX_CAPTURE_BYTES + 1, 4096), + ("a zero event chunk", 1024, 0), + ("an over-large event chunk", 1024, MAX_EVENT_CHUNK_BYTES + 1), + ]; + + for (label, capture_limit, event_chunk_bytes) in cases { + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.set_output_policy(capture_limit, event_chunk_bytes, OverflowPolicy::Truncate); + assert!( + matches!( + request.contract_error(), + Some(ValidationError::OutOfRange { + field: "output policy" + }) + ), + "{label}: must be refused by the core output rule; got {:?}", + request.contract_error() + ); + let error = assert_refused_before_spawn(request, root.path()).await; + assert!( + matches!( + error, + RunnerError::InvalidRequest(ValidationError::OutOfRange { + field: "output policy" + }) + ), + "{label}: the refusal must name the output policy; got {error:?}" + ); + } + + // A policy exactly at the bounds is accepted. + let mut request = RunnerRequest::new(command().argv.clone(), root.path()); + request.set_output_policy( + MAX_CAPTURE_BYTES, + MAX_EVENT_CHUNK_BYTES, + OverflowPolicy::Terminate, + ); + assert!( + request.contract_error().is_none(), + "a policy at the core bounds must be accepted; got {:?}", + request.contract_error() + ); +} + +/// The runner's public request surface is pinned. +/// +/// The builder path is the runner's embedding surface, and a new public entry +/// point on `RunnerRequest` is a new way to produce a request. This test +/// fails when one is added, so the new entry point has to be reviewed against +/// the core contract rather than slipped in. +#[test] +fn the_runner_request_public_surface_is_pinned() { + let source = include_str!("../src/lib.rs"); + let start = source + .find("impl RunnerRequest {") + .expect("the RunnerRequest impl block exists"); + let body = &source[start..]; + let mut depth = 0usize; + let mut end = body.len(); + for (index, character) in body.char_indices() { + match character { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + end = index; + break; + } + } + _ => {} + } + } + let mut found: Vec<&str> = body[..end] + .lines() + .filter_map(|line| line.trim().strip_prefix("pub fn ")) + .filter_map(|rest| rest.split('(').next()) + .map(|name| name.trim()) + .collect(); + found.sort_unstable(); + + let mut expected = vec![ + "new", + "from_spec", + "contract_error", + "set_argv", + "set_working_directory", + "set_environment", + "set_stdin_policy", + "set_timeout", + "set_output_policy", + "set_provenance", + "set_sandbox_request", + "set_resource_setup_request", + "resource_setup_request_mut", + "sandbox_request", + "resource_setup_request", + ]; + expected.sort_unstable(); + + assert_eq!( + found, expected, + "the public surface of RunnerRequest changed: a new public entry point is a new \ + way to produce a request and has to be reviewed against the core contract" + ); +} diff --git a/plans/closure/foundation-execution-core/005-status.md b/plans/closure/foundation-execution-core/005-status.md new file mode 100644 index 0000000..bca3f21 --- /dev/null +++ b/plans/closure/foundation-execution-core/005-status.md @@ -0,0 +1,236 @@ +# Foundation M005 Closure — Runner Request Validation Parity Corrective + +Status: active + +Source plan: `plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md` + +Corrective addendum: `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` + +Roadmap: `plans/subsystems/foundation-execution-core-roadmap.md` + +## Reviewed baseline + +- Reviewed head before implementation: `af5a21709573e20f26eca77df83bd5560c46e936` ("docs(plans): accept ADR-0007 — implement resource-scoped grants"). +- Implementation commits: **none yet**. The implementation is in the working tree; the coordinator commits. +- Workspace version at the reviewed head: `0.1.5`. + +## Executive finding + +The runner no longer carries a second copy of the domain validation rules. Before this milestone the runner re-spelled the `eggwork-core` rules in a private helper, and the two copies disagreed: the runner's copy accepted environment names containing `-` or `.`, accepted a name beginning with a digit, and did not detect duplicate environment names at all — while `eggwork-core` rejected all three. The runner's copy was the one gating the actual `Command::env()` call on the run path. Worse, `RunnerRequest::new` and `RunnerRequest::set_environment` reached that weaker gate without passing through core validation at all, which contradicted the runner crate's own documented claim that "Request fields remain private so callers cannot bypass protocol bounds". + +After this milestone: + +- The argv, environment-entry, timeout, stdin, output-policy and resource rules each have exactly one owner, in `eggwork-core`, and the runner **consumes** them rather than re-deriving them. +- The runner is never weaker than core on any shared rule, and is deliberately stricter on exactly one rule — an empty argv entry — which is documented in the source with its reason and covered by a test. +- Every public construction path converges on the same enforcement point. `RunnerRequest::contract_error()` reports the first violation in a request without running anything, and `RunnerRequest::validate` refuses the request with the same typed error, before setup and before any child exists. +- The runner's local `StdinPolicy` duplicate — the enum, its `Debug` impl, its copy of the stdin bound, and the hand-written conversion in `from_spec` — is gone. +- The failure keeps its attribution: `RunnerError::InvalidRequest` now carries the typed `eggwork_core::ValidationError` instead of a rendered string, so "environment name with invalid syntax" and "duplicate environment name" are two distinguishable outcomes rather than one message. + +**The public-API disposition is (b), not (a).** The plan preferred removing `RunnerRequest::new` and `RunnerRequest::set_environment`, and preferred that option "if the repository has no in-tree caller". The in-tree caller set is **not** empty — five test files across two crates — and two of them live in `crates/eggwork-sandbox-helper/tests/`, which is outside this milestone's file ownership and outside the plan's stated scope ("the `eggwork-sandbox-helper` crate … does not construct runner requests"). That premise is true of the helper's *production* crate, which has no workspace-crate dependency, but **not** of its integration tests, which take `eggwork-runner` as a dev-dependency and drive the runner's public API. Removing the constructor would therefore have broken the build rather than hardened it. The builder path is kept and covered instead. + +## Requirement-to-evidence matrix + +| Requirement | Implementation / evidence | +|---|---| +| §5.1 — the environment-entry rules have one owner in core, in a form the runner can consume | `eggwork_core::validate_environment_entries(&[EnvironmentEntry])` is public and owns the list-count bound, the per-entry name/value rules and the duplicate-name rule. `eggwork_core::CommandSpec::validate` calls it, so there is one implementation, not two. `EnvironmentEntry::new` was already public and is consumed unchanged. The runner calls the same function (`crates/eggwork-runner/src/lib.rs`, `RunnerRequest::contract_violation`). | +| §5.2 — the runner consumes the core rules rather than restating them; the empty-argv rule is kept, documented and tested | The runner's private environment check, its argv bounds check, its output-bounds check, its timeout check and its stdin check are all deleted. The runner's own argv rule survives as `RunnerRequest::argv_entry_violation`, with the reason (an empty argument is a child-process construction hazard, not a protocol concern) in the source comment, and is pinned by `the_runner_refuses_an_empty_argv_entry_which_core_permits`. | +| §5.3 — the local `StdinPolicy`, its `Debug` impl, its `validate` and the hand-written conversion are removed | The enum, the `Debug` impl, `StdinPolicy::validate` and the `match stdin { CoreStdinPolicy::… }` conversion in `from_spec` are deleted. The runner now holds `eggwork_core::StdinPolicy` directly. The public path `eggwork_runner::StdinPolicy` survives as `pub use eggwork_core::StdinPolicy;` (see "Public-API compatibility" below). | +| §5.4 — the core output-policy bounds are consumed | The runner's `capture_limit`/`event_chunk_bytes` check is deleted; the runner builds the core `OutputPolicy` (`RunnerRequest::output_policy`) and calls core's `OutputPolicy::validate`. The runner's default `capture_limit`/`event_chunk_bytes` are still core's `MAX_CAPTURE_BYTES`/`MAX_EVENT_CHUNK_BYTES`. | +| §5.5 — the public construction path is guarded | Option (b): the builder path is kept and covered. `RunnerRequest::contract_error()` reports the first violation without running; `RunnerRequest::validate` refuses the same request with the same typed error before setup and before any child exists. The caller enumeration that forced this choice is in "Public-API compatibility" below. | +| §5.6 — error fidelity is preserved | `RunnerError::InvalidRequest` now carries `eggwork_core::ValidationError` instead of `String`. Each rule keeps its own variant and `field` label, so a too-long environment name and a duplicate environment name are distinguishable *by type*, not by parsing a message. | +| §5.7 — the runner's own contract rules survive unchanged | The root canonicalisation, the "root is a directory" check and the "cwd escapes root" check are byte-for-byte unchanged in `RunnerRequest::validate`, and they remain runner-owned: core never sees a filesystem. | +| §4.1 — a request-validation rule has exactly one owner in core | `validate_argv`, `validate_environment_entries` and `validate_timeout` are public in core and are called by both `CommandSpec::validate` and the runner. `StdinPolicy::validate`, `OutputPolicy::validate` and `ResourceRequirements::validate` were already public and are now consumed by the runner rather than restated. | +| §4.2 — the runner is never weaker than core on a shared rule | `every_public_construction_path_reaches_the_same_contract_verdict` asserts, for fifteen single-violation inputs, that `from_spec` rejecting implies the builder path reports the *same typed error*. | +| §4.3 — stricter runner-level rules are documented and tested | Exactly one such rule exists (empty argv entry); documented in `RunnerRequest::argv_entry_violation` and in `architecture/runner-execution.md`; tested by `the_runner_refuses_an_empty_argv_entry_which_core_permits`, which also asserts that core *permits* the same input. | +| §4.4 — no public runner API can produce a request that violates the core contract | Every public entry point is covered by `RunnerRequest::contract_violation`, which the enforcement point uses. `the_runner_request_public_surface_is_pinned` fails if a new public entry point is added to `RunnerRequest`. `the_mutable_resource_door_is_covered_by_the_contract` covers the one door (`resource_setup_request_mut`) that cannot validate on the way in. | +| §4.5 — the argv is an argument vector, not a shell string | Unchanged; no shell is involved and the runner was already stricter than core on the empty-entry case. | +| §4.6 — the runner's bounds are core's bounds | No numeric bound was changed. The runner now takes every bound from core's constants and core's `validate` functions rather than restating them. | +| §4.7 — core has no dependency edges | `crates/eggwork-core/Cargo.toml` was not touched. | +| §4.8 — the runner owns process creation | No process-creation call was added or removed. `scripts/check_execution_ownership.py` still reports two runner-owned and one helper-owned spawn site. | +| §6 — no wire change, no stored-format change, no serde change, no bound change | No type's `Serialize`/`Deserialize` representation was touched. `CommandSpec`, `ExecutionSpec` and every wire type are unchanged. `RunnerError`'s payload type changed (see "Public-API compatibility"), but `RunnerError` is not a wire type and is not serialized. | +| §6 — validation still happens before any child exists, on the same path, at the same point | `LocalProcessRunner::run` still calls `request.validate()?` at the top, unchanged in position. The refusal is now typed. `assert_refused_before_spawn` proves no child was created, using a marker file the target would have written. | +| §6 — `CancelledBeforeSpawn` still takes precedence over validation | Unchanged and verified by inspection at `crates/eggwork-runner/src/lib.rs`: `run` checks `cancellation.is_cancelled()` and returns `CancelledBeforeSpawn` before it reaches `request.validate()`. The existing test `cancellation_before_spawn_and_spawn_failure_are_typed` still passes. | +| §6 — timeout, cancellation, nonzero exit, output-limit termination and cleanup failure remain distinguishable | Untouched: `TerminationReason` still carries `Exited`/`TimedOut`/`Cancelled`/`OutputLimit`, and `RunnerError::Io`/`Wait` are unchanged. `RunnerError::InvalidRequest` stays in the "refused before any side effect" tier. | +| §7 — the compatibility surface is enumerated and the disposition is recorded | See "Public-API compatibility" below. | +| §8.1 — construction-path parity | `every_public_construction_path_reaches_the_same_contract_verdict` (15 inputs × 2 paths). `the_runner_request_public_surface_is_pinned` additionally fails if a new public construction path is added. | +| §8.2 — environment-name syntax, through the runner's public API | `the_runner_rejects_every_environment_name_form_core_rejects` covers nine refused name forms (dash, dot, space, `=`, leading digit, leading zero, empty, NUL, one byte over `MAX_ENV_NAME_BYTES`) through `RunnerRequest::new` + `set_environment` *and* through `from_spec`, asserting the typed `InvalidSyntax { field: "environment name" }` and that no child was created. `a_legal_environment_name_is_accepted_by_the_runner` covers the accepted side. | +| §8.3 — duplicate environment names, attributable to the duplicate rule | `a_duplicate_environment_name_is_refused_by_the_duplicate_rule` asserts `InvalidSyntax { field: "duplicate environment name" }` specifically — not the generic name rule — through the builder path, through `run`, and through `from_spec`. | +| §8.4 — the accepted and rejected sets partition the input space | `crates/eggwork-core/tests/environment_rule_partition.rs`: three tests over the name set, the value set and the list set. The name predicate is re-derived independently of the implementation and asserted to agree on every candidate; the accepted and rejected sets are then asserted to be disjoint and to cover the whole candidate space, and both sides are asserted non-empty. | +| §8.5 — the runner's stricter rules | `the_runner_refuses_an_empty_argv_entry_which_core_permits`. | +| §8.6 — the stdin policy still works and the bound is core's | `the_runner_forwards_stdin_bytes_and_enforces_the_core_stdin_bound` (the compile-time proof that `eggwork_runner::StdinPolicy` *is* `eggwork_core::StdinPolicy`, plus the bound at and over the limit) and `stdin_bytes_are_forwarded_to_the_child`. | +| §8.7 — the output bounds still behave | `the_runner_enforces_the_core_output_bounds`: over-large capture limit, zero event chunk and over-large event chunk are refused by the core output rule; a policy exactly at the bounds is accepted. | +| §8.8 — no behavioural regression | The pre-existing runner, core and sandbox-helper suites are green — see "Verification performed". | +| §10 — documentation | `architecture/runner-execution.md` rewritten for the new ownership, and all of its stale line-number citations replaced with symbol references. `architecture/core-domain.md` records that core now owns the environment-entry rules the runner consumes, and the rule-bearing citations in it were replaced with symbols. `AGENTS.md` needs no change: it already says "Construct validated state behind private fields (`RunnerRequest::from_spec`)" and `from_spec` remains the protocol path. | + +## Public-API compatibility + +### In-tree caller enumeration + +Every in-tree caller of every item whose public shape changed, as of the reviewed head: + +`RunnerRequest::new` — **kept**, signature unchanged: + +| Caller | Kind | +|---|---| +| `crates/eggwork-runner/tests/environment_policy.rs:35` | test, runner crate | +| `crates/eggwork-runner/tests/diagnostic_degradation.rs:100,156,186,227,258,278,307` | test, runner crate | +| `crates/eggwork-runner/tests/windows_process_tree.rs:143` | test, runner crate, `#![cfg(windows)]` | +| `crates/eggwork-sandbox-helper/tests/landlock_runner.rs:42` | test, sandbox-helper crate (dev-dependency on the runner) | +| `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs:608` | test, sandbox-helper crate (dev-dependency on the runner) | + +`RunnerRequest::set_environment` — **kept**, signature unchanged: + +| Caller | Kind | +|---|---| +| `crates/eggwork-runner/tests/environment_policy.rs:36` | test, runner crate | +| `crates/eggwork-sandbox-helper/tests/landlock_runner.rs:50` | test, sandbox-helper crate | +| `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs:609` | test, sandbox-helper crate | + +`eggwork_runner::StdinPolicy` — the local type is **deleted**; the path is **kept** as a re-export of `eggwork_core::StdinPolicy`: + +| Caller | Kind | +|---|---| +| `crates/eggwork-runner/tests/environment_policy.rs:26` (`use eggwork_runner::{… StdinPolicy …}`) | test, runner crate | +| `crates/eggwork-runner/tests/windows_process_tree.rs:38` | test, runner crate, `#![cfg(windows)]` | +| `crates/eggwork-sandbox-helper/tests/landlock_runner.rs:16` | test, sandbox-helper crate | +| `crates/eggwork-sandbox-helper/tests/environment_policy_parity.rs:242` | test, sandbox-helper crate | + +`RunnerError::InvalidRequest` — **payload type changed** from `String` to `eggwork_core::ValidationError`: + +| Caller | Kind | +|---|---| +| none in-tree | the server maps `RunnerError` by variant and never names `InvalidRequest`; no test constructs or matches it | + +Production callers of the runner's request API: **one**, `crates/eggwork-server/src/lib.rs:1907`, which uses `RunnerRequest::from_spec` only. The server never uses the builder path, so the server's behaviour is unaffected by the builder-path changes. + +### Out-of-tree embedder position + +**Unknown, and stated as unknown.** The runner crate is part of the released artifact set (`0.1.5`), and the plan's §7 treats it as a published crate with an external embedding surface. This repository contains no evidence of who embeds it outside the tree — no consumer manifest, no downstream workspace, no published-crate download record. Nothing in the reviewed tree establishes that the API is free to change, so it is not assumed free. The compatibility position is stated from the code, not from an assertion that there are no embedders. + +### Disposition, item by item + +| Item | Disposition | Breaking? | +|---|---|---| +| `RunnerRequest::new` | **kept**, signature unchanged; now covered by the core contract at the enforcement point, and reportable without running via `contract_error()` | No | +| `RunnerRequest::set_environment` | **kept**, signature unchanged; same | No | +| `RunnerRequest::from_spec` | **kept**; its error mapping now carries the typed core error | No (the error *payload* type changed — see the next row) | +| `eggwork_runner::StdinPolicy` | local type **deleted**; the path survives as a re-export of `eggwork_core::StdinPolicy` | No for the common case: the path still resolves, the variants have the same names and shapes, and the new type is a superset (it additionally derives `Serialize`/`Deserialize`). A downstream crate that relied on the runner's local type being *distinct* from core's would now see them unify — that is the intent, and it is a source-compatible change for every use found in-tree. | +| `RunnerError::InvalidRequest` | payload changed from `String` to `eggwork_core::ValidationError` | **Yes** — a published crate's public error type changed shape. A downstream crate that constructs `RunnerError::InvalidRequest("…".into())` or matches it as `InvalidRequest(s)` and uses `s` as a `String` will not compile. No in-tree caller does. This is a **breaking change to a published crate**: the release notes and the version must reflect it. The version bump and the release notes are the coordinator's; they are not part of this milestone. | +| `RunnerRequest::contract_error` | **added** | No (additive) | +| `eggwork_core::validate_argv`, `::validate_environment_entries`, `::validate_timeout` | **added**, public | No (additive) | + +### Why option (a) was not taken + +Option (a) — removing `RunnerRequest::new` and `RunnerRequest::set_environment` — would have required migrating five in-tree test files, two of them in `crates/eggwork-sandbox-helper/tests/`, which this milestone does not own and the plan places out of scope. It would also have made the remaining `set_*` setters unreachable, since a request could no longer be built without `new`. The plan's stop condition ("Removing the public constructor or setter would break a known in-tree caller that cannot be migrated within this milestone") is therefore met, and the closure record can state the compatibility position honestly: the builder path is kept, covered, and observable. + +## §12 stop conditions — assessed, none fired + +| Stop condition | Assessment | +|---|---| +| "Consuming the core rules would require the `eggwork-core` crate to acquire a dependency, or would create a dependency edge the workspace's one-way rule forbids" | **Did not fire.** The three new core functions use only `std` types already in the crate. `crates/eggwork-core/Cargo.toml` was not touched, and the ownership guard's dependency-direction check still passes. | +| "Removing the public constructor or setter would break a known in-tree caller that cannot be migrated within this milestone, **and** the closure record cannot state the public-API compatibility position honestly" | **Did not fire, on the second clause.** Removal *would* break five in-tree callers, two of them outside this milestone's ownership — but the compatibility position *is* stated honestly above: every caller is enumerated, the disposition is recorded item by item, and the breaking change is named. The milestone therefore proceeds under §5.5's decision rule, which selects option (b) when in-tree callers exist. | +| "The core rules are found to be *weaker* than the runner's copy on some rule, which would mean the authority itself is wrong" | **Did not fire.** Core is stronger than the runner's old copy on every rule it shares (environment name syntax, leading digit, duplicate names, resource bounds) and equal on the rest. Core is weaker in exactly one place — the empty argv entry, which the addendum names as the runner's permitted stricter rule ("the existing rejection of an empty argv entry, which protects the child-process construction") and which §5.2 and §5.3 sanction explicitly. That is a decided divergence, not a discovered one. | +| "Correcting the validation changes the observable behaviour of the server's execute path in a way that is not a pure rejection tightening" | **Did not fire.** The server builds requests only through `RunnerRequest::from_spec` (`crates/eggwork-server/src/lib.rs:1907`), and `ExecutionSpec::validate` already applied the environment and resource rules before this milestone. Every behavioural difference listed under "Rule dispositions that changed" is a pure rejection tightening, and none of them is reachable from the server's path. | +| "The milestone cannot be completed without weakening an authentication, lease, generation, fencing, or digest bound" | **Did not fire.** No bound of any kind was changed. `RunnerError::InvalidRequest` still refuses before setup and before any child exists; `CancelledBeforeSpawn` still takes precedence; lease, generation and fencing code is not in this milestone's scope and was not touched. | + +## Rule dispositions that changed + +Named explicitly, because the plan requires it. "Before" is the runner's private check at the reviewed head; "after" is the disposition in this milestone. + +| Rule | Before | After | Direction | +|---|---|---|---| +| argv empty | refused (bundled with other argv failures) | refused by `eggwork_core::validate_argv` → `Empty { field: "argv" }` | same verdict, per-rule attribution | +| argv entry count > 256 | refused | refused by `validate_argv` → `TooMany { field: "argv" }` | same | +| argv entry longer than 32 KiB | refused | refused by `validate_argv` → `OutOfRange { field: "argv entry" }` | same | +| argv entry containing NUL | refused | refused by `validate_argv` | same | +| **argv entry that is empty** | refused (bundled) | refused by the runner's own `argv_entry_violation` → `InvalidSyntax { field: "argv entry" }` | same verdict, now attributable to the runner's own rule | +| **environment name containing a character outside ASCII alphanumerics and `_`** | **accepted** by the runner | **refused** by `eggwork_core::validate_environment_entries` → `InvalidSyntax { field: "environment name" }` | **runner was weaker; now aligned** | +| **environment name beginning with an ASCII digit** | **accepted** by the runner | **refused** by `validate_environment_entries` | **runner was weaker; now aligned** | +| **duplicate environment names** | **accepted** by the runner | **refused** by `validate_environment_entries` → `InvalidSyntax { field: "duplicate environment name" }` | **runner was weaker; now aligned** | +| environment name empty | refused | refused by `validate_environment_entries` | same verdict, per-rule attribution | +| environment name longer than 256 bytes | refused | refused by `validate_environment_entries` | same | +| environment name containing NUL | refused | refused by `validate_environment_entries` | same | +| environment name containing `=` | refused | refused by `validate_environment_entries` (the charset rule covers it) | same | +| environment value longer than 16 KiB | refused | refused by `validate_environment_entries` → `TooLong { field: "environment value" }` | same verdict, per-rule attribution | +| environment value containing NUL | refused | refused by `validate_environment_entries` → `Forbidden { field: "environment value NUL" }` | same verdict, per-rule attribution | +| environment entry count > 256 | refused | refused by `validate_environment_entries` → `TooMany { field: "environment" }` | same verdict, per-rule attribution | +| **resource requirement out of core's range** (e.g. memory `Required(u64::MAX)`) | **not checked by the runner at all** | **refused** by `eggwork_core::ResourceRequirements::validate` → `OutOfRange { field: "resource requirements" }` | **new rule at the runner; a pure rejection tightening.** The server is unaffected: it builds requests only through `from_spec`, and `ExecutionSpec::validate` already applied this rule. The rule existed in core and was reachable through the runner's mutable resource door; the runner now consumes it. | +| capture limit above 16 MiB | refused | refused by `eggwork_core::OutputPolicy::validate` → `OutOfRange { field: "output policy" }` | same verdict, per-rule attribution | +| event chunk of 0 | refused | refused by `OutputPolicy::validate` | same | +| event chunk above 64 KiB | refused | refused by `OutputPolicy::validate` | same | +| timeout of zero | refused | refused by `eggwork_core::validate_timeout` → `OutOfRange { field: "timeout" }` | same verdict, per-rule attribution | +| timeout above 7 days | refused | refused by `validate_timeout` | same | +| stdin above 4 MiB | refused by the runner's local copy of the bound | refused by `eggwork_core::StdinPolicy::validate` → `TooLong { field: "stdin", max: MAX_STDIN_BYTES }` | same verdict, bound now owned by core | +| root canonicalisation / "root is a directory" | runner-owned | runner-owned, unchanged | unchanged | +| cwd canonicalisation / "cwd escapes root" | runner-owned | runner-owned, unchanged | unchanged | + +Net effect on a request that was previously accepted: three classes of request that core refused and the runner accepted are now refused by the runner (environment names with a non-alphanumeric character, names beginning with a digit, and duplicate names), plus one class the runner never checked (out-of-range resource requirements). All four are pure rejection tightenings and every one of them is a request core already considered invalid. + +## Verification performed + +All commands were run with `CARGO_TARGET_DIR=/home/sugarwookie/projects/eggwork/target-w1f`, on Linux (`6.8.0-147-generic x64`), with the pinned toolchain from `rust-toolchain.toml` (1.89.0). Counts are the real output. + +| Command | Result | +|---|---| +| `cargo fmt -p eggwork-runner -- --check` | passed (after `cargo fmt -p eggwork-runner`) | +| `cargo fmt -p eggwork-core -- --check` | passed (after `cargo fmt -p eggwork-core`) | +| `cargo clippy --locked -p eggwork-runner -p eggwork-core --all-targets --all-features -- -D warnings` | passed, no warnings | +| `cargo test --locked -p eggwork-runner --all-targets` | passed — unit: 28 passed, 0 failed, 1 ignored (`characterize_output_drain_overhead`, the pre-existing manual characterization); `capability_probe`: 2 passed; `diagnostic_degradation`: 7 passed; `environment_policy`: 5 passed; `request_validation_parity` (new): 10 passed; `windows_process_tree`: 0 tests (`#![cfg(windows)]`) | +| `cargo test --locked -p eggwork-core --all-targets` | passed — unit: 35 passed; `environment_rule_partition` (new): 3 passed; `shared_protocol_contract`: 7 passed | +| `cargo test --locked -p eggwork-sandbox-helper --all-targets` | passed — `environment_policy_parity`: 12 passed; `landlock_runner`: 18 passed. Run because that crate's tests are in-tree callers of the changed runner API. | +| `cargo check --locked --workspace --all-targets` | passed — the whole workspace, including the server, compiles against the changed runner API | +| `cargo check --locked -p eggwork-runner -p eggwork-core` | passed | +| `python3 scripts/check_execution_ownership.py` | passed — "execution ownership guard passed; approved process owners: eggwork-runner (2 spawn sites), eggwork-sandbox-helper (1 spawn sites)"; "negative scanner self-test passed; crate dependency direction passed" | + +Not run here, and therefore not claimed: the full-workspace `cargo test`, the full-workspace `cargo clippy`, `cargo fmt --all -- --check` (the coordinator's gate owns these; `cargo fmt --all` was deliberately not run because it would reformat the concurrent worker's in-flight files), and any non-Linux target. **No non-Linux platform is qualified by this record.** The Windows-only suite (`crates/eggwork-runner/tests/windows_process_tree.rs`) compiles only under `cfg(windows)` and was not executed here; its two in-tree uses of the changed API (`RunnerRequest::new` at line 143 and `eggwork_runner::StdinPolicy` at line 38) are covered by the re-export, but that is code inspection, not executed evidence. + +### Pre-existing condition, not caused by this work + +`crates/eggwork-runner/src/process_tree.rs` has a known macOS clippy failure (`method 'start_kill' is never used`, with `#[cfg(target_os = "linux")]`-gated call sites). It was **not observed** in this run, because this run was on Linux and the lint is macOS-specific. It is reported here as an inspection-level statement about a platform that was not exercised, not as an observed failure. + +## Negative and adversarial evidence + +The new suites are non-vacuous. Both were checked by deliberately breaking the code and observing the failure: + +1. **The runner's weaker environment rules restored.** The runner's `contract_violation` was temporarily replaced with the pre-corrective environment check (empty name, over-long name/value, NUL, `=` in the name — but no charset rule, no leading-digit rule and no duplicate detection). `cargo test --locked -p eggwork-runner --test request_validation_parity` then failed **3 of 10**: + - `the_runner_rejects_every_environment_name_form_core_rejects` — "a dash: the builder path must refuse \"WITH-DASH\" by the name rule; got None"; + - `a_duplicate_environment_name_is_refused_by_the_duplicate_rule` — "a repeated name must be refused by the duplicate rule; got None"; + - `every_public_construction_path_reaches_the_same_contract_verdict` — "an environment name with a dash: the two construction paths must report the same typed error; left: None, right: Some(InvalidSyntax { field: \"environment name\" })". + + The runner was then restored and the suite returned to 10/10. + +2. **Core's environment-name rule widened.** `eggwork_core`'s name rule was temporarily widened to accept `-`. `cargo test --locked -p eggwork-core --test environment_rule_partition` then failed: "the implementation and the documented rule disagree about \"A-B\": implemented accepted = true, documented accepted = false". Core was then restored and the suite returned to 3/3. + +3. **Refusal happens before the spawn.** Every refusal assertion in the runner suite runs a real request whose target would create a marker file, and asserts the marker does not exist afterwards. This is the adversarial form of "the request was refused", not merely "the request returned an error". + +4. **The stricter direction is checked, not just the stricter-rule behaviour.** `the_runner_refuses_an_empty_argv_entry_which_core_permits` asserts that `from_spec` *accepts* the same spec, so the test cannot pass by core having become stricter. + +## Documentation status + +- `architecture/runner-execution.md` — updated. The request-validation narrative now states that the rules have one owner in core and that the runner consumes them; the `RunnerRequest` field table now names the rule owner and the checker per field; the "Two `StdinPolicy` types" section became "One `StdinPolicy`"; the `RunnerError` table now describes the typed payload; the "What a caller cannot do" section states the coverage property; the runner-level empty-argv rule is documented with its reason; and the test-coverage section describes the two new suites. **All 42 stale line-number citations in this file were replaced with symbol references**, as the plan required — `grep -nE "lines? [0-9]+" architecture/runner-execution.md` now returns nothing. +- `architecture/core-domain.md` — updated. The `CommandSpec::validate` section now records that the argv, environment-entry and timeout rules are three public core functions rather than inline code, and that core is the single owner of the environment-entry rules; the rule-bearing citations were replaced with symbols. The remaining `lib.rs:NNN` citations in this file were **already stale before this milestone** (spot-checked against the reviewed head: `lib.rs:229-268`, cited for `EnvironmentEntry`, actually pointed inside `DiagnosticError`; `lib.rs:1264`, cited for a test, pointed at the `Spawn` enum variant), and the plan scopes the citation cleanup to the runner deep dive, so they were left alone. That is a recorded residual, not an oversight. +- `architecture/overview.md` — **not changed by this worker** (coordinator-owned). No residual divergence is known to remain: the runner is now at least as strict as core on every shared rule and the one stricter rule is explicit. If the coordinator prefers a row in the divergences table, the proposed text is in the handoff report. +- `AGENTS.md` — **not changed**: the line "Construct validated state behind private fields (`RunnerRequest::from_spec`)" remains accurate. `from_spec` is still the protocol path and the construction path is still private-fields-based. +- `plans/subsystems/foundation-execution-core-roadmap.md` — updated: the status line and the M005 entry now read `active`, the M005 entry carries the implementation record and the public-API disposition, and the entry points at this closure record. +- `plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md` — `Status:` changed from `proposed` to `active`. The coordinator sets the final status after the gate. +- `docs/` — no change. The loader strictness and the operator verbs are unaffected; the runner's request contract is an embedding-surface concern, not an operator-facing one. + +## Unresolved findings, by severity + +**No high or medium findings.** + +- **Low — the `RunnerError::InvalidRequest` payload type change is breaking for unknown out-of-tree embedders.** The out-of-tree position is unknown (§ "Out-of-tree embedder position"), so the change is recorded as breaking and must be reflected in the release notes and the version. Mitigation: no in-tree caller; the error family, the variant name and the `Display` prefix are unchanged; the new payload is strictly more informative. +- **Low — the builder path is checked at the enforcement point rather than at the setter.** The plan's option (b) said the public setters would "validate with a typed error" *at the call*. Every reading of (b) that changes a signature is blocked by the same boundary as (a): `RunnerRequest::new` and `RunnerRequest::set_environment` have five in-tree callers across two crates, two of them in `crates/eggwork-sandbox-helper/tests/` which this milestone does not own; changing either to return `Result<_, ValidationError>` would not compile those callers, and would additionally introduce `unused_must_use` warnings that fail `clippy -D warnings` in files this milestone cannot edit. The typed error is therefore returned by the enforcement point (`RunnerRequest::validate`, before setup and before any child exists) and is observable without running via the new `RunnerRequest::contract_error()`. The property the milestone protects — no request built through any public path is *executed* in violation of the core contract — holds, and is proved by test. What does not hold is the stronger literal reading of §4.4: a request *object* built through the builder can transiently hold a core-invalid value between the setter call and the run. If the coordinator prefers the stricter reading, the follow-up is a separate API-breaking milestone that migrates the five callers to `from_spec` and returns `Result` from the setters. +- **Low — `architecture/core-domain.md` still carries stale `lib.rs:NNN` citations** outside the rule-bearing text this milestone touched. They pre-date this work; the plan scopes the citation cleanup to the runner deep dive. +- **Low — the root/cwd rules remain untested at the runner level.** Unchanged by this milestone and already recorded as a thin area in `architecture/runner-execution.md`. The "cwd escapes root" case is covered only in the helper crate's test, and only in its symlink form. +- **Informational — the runner now refuses out-of-range resource requirements** that it previously accepted. Pure rejection tightening; the server is unaffected because it only uses `from_spec`. + +## Registry and roadmap disposition + +- Roadmap `plans/subsystems/foundation-execution-core-roadmap.md`: M005 status set to `active`; the roadmap status line updated to read "M005 request-validation parity corrective active"; the M005 entry carries the public-API disposition and points at this record. The coordinator sets the final status after the gate. +- Registry `plans/registry.md`: **coordinator-owned; not edited by this worker.** The proposed entry text is in the handoff report. +- No other roadmap or closure file was edited. + +## Scope note + +`crates/eggwork-sandbox-helper` was **not** modified. Its production crate has no workspace-crate dependency, as the plan states, and it does not construct runner requests. Its *integration tests* do, and they were the reason option (a) was not taken; they were left untouched and their suite was run to confirm they still pass against the changed runner API. diff --git a/plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md b/plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md index 2e49b05..a63c5d0 100644 --- a/plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md +++ b/plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md @@ -1,6 +1,6 @@ # Foundation M005 — Runner request validation parity corrective -Status: proposed +Status: active Closure record: `plans/closure/foundation-execution-core/005-status.md` diff --git a/plans/subsystems/foundation-execution-core-roadmap.md b/plans/subsystems/foundation-execution-core-roadmap.md index d7d0bda..8a0a8ff 100644 --- a/plans/subsystems/foundation-execution-core-roadmap.md +++ b/plans/subsystems/foundation-execution-core-roadmap.md @@ -1,6 +1,6 @@ # Foundation and Execution Core Roadmap -Status: M001-M004 closed (M004 conditional on a release containing it); C001 post-closure CI corrective closed; M005 request-validation parity corrective proposed +Status: M001-M004 closed (M004 conditional on a release containing it); C001 post-closure CI corrective closed; M005 request-validation parity corrective active Canonical authority: @@ -155,7 +155,7 @@ Dependencies: Class: invariant -Status: proposed +Status: active Corrective addendum: @@ -177,6 +177,12 @@ Exit conditions: - the runner's local `StdinPolicy` duplicate and its hand-written conversion are removed; - no numeric bound and no wire representation changes. +Implementation record: + +- `plans/closure/foundation-execution-core/005-status.md` + +Owner disposition for the public API: the runner's public `RunnerRequest::new` and `RunnerRequest::set_environment` are **kept**, not removed. Both have in-tree callers in five test files across two crates — two of them in `crates/eggwork-sandbox-helper/tests/`, which is outside this milestone's file ownership and outside the plan's stated scope — so removing them would have broken the build rather than hardened it. They are instead covered by the core contract at the single enforcement point, with `RunnerRequest::contract_error()` reporting a violation without running anything. The runner's local `StdinPolicy` duplicate is deleted; the public path `eggwork_runner::StdinPolicy` survives as a re-export of `eggwork_core::StdinPolicy`. + ## 4. CodeGG reuse strategy The implementation agent MUST inspect the current CodeGG `src/managed_process.rs` baseline before M002. From c87a4b6cde797814c50f42bd24ad56375f125d38 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Sun, 25 Oct 2026 08:08:09 +0000 Subject: [PATCH 15/37] docs(architecture,plans): close divergence #4 and register the M005c and Foundation M005 dispositions - architecture/overview.md divergence #4 is closed by ADR-0007 (Option A): the resource-aware hook now decides, the store's principal_id fences remain authoritative for ownership, and the residual blob boundary is stated plainly rather than implied closed. - plans/registry.md records M005c as unblocked by the accepted ADR, and Foundation M005 as active. --- architecture/overview.md | 2 +- plans/registry.md | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/architecture/overview.md b/architecture/overview.md index a268c66..6ece9f5 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -172,7 +172,7 @@ None of these are presented as bugs already judged to be bugs. They are the plac | # | Observation | Where | |---|---|---| -| 4 | `GrantAuthorizer` implements only `Authorizer::authorize`, **not** the resource-aware `authorize_request` hook. Resource-scoped authorization is therefore inert on the real deployment path; ownership is enforced only in the store, by `principal_id` comparison. | [operations-cli.md](operations-cli.md) · [server-node.md](server-node.md) | +| 4 | ~~`GrantAuthorizer` implements only `Authorizer::authorize`, **not** the resource-aware `authorize_request` hook. Resource-scoped authorization is therefore inert on the real deployment path; ownership is enforced only in the store, by `principal_id` comparison.~~ **Closed 2026-10-25 by [ADR-0007](../plans/adrs/ADR-0007-resource-scoped-authorization.md) (Option A).** `GrantAuthorizer` now implements `authorize_request`: a grant may carry a bounded, optional list of resource scopes naming an operation, a resource kind, and a typed identifier, and the decision narrows the operation grant against that configuration-derived set. The scope is per `(operation, kind)`, so a scope for `Execute`/`Execution` does not narrow `Execute`/`Workspace`. The store's `principal_id` fences remain authoritative for ownership, so a scope naming another principal's execution, workspace, or artifact is still refused there. **Residual boundary:** a grant with no scope is still operation-wide, so a broad `BlobRead` still reaches any known digest — blob storage is content-addressed and shared, so a blob has no owner to fence it, and a blob scope is an explicit digest list the operator must configure. | [operations-cli.md](operations-cli.md) · [server-node.md](server-node.md) · [threat-model.md](../plans/security/threat-model.md) | | 5 | `deployment::check_helper_compatibility_with_timeout` checks the helper **file** only, while `eggwork_runner::verify_trusted_helper` also walks every ancestor directory. The deployment trust path is the weaker subset plus version coherence. | [deployment-lifecycle.md](deployment-lifecycle.md) · [runner-execution.md](runner-execution.md) | | 6 | Invariant 2 (no direct node-service manager invocation) has **no dedicated mechanical guard**. The only automated check is the Rust test `no_direct_service_manager_invocation_exists` in `deployment.rs`, and it scans just three files (`src/deployment.rs`, `src/operations.rs`, `src/bin/eggworkd.rs`) for manager *string literals*. `eggwork-runner` is outside that scope entirely. | [ci-guardrails.md](ci-guardrails.md) | | 7 | The ownership guard globs only `crates/*/src/**/*.rs`. `tests/`, `examples/`, and `build.rs` are unscanned, and the allowlist is keyed by crate name rather than path. | [ci-guardrails.md](ci-guardrails.md) | diff --git a/plans/registry.md b/plans/registry.md index 88f9f0f..a69f2e0 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -94,7 +94,7 @@ A repository-wide code interrogation pass over the reviewed baseline found no `t | `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md` | M005a declared-artifact capture fail-closed; M005b GC preview and store ownership | invariant | M005a conditionally closed; M005b closed | | `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md` | M005a degraded-isolation observability; M005b sandbox-helper environment parity; M005c resource-scoped authorization | invariant | M005a conditionally closed; M005b closed; **M005c active — ADR-0007 accepted, Option A** | | `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md` | M008a operator surface truthfulness; M008b release harness and documentation single-sourcing | capability; infrastructure/polish | proposed | -| `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | proposed | +| `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | M005 runner request validation parity | invariant | active | None of these milestones is dependency-ready. M007 remains the only ready handoff. The batch is registered so that the new findings are visible as current authority rather than as unwritten observations, and so that the five subsystems' roadmaps can be amended to point at their correctives. @@ -108,7 +108,7 @@ Two findings in this batch were deliberately **not** given a milestone, because | Workstream | Status | Current work | Authority | |---|---|---|---| | Optional Gregg host telemetry | **closed; M001 and M002 both closed** | M001 closed the default-off loopback Gregg adapter, normalized cache and single polling owner (`plans/closure/optional-gregg-host-telemetry/001-status.md`, implementation `ac55985`); M002 closed the authorized node telemetry API/client behind a narrow `telemetry` grant (`plans/closure/optional-gregg-host-telemetry/002-status.md`, implementation `5ccb1e6`). The frozen contract is `eggwork_core::NodeTelemetry` schema version 1. No Gregg changes, no Eggwork scheduling, no capability feature added. The CodeGG worker-telemetry consumer is unblocked. | `plans/subsystems/optional-gregg-host-telemetry-roadmap.md`, `plans/adrs/ADR-0006-optional-gregg-host-telemetry.md` | -| Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective proposed; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | +| Foundation / execution core | M001-M003 closed; M004 conditionally closed; M005 corrective active; no ready implementation work | Windows execution is implemented: M004 replaced the `UnsupportedPlatform` gate with a Job Object process-tree backend and qualified the tree lifecycle on hosted `windows-latest`. What remains is the installed-release receipt, which needs a release containing M004. A repository interrogation pass added M005: the runner's request validation is a weaker restatement of the core domain contract, and the runner's public constructor and environment setter bypass even that | `plans/subsystems/foundation-execution-core-roadmap.md`, `plans/closure/foundation-execution-core/004-status.md`, `plans/subsystems/foundation-execution-core-post-closure-ci-corrective-addendum.md`, `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md` | | Control-plane protocol | M001-M004 closed; no milestone in flight | M001-M003 complete. A repository interrogation pass added M004: `API_SCHEMA_VERSION` is declared independently in the client and the server that must agree on it, the capability feature-name strings are re-typed across runner, server, and client, and the terminal-state classification is enumerated in roughly nine places because `eggwork-core` owns no terminal concept — **implemented**: `eggwork-core` now owns the control-plane schema version, the `exec.argv.v1` capability name, and the terminal/non-terminal classification, and the runner owns the capability names it produces. No wire value, wire field, or capability byte changed. Closure record: `plans/closure/control-plane-protocol/004-status.md` | `plans/subsystems/control-plane-protocol-roadmap.md`, `plans/subsystems/control-plane-protocol-shared-contract-corrective-addendum.md` | | Workspace / artifacts | M001-M004 closed; M005a conditionally closed, M005b closed | M001-M004 closed, including reusable manifest CAS + derived materialization (`plans/closure/workspace-artifact-transport/004-status.md`). A repository interrogation pass added M005a (on a non-Unix target declared-artifact capture is refused while the execution still reports `Succeeded` with zero artifacts) — **implemented**: a declared output that was not captured now ends the execution in a truthful non-success state with a first-class disposition and a diagnostic event, and a node whose platform cannot capture no longer advertises `artifact.declared.v1` — and M005b (the operator's GC dry-run preview and the apply pass use different candidate predicates, and the store's path layout and manifest owner-id format are re-derived outside their owners) | `plans/subsystems/workspace-artifact-transport-roadmap.md`, `plans/closure/workspace-artifact-transport/004-status.md`, `plans/subsystems/workspace-artifact-transport-data-plane-corrective-addendum.md`, `plans/closure/workspace-artifact-transport/005a-status.md`, `plans/closure/workspace-artifact-transport/005b-status.md` | | Security / isolation / resources | M001-M004 plus remote-admission corrective C001 closed; M005a conditionally closed, M005b closed, M005c active | M001-M004 plus remote-admission corrective C001 are closed (`plans/closure/security-isolation-resource/004-status.md`); macOS/Windows hosted qualification remains future Operations M004 work, not a Security defect. A repository interrogation pass added M005a (degraded isolation is recorded in the terminal snapshot but never emitted as a production diagnostic event, so an event-streaming caller cannot see it) — **implemented**: a degraded best-effort request now produces a bounded diagnostic event published by the runner before the target spawns, so it precedes any target output and the terminal event; the diagnostic grammar is owned by `eggwork-core`. Also added M005b (the sandbox environment deny-list is maintained twice, with different drop-versus-reject semantics), and M005c, whose disposition of the already-recorded inert resource-scoped authorization hook was **decided by ADR-0007** (accepted 2026-10-25, Option A — implement resource-scoped grants) and is now being implemented as Branch A of its plan | `plans/subsystems/security-isolation-resource-roadmap.md`, `plans/subsystems/security-isolation-resource-remote-admission-corrective-addendum.md`, `plans/subsystems/security-isolation-resource-isolation-truthfulness-corrective-addendum.md`, `plans/closure/security-isolation-resource/005a-status.md`, `plans/adrs/ADR-0007-resource-scoped-authorization.md` | @@ -180,7 +180,7 @@ The repository interrogation corrective batch is registered and is being worked. | Workspace M005b GC preview and store ownership corrective | **closed** | `plans/implementation/workspace-artifact-transport/005b-gc-preview-and-store-ownership-corrective.md`. The operator's GC dry-run preview and the apply pass used different candidate predicates, in a module whose own doc comment states the two must be shared. Implemented: the candidate predicate, the metadata filenames, and the blob path layout each have one owner; the preview reaches owner code through a read-only, non-reconciling seam (`blob::preview_gc`, `workspace::preview_gc`, `artifact::preview_gc`); the materializer verifies the bytes it writes against the manifest digest **while copying** (`BlobStore::copy_verified`); and the manifest owner-id composite has one producer with two entry points. Closure record: `plans/closure/workspace-artifact-transport/005b-status.md`. | | Security M005a degraded-isolation observability corrective | **conditionally closed** | `plans/implementation/security-isolation-resource/005a-degraded-isolation-observability-corrective.md`. `ExecutionEventKind::Diagnostic` was emitted only from test code, so a degraded best-effort isolation or resource enforcement was invisible to an event-streaming caller. Implemented: the runner emits a bounded diagnostic through its output channel **before the target spawns**, the server forwards it as `ExecutionEventKind::Diagnostic`, and the diagnostic grammar is owned by `eggwork-core` so producer and server share one definition. The diagnostic precedes the target's first output and the terminal event, is durable in the journal, and is emitted exactly once per degradation. The `Required` path is untouched. Closure record: `plans/closure/security-isolation-resource/005a-status.md`. | | Security M005b sandbox-helper environment parity corrective | **closed** | `plans/implementation/security-isolation-resource/005b-sandbox-helper-environment-parity-corrective.md`. The environment deny-list was maintained in the runner and again in the standalone sandbox helper, with different semantics — the runner silently drops denied keys, the helper rejects the whole launch — and the helper's `PATH` rule had no runner counterpart. The helper's no-workspace-dependency rule makes the duplication architecturally forced, so the fix is a shared artifact plus a pinning test, not a shared crate. **This was the most severe finding in the batch**, and it was live: the runner's launch-spec builder started from a fixed baseline and appended every non-denied caller key, and none of those baseline keys except `PATH` was denied. A caller that set `LANG` produced a launch specification with two `LANG` entries; the helper refused it with status 12; the runner read that as a pre-target setup failure and — for a **best-effort** request only — rewrote the sandbox outcome to `NotApplied` and **re-spawned the target directly with no Landlock ruleset at all**. Implemented: the environment policy now has one checked-in source of truth (`crates/eggwork-runner/policy/environment-policy.toml`), a deterministic generator (`scripts/generate_environment_policy.py`), and generated copies in each crate; one builder serves both the direct and the helper launch path; the runner drops denied keys and lets the node's value win for node-owned keys; the helper refuses a policy violation with its own status byte, **13**, distinct from the general specification-validation status 12. The `Required` path is untouched and still fails closed. Closure record: `plans/closure/security-isolation-resource/005b-status.md`. | -| Security M005c resource-scoped authorization corrective | **blocked** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. Blocked on ADR-0007 (`plans/adrs/ADR-0007-resource-scoped-authorization.md`, **proposed, not accepted**), which must decide whether resource-scoped grants are implemented or the inert hook and its `ResourceId` plumbing are removed. The gap itself is already recorded as divergence #4; this is a decision about a known gap, not a new defect. | +| Security M005c resource-scoped authorization corrective | **active** | `plans/implementation/security-isolation-resource/005c-resource-scoped-authorization-corrective.md`. ADR-0007 is **accepted** — Option A: implement resource-scoped grants. The hook is real: `GrantAuthorizer` implements `authorize_request` and a grant may carry a bounded, optional resource-scope list naming an operation, a resource kind, and a typed identifier. The store's `principal_id` fences remain authoritative for ownership, and blobs are governed by an explicit digest list because content-addressed blob storage has no owner. A resource-scoped denial is indistinguishable from an operation-level denial. No wire value, wire field, capability byte, or `API_SCHEMA_VERSION` changes. Closure evidence: `plans/closure/security-isolation-resource/005c-status.md`. | | Operations M008a operator surface truthfulness corrective | **proposed** | `plans/implementation/operations-distribution/008a-operator-surface-truthfulness-corrective.md`. Five live metrics are incremented by the server and never reported by `eggworkd status`/`eggworkd metrics`; one `active_executions` field name carries two different meanings across the API and the CLI; and every configuration fault collapses into the single unhelpful message `configuration is invalid or unreadable`. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | | Operations M008b release harness and documentation single-sourcing corrective | **proposed** | `plans/implementation/operations-distribution/008b-release-harness-and-documentation-single-sourcing-corrective.md`. The release harness re-derives the workspace version, the release asset inventory, the install identities, and the target classification that already have owners; the tag guard's own docstring deliberately keeps it out of CI, so the defect is the divergent parser and the absence of any automated exercise, not the missing CI wiring. Roughly 92% of the design record's line-number citations no longer point at the symbol they claim, every crate size figure in `architecture/overview.md` is stale, and divergence #20 now describes a fixed issue as open. CI type-checks feature-gated code it never executes — the qualification workflow is `workflow_dispatch`-only, so the suite runs on no ordinary pull request, and adding `--all-features` would not close the gap because those tests are `#[ignore]`d — while one runner test passes with zero assertions on the normal CI path. Addendum: `plans/subsystems/operations-distribution-operator-truthfulness-corrective-addendum.md`. | | Foundation M005 runner request validation parity corrective | **proposed** | `plans/implementation/foundation-execution-core/005-runner-request-validation-parity-corrective.md`. The runner's private request validation is a weaker restatement of the `eggwork-core` contract — it accepts environment names core rejects and does not detect duplicate names — and the runner's public constructor and public environment setter reach that gate without passing through core validation at all, contradicting the runner's own documented claim that callers cannot bypass protocol bounds. Addendum: `plans/subsystems/foundation-execution-core-request-validation-corrective-addendum.md`. | @@ -227,7 +227,7 @@ Repository interrogation corrective batch [PARTLY IMPLEMENTED] --+--> Control-pl +--> Workspace M005b GC preview and store ownership [CLOSED] +--> Security M005a degraded-isolation observability [CONDITIONALLY CLOSED] +--> Security M005b helper environment parity [CLOSED] - +--> Security M005c resource-scoped authorization [BLOCKED on ADR-0007] + +--> Security M005c resource-scoped authorization [ADR-0007 ACCEPTED — IMPLEMENTING] +--> Operations M008a operator surface truthfulness [PROPOSED] +--> Operations M008b release harness and docs single-sourcing [PROPOSED] +--> Foundation M005 runner request validation parity [PROPOSED] From c8999e1870e9646475b4bed7772c518fc9ea4d41 Mon Sep 17 00:00:00 2001 From: wr3n-ai Date: Sun, 25 Oct 2026 09:16:19 +0000 Subject: [PATCH 16/37] =?UTF-8?q?feat(release):=20M008b=20OP-4/OP-6=20?= =?UTF-8?q?=E2=80=94=20one=20owner=20per=20fact,=20and=20CI=20executes=20w?= =?UTF-8?q?hat=20it=20type-checks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The release harness re-derived facts that already had one owner, and CI type-checked code it never executed. OP-4 — the rule the milestone establishes: multiple readers of one owner are fine; multiple owners are not. - The workspace version now has one Python reader. release_candidate_probe.py owns read_manifest/workspace_version with tomllib; check_release_tag.py and qualify_release.py obtain the version through it. The old regex reader in check_release_tag.py — which took the first 'version =' line in the file and worked only by accident of the manifest layout — is gone. - Cargo.lock is parsed with a real TOML reader, and the repository's own packages are selected structurally (no 'source'), not by a name prefix. - The two version authorities are reconciled and written down: the manifest is the build assertion (what the binaries report); the tag is the release gate, and check_release_tag.py is the only place a tag and a version are compared. The harness reads the manifest-derived version and delegates the tag comparison to the gate. - QUALIFIED_ASSET_COUNT is deleted, not re-synced: the expected asset set is derived from the contract and the receipt's count is computed from it. - The harness holds no literal install or service identity. Install identities come from release/eggpack/distribution.toml; the service identity is read from the candidate daemon. Target classification is derived from the contract's asset entries instead of a triple suffix. OP-6 — CI executes what it type-checks. - The qualification suite's ignored tests now execute in a dedicated job that has the environment they need, with --test-threads=1 (they fail concurrently on the daemon's state lock). The workflow and the CI narrative record why the default test step does not enable the qualification feature. - The capability probe no longer passes with zero assertions when it cannot find the helper: it fails loudly and names the paths it tried. It was exercised in both directions. The tag-dependent half of the guard still cannot run in CI — CI never knows the future tag, and the release workflow is generated by eggpack. That prerequisite is recorded rather than faked; the tag-independent half (the manifest against the lock) now runs on every push and pull request. --- .github/workflows/ci.yml | 131 ++++++ architecture/ci-guardrails.md | 156 ++++++- architecture/release-qualification.md | 195 +++++++- .../eggwork-runner/tests/capability_probe.rs | 49 +- .../tests/installed_qualification.rs | 29 +- docs/releases.md | 38 +- .../operations-distribution/008b-status.md | 432 ++++++++++++++++++ ...ocumentation-single-sourcing-corrective.md | 2 +- scripts/check_release_tag.py | 252 ++++++++-- scripts/qualify_release.py | 401 ++++++++++++---- scripts/release_candidate_probe.py | 43 +- .../test_release_harness_derivations.py | 365 +++++++++++++++ tests/release/test_release_tag_guard.py | 263 +++++++++++ 13 files changed, 2188 insertions(+), 168 deletions(-) create mode 100644 plans/closure/operations-distribution/008b-status.md create mode 100644 tests/release/test_release_harness_derivations.py create mode 100644 tests/release/test_release_tag_guard.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cf95697..6ac2881 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -24,9 +24,38 @@ jobs: # release attempt: the `v0.1.3` producer run failed closed on it. CI must # catch a stale lock before a release does. - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + # The runner's capability probe drives the *built* sandbox helper and + # fails loudly when it is absent, so the helper has to exist before the + # test step runs. Building it explicitly is what makes the precondition + # deterministic rather than incidental. + - name: build the sandbox helper the capability probe drives + run: cargo build --locked -p eggwork-sandbox-helper + # The default test step does **not** enable the `qualification` feature: + # the qualification suite names an installed release as its subject + # through the environment, so it belongs in the `installed-qualification` + # job below, which stages that installation. Its tests are `#[ignore]`d + # as well, so adding `--all-features` here would not run them either. - run: cargo test --locked --workspace --all-targets - run: cargo check --workspace + - name: release identity coherence + # The release gate has two halves. The tag-dependent half — "does the + # tag about to be created name the workspace version?" — cannot live + # in CI: CI never knows the future tag, and the generated release + # workflow is producer authority. `scripts/check_release_tag.py` owns + # that comparison and is run by whoever cuts the tag, before the tag + # exists. + # + # The tag-independent half is the workspace manifest's version against + # the versions `Cargo.lock` pins for this repository's own packages. + # That is what this step asserts, on every push and every pull + # request, and it is exactly the condition that broke the `v0.1.3` + # release attempt. + run: python3 scripts/check_release_tag.py --coherence - name: release candidate validator tests + # These are the tag guard's own tests: they exercise the code path + # that decides whether a release may be tagged, against fixtures, so + # the guard's correctness is an executed result rather than a trusted + # assumption. run: python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release windows-runner: # The Windows process-tree backend cannot be observed from Linux: Job Object @@ -64,6 +93,13 @@ jobs: - name: eggwork-runner test targets run: cargo clippy --locked -p eggwork-runner --all-targets --all-features -- -D warnings - name: Windows process-tree lifecycle suite + # The runner's capability probe drives the built sandbox helper and + # fails loudly when it is absent, so this job would need the helper + # built too. It does not: the helper-dependent half of that probe is + # `#[cfg(target_os = "linux")]`, so it does not exist in this job at + # all, and only the platform-neutral negative case — a missing helper + # must not advertise a capability — runs here. The Linux `rust` job + # builds the helper explicitly and runs the full probe. run: cargo test --locked -p eggwork-runner --all-targets -- --nocapture # One portable server integration target, and only that target. The # declared-artifact capture disposition is a contract about the @@ -74,6 +110,101 @@ jobs: # test surface is still Linux-only and is not claimed here. - name: declared-artifact capture disposition suite run: cargo test --locked -p eggwork-server --test artifact_capture_disposition + installed-qualification: + # The `qualification`-feature suite qualifies an *installed* release: it + # names its subject through the environment (`EGGWORK_QUALIFY_DAEMON`, + # `EGGWORK_QUALIFY_CONFIG`, `EGGWORK_QUALIFY_TLS_DIR`) and its three + # tests are `#[ignore]`d. + # + # That is why the default `cargo test` step does not enable the feature. + # Adding `--all-features` there would compile the file, but the + # `#[ignore]` attributes would still keep all three tests out of the run, + # and an ordinary test run has no installed release to drive in the first + # place. The suite is therefore executed here, in the job that stages the + # installation it drives, so a green CI run is evidence that the code + # ran rather than only that it type-checked. + # + # The `operational-qualification` workflow runs the same suite against a + # *published* release's exact bytes. This job runs it against the bytes + # this repository builds, on every push and every pull request. + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.89.0 + - uses: Swatinem/rust-cache@v2 + - name: build the installed product surface + run: cargo build --locked -p eggwork-server -p eggwork-sandbox-helper --bins + - name: stage the installation root + # The directories are created 0755 rather than with the shell's umask, + # because the installed helper's trust check walks every ancestor of + # its own path and refuses a group- or world-writable one. + shell: bash + run: | + set -euo pipefail + root="${{ runner.temp }}/qualification" + mkdir -p "$root/bin" + install -m 0755 target/debug/eggworkd "$root/bin/eggworkd" + install -m 0755 target/debug/eggwork-sandbox-helper "$root/bin/eggwork-sandbox-helper" + chmod 0755 "$root" "$root/bin" + - name: check the installation root's trust chain + # The product's own rule, checked before the node is started: the + # helper's path and every ancestor of it must be free of group- and + # world-writable bits. The qualification harness's `ensure_trusted_root` + # fails closed on the same condition; here it is checked explicitly so + # a runner whose temporary directory is group-writable reports that + # reason instead of the node refusing its own helper. + shell: bash + env: + INSTALL_ROOT: ${{ runner.temp }}/qualification + run: | + set -euo pipefail + current="$INSTALL_ROOT" + while true; do + mode=$(stat -c '%a' "$current") + world="${mode: -1}" + group="${mode: -2:1}" + if [ $(( world & 2 )) -ne 0 ] || [ $(( group & 2 )) -ne 0 ]; then + echo "$current is group/world writable (mode $mode); the installed helper's trust check walks every ancestor and would reject it" >&2 + exit 1 + fi + parent=$(dirname "$current") + if [ "$parent" = "$current" ]; then + break + fi + current="$parent" + done + - name: materialise the bounded qualification fixture + # The TLS fixture and node configuration come from the repository's own + # `rcgen`-based harness, not from whichever OpenSSL the runner ships. + shell: bash + env: + EGGWORK_QUALIFY_ROOT: ${{ runner.temp }}/qualification + run: | + set -euo pipefail + cargo test --locked -p eggwork-server --features qualification \ + --test installed_qualification -- --ignored --exact qualification_fixture + - name: qualify installed execution through the production client + # Both qualification tests run against the fixture the previous step + # materialised; the fixture itself is skipped here so it is not + # re-materialised underneath the node that is already running. + # + # `--test-threads=1` is load-bearing. The two tests share one + # installation root, one state directory, and one execution-state + # lock, so a concurrent second daemon cannot start: the first test + # would fail with "the installed daemon exited before reporting + # ready". They are one installation, qualified one at a time. + shell: bash + env: + EGGWORK_QUALIFY_DAEMON: ${{ runner.temp }}/qualification/bin/eggworkd + EGGWORK_QUALIFY_CONFIG: ${{ runner.temp }}/qualification/state/node.json + EGGWORK_QUALIFY_TLS_DIR: ${{ runner.temp }}/qualification/state/tls + EGGWORK_QUALIFY_PLATFORM: linux + run: | + set -euo pipefail + cargo test --locked -p eggwork-server --features qualification \ + --test installed_qualification -- --ignored --skip qualification_fixture \ + --test-threads=1 --nocapture release-drift: # Eggpack is producer authority for the release matrix: the generated # release workflow must be exactly what the pinned tool renders from the diff --git a/architecture/ci-guardrails.md b/architecture/ci-guardrails.md index c787c88..7798f0b 100644 --- a/architecture/ci-guardrails.md +++ b/architecture/ci-guardrails.md @@ -163,8 +163,12 @@ The allowlist is keyed by crate name, so a backend that lives inside `eggwork-ru run: python3 scripts/check_execution_ownership.py --prove-negative-exit - run: cargo fmt --all -- --check - run: cargo clippy --locked --workspace --all-targets --all-features -- -D warnings + - name: build the sandbox helper the capability probe drives + run: cargo build --locked -p eggwork-sandbox-helper - run: cargo test --locked --workspace --all-targets - run: cargo check --workspace + - name: release identity coherence + run: python3 scripts/check_release_tag.py --coherence - name: release candidate validator tests run: python3 -m unittest discover --start-directory tests/release --top-level-directory tests/release ``` @@ -178,9 +182,11 @@ Step by step, and what each would miss without it: 5. **negative-exit proof** — as above. Without it, the guard is a check that has only ever returned 0 in practice. 6. **`cargo fmt --all -- --check`** — mechanical formatting. Without it, diffs carry noise and review attention moves from substance to whitespace. 7. **`cargo clippy --locked --workspace --all-targets --all-features -- -D warnings`** — `--all-features` matters because the qualification and test features are where the interesting code lives; `-D warnings` is what makes the promotion from "warn" to "fail" real, matching `[workspace.lints.clippy] all = "warn"`. Without it, warnings accumulate and the workspace lint table becomes decorative. -8. **`cargo test --locked --workspace --all-targets`** — the whole Rust suite, including `crates/eggwork-server/tests/release_contract.rs` (36 `#[test]` functions), because `--all-targets` pulls in integration tests. This is where most of the release-configuration invariants in the map above are actually enforced. -9. **`cargo check --workspace`** — a cheap whole-workspace type check *without* `--locked` and without `--all-targets`. It is the fastest possible signal on a broken tree and the first thing a contributor sees go red. -10. **Python release validator tests** — the harness test suite, below. +8. **`cargo build --locked -p eggwork-sandbox-helper`** — the runner's capability probe drives the *built* helper and **fails loudly** when it is absent, so the helper has to exist before the test step. Before Operations M008b that probe returned early and passed with zero assertions when it could not find the helper, which made the skip the normal path in CI as well as locally: the test proved nothing and reported success. Building the helper explicitly is what makes the precondition deterministic rather than incidental. The probe is not a separate job because the runner's test targets already run in this job. +9. **`cargo test --locked --workspace --all-targets`** — the whole Rust suite, including `crates/eggwork-server/tests/release_contract.rs` (36 `#[test]` functions), because `--all-targets` pulls in integration tests. This is where most of the release-configuration invariants in the map above are actually enforced. +10. **`cargo check --workspace`** — a cheap whole-workspace type check *without* `--locked` and without `--all-targets`. It is the fastest possible signal on a broken tree and the first thing a contributor sees go red. +11. **`release identity coherence`** — `python3 scripts/check_release_tag.py --coherence`. The release gate has two halves and only one of them needs a tag. The **tag-dependent** half — "does the tag about to be created name the workspace version?" — cannot live in CI: CI never knows the future tag, and the generated release workflow is producer authority. That comparison lives in `scripts/check_release_tag.py` and is run by whoever cuts the tag, before the tag exists. The **tag-independent** half — the workspace manifest's version against the versions `Cargo.lock` pins for this repository's own packages — needs no tag, so it runs here, on every push and every pull request. It is exactly the condition that broke the `v0.1.3` release attempt. The workflow says so in the step's own comment, so a reader does not have to infer where the gate is. +12. **Python release validator tests** — the harness test suite, below. It now includes the tag guard's own tests, so the code path that decides whether a release may be tagged is **executed against fixtures** by an automated job rather than trusted. ### Why `--locked` is load-bearing @@ -216,6 +222,20 @@ A second job in the same workflow, on `windows-latest`, added by Foundation M004 run: cargo test --locked -p eggwork-server --test artifact_capture_disposition ``` +**The capability probe's loud failure is not expected here, and the reason is +recorded.** The `rust` job builds the sandbox helper explicitly because +`crates/eggwork-runner/tests/capability_probe.rs` drives the *built* helper and +now **fails loudly** when it cannot find it — the previous implementation +returned early and passed with zero assertions, so the skip was the normal path +in CI as well as locally. This job runs the same test target +(`cargo test --locked -p eggwork-runner --all-targets`), so the precondition has +to be accounted for. It is: the helper-dependent half of the probe is +`#[cfg(target_os = "linux")]`, so it **does not exist** in a Windows build at +all, and only the platform-neutral negative case — a missing helper must not +advertise a Landlock capability — runs here. The Linux `rust` job builds the +helper and runs the full probe. The workflow says the same thing in the step's +comment, so the reason is visible where a reader looks for it. + **Why it exists.** The Windows process-tree backend cannot be observed from Linux. Job Object ownership, descendant convergence after leader exit, and pipe inheritance across a process tree only mean something on a real Windows kernel, and a green Linux run must never be readable as Windows coverage. Foundation M004's `runner` tests are `#![cfg(windows)]`, so without this job the entire suite would silently not exist in CI. **What it deliberately does not run.** `cargo test --workspace` is not used, and test-target clippy is scoped to `eggwork-runner`. The server's and client's unit tests are Linux-shaped: they spawn `/bin/sh` and set `0700`/`0600` modes through `std::os::unix::fs`, so several test helpers do not even *compile* for Windows (`place_trusted_helper` in `crates/eggwork-server/src/lib.rs`, the `PermissionsExt` uses in `artifact.rs`, `blob.rs`, `operations.rs`, and `deployment.rs`). Making them portable is its own milestone. @@ -239,6 +259,118 @@ own bytes; a build-tree job could not prove release identity. **Cross-check against the local guard.** Before pushing, `cargo check --locked -p eggwork-runner --all-targets --target x86_64-pc-windows-msvc` compiles the Windows-only code paths on a Linux host. It catches types, imports, and lints; it does not catch kernel behaviour, which is the entire point of the hosted job. (A full `--workspace --target x86_64-pc-windows-msvc` check does not work on Linux: `cc-rs` needs MSVC's `lib.exe` for a transitive C dependency.) +## The `installed-qualification` CI job + +A third job in the same workflow, on `ubuntu-latest`, added by Operations M008b: + +```yaml + installed-qualification: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@1.89.0 + - uses: Swatinem/rust-cache@v2 + - name: build the installed product surface + run: cargo build --locked -p eggwork-server -p eggwork-sandbox-helper --bins + - name: stage the installation root + run: | + set -euo pipefail + root="${{ runner.temp }}/qualification" + mkdir -p "$root/bin" + install -m 0755 target/debug/eggworkd "$root/bin/eggworkd" + install -m 0755 target/debug/eggwork-sandbox-helper "$root/bin/eggwork-sandbox-helper" + chmod 0755 "$root" "$root/bin" + - name: check the installation root's trust chain + env: + INSTALL_ROOT: ${{ runner.temp }}/qualification + run: | + set -euo pipefail + current="$INSTALL_ROOT" + while true; do + mode=$(stat -c '%a' "$current") + world="${mode: -1}" + group="${mode: -2:1}" + if [ $(( world & 2 )) -ne 0 ] || [ $(( group & 2 )) -ne 0 ]; then + echo "$current is group/world writable (mode $mode); ..." >&2 + exit 1 + fi + parent=$(dirname "$current") + if [ "$parent" = "$current" ]; then break; fi + current="$parent" + done + - name: materialise the bounded qualification fixture + env: + EGGWORK_QUALIFY_ROOT: ${{ runner.temp }}/qualification + run: | + cargo test --locked -p eggwork-server --features qualification \ + --test installed_qualification -- --ignored --exact qualification_fixture + - name: qualify installed execution through the production client + env: + EGGWORK_QUALIFY_DAEMON: ${{ runner.temp }}/qualification/bin/eggworkd + EGGWORK_QUALIFY_CONFIG: ${{ runner.temp }}/qualification/state/node.json + EGGWORK_QUALIFY_TLS_DIR: ${{ runner.temp }}/qualification/state/tls + EGGWORK_QUALIFY_PLATFORM: linux + run: | + cargo test --locked -p eggwork-server --features qualification \ + --test installed_qualification -- --ignored --skip qualification_fixture \ + --test-threads=1 --nocapture +``` + +Three conditions in that job are load-bearing, and each was found by running it, +not by reading it: + +- **The installation root's ancestor chain must be free of group- and + world-writable bits.** The installed helper's trust check + (`eggwork_runner::verify_trusted_helper`) walks *every* ancestor of its own + path and refuses a writable one, because such a directory lets another user + replace the binary that enforces the sandbox. A staging directory created + under a umask of `002` is therefore `0775` and the node refuses its own + helper with `sandbox-resource-backend: configured sandbox helper is missing + or fails installation ownership checks`. The job creates its directories + `0755` and checks the chain explicitly, so the failure names the cause. +- **The two qualification tests must run serially.** They share one + installation root, one state directory, and one execution-state lock, so a + concurrent second daemon cannot start and the first test fails with + `the installed daemon exited before reporting ready`. `--test-threads=1` is + what makes one installation qualify one test at a time. +- **The fixture's client grant must name every operation the suite + exercises.** The declared-artifact test creates a workspace and then lists + the published artifact, so the grant needs `workspace-create` and + `artifact-read`; without them the node refuses with a bare `403 forbidden` + and the qualification reports a fixture problem as a product one. The + repository's fixture now names them. + +**Why this is a separate job and not a flag on the default test step.** The +qualification suite is `crates/eggwork-server/tests/installed_qualification.rs`, +which is `#![cfg(feature = "qualification")]` and whose three tests are +`#[ignore]`d. Adding `--all-features` to the default `cargo test` step would +therefore **not** run them: the `#[ignore]` attributes keep all three tests out +of every ordinary run regardless of the feature set. And an ordinary run has no +installed release to drive in the first place — the suite names its subject +through the environment (`EGGWORK_QUALIFY_DAEMON`, `EGGWORK_QUALIFY_CONFIG`, +`EGGWORK_QUALIFY_TLS_DIR`), and it starts the installed daemon as a child +process. So the gap is closed by **executing** the ignored tests in a job that +has the environment they need: this one stages an installation root, lets the +repository's own `rcgen`-based fixture materialise the TLS material and the +node configuration into it, and then drives the installed daemon through the +production client path. + +**What it proves, and what it does not.** It proves that the bytes this +repository builds admit an execution, report it truthfully, and refuse an +unsupported isolation request — on the build tree's own bytes. It does not +prove release identity: the hosted `operational-qualification` workflow runs +the same suite against a *published* release's exact bytes, and only that can +say anything about what a consumer would download. The installation root here +is under the runner's temporary directory for the same reason the hosted +workflow puts it there: nothing on the installed helper's path may be group- or +world-writable, and the helper's trust check refuses a tree that is. + +**Where the suite runs, in one sentence.** The default `cargo test` step does +not enable `qualification` because the suite is opt-in, ignored, and needs an +installed release; it is executed by this job on every push and pull request, +and by `operational-qualification.yml` against a published release. + ## The `release-drift` job ```yaml @@ -421,7 +553,11 @@ Both `ci.yml` and the generated release workflow install the same `1.89.0` chann ## Other guard scripts -**`scripts/check_release_tag.py` (pre-tag guard).** Takes one argument, the exact tag about to be created, e.g. `python3 scripts/check_release_tag.py v0.1.5`. It requires three things to agree: the tag (minus a leading `v`) equals the first `version = "…"` in `Cargo.toml`; every `eggwork-*` package in `Cargo.lock` is pinned at that same version; and the run is otherwise clean. Its docstring names both incidents it exists for — v0.1.3 (bump without lock regeneration, so every `--locked` release build failed closed) and v0.1.4 (bump missed entirely, so staged binaries reported `0.1.3` and hosted qualification refused them with `installed-daemon-version: daemon reports '0.1.3', expected 0.1.4`). Crucially, it is **not** a CI check, and the docstring explains why: "The tag-to-version link cannot live in CI: the generated release workflow is producer authority (the `release-drift` job rejects hand edits to it), and CI never knows the future tag. So the check lives here, run by whoever cuts the tag, before the tag exists." It defends the tag→version→lock identity, and its failure message ends with the remediation: `bump Cargo.toml, regenerate the lock, rerun the gates, then tag.` +**`scripts/check_release_tag.py` (pre-tag guard).** Takes one argument, the exact tag about to be created, e.g. `python3 scripts/check_release_tag.py v0.1.5`, or `--coherence` to run only the tag-independent half. It requires three things to agree: the tag (minus a leading `v`) equals `[workspace.package].version` in `Cargo.toml`; every package `Cargo.lock` records as built from this repository is pinned at that same version; and every workspace member is pinned in the lock at all. Its docstring names both incidents it exists for — v0.1.3 (bump without lock regeneration, so every `--locked` release build failed closed) and v0.1.4 (bump missed entirely, so staged binaries reported `0.1.3` and hosted qualification refused them with `installed-daemon-version: daemon reports '0.1.3', expected 0.1.4`). + +Two changes in Operations M008b are load-bearing rather than cosmetic. First, the guard no longer reads the manifest with a regular expression that took the *first* `version = "…"` line in the file — that was the right answer only by accident of the manifest's current layout — and it no longer parses `Cargo.lock` with regular expressions either. Both are read with real TOML readers now, because **a guard that decides whether a release may be tagged must not depend on the layout of the files it reads**. The workspace version comes from the shared reader in `release_candidate_probe.py`, which every release script uses. Second, the guard is no longer *only* a manual step: its **tag-independent** half now runs in CI on every push and every pull request (`release identity coherence` in the `rust` job), and its logic is exercised against fixtures by `tests/release/test_release_tag_guard.py`, so the code path that decides whether a release may be tagged is executed by an automated job rather than trusted. + +The **tag-dependent** half is still a human pre-tag step, and the docstring says why: "The tag-to-version link cannot live in CI: the generated release workflow is producer authority (the `release-drift` job rejects hand edits to it), and CI never knows the future tag. So the check lives here, run by whoever cuts the tag, before the tag exists." It defends the tag→version→lock identity, and its failure message ends with the remediation: `bump Cargo.toml, regenerate the lock, rerun the gates, then tag.` The upstream prerequisite that would move this half into the generated release workflow is recorded in [release-qualification.md](release-qualification.md#where-the-tag-gate-runs-today--and-where-it-does-not). **`scripts/release_candidate_probe.py` (shared bounded probe library).** Not a validator itself — the shared substrate the two Eggpack-facing validators import. Eggpack invokes each validator as `python3