diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index 1ac07ab0fe..81b4da0d8c 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -231,6 +231,7 @@ export default defineConfig({ { text: "Overview", link: "/cli/" }, { text: "fullsend agent", link: "/cli/agent" }, { text: "fullsend github", link: "/cli/github" }, + { text: "fullsend execution-plan", link: "/cli/execution-plan" }, { text: "fullsend inference", link: "/cli/inference" }, { text: "fullsend lint", link: "/cli/lint" }, { text: "fullsend mint", link: "/cli/mint" }, @@ -403,6 +404,7 @@ export default defineConfig({ { text: "Behaviour Testing", link: "/guides/dev/behaviour-testing" }, { text: "CLI Internals", link: "/guides/dev/cli-internals" }, { text: "E2E Testing", link: "/guides/dev/e2e-testing" }, + { text: "Execution Plan Drivers", link: "/guides/dev/execution-plan-driver" }, { text: "Testing Workflows", link: "/guides/dev/testing-workflows" }, { text: "Tracing Internals", link: "/guides/dev/tracing" }, ], diff --git a/docs/cli/README.md b/docs/cli/README.md index 3d36da979d..db0e643053 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -28,6 +28,7 @@ To update an installed binary later, run [`fullsend self-update`](self-update.md |---------|-------------| | [`fullsend run`](run.md) | Execute an agent locally in a sandbox. See [running agents locally](../guides/user/running-agents-locally.md). | | `fullsend poll` | Discover forge events and dispatch agent pipelines. `--forge gitlab` runs the cron poller ([ADR 0067](../ADRs/0067-gitlab-cron-polling-event-dispatch.md)); events-mode polling also recovers issue opens whose webhook delivery was missed. `--input-driver jira-poll` polls Jira (see [Jira integration](../guides/user/jira-integration.md)). It reads the Jira site, API gateway, project, and query only from the effective `tracker.jira` config (`base_url` and `project` required; the removed `--jira-url`, `--jira-project`, and `--jql` flags are rejected), authenticates with `FULLSEND_JIRA_TOKEN` (plus `FULLSEND_JIRA_EMAIL` for a bot user) or with OAuth 2.0 client credentials via `FULLSEND_JIRA_CLIENT_ID` and `FULLSEND_JIRA_CLIENT_SECRET`, and skips the cycle unless `tracker.jira.poll.enabled` is `true`; by default it writes dispatch records (`--output`) for a GitHub repository (`--target-repo`, an `owner/repo` slug; one that contains `..` is refused), and with `--target-forge gitlab` it starts the protected agent pipelines of the GitLab project named by `--project` (full path, nested groups allowed; default `CI_PROJECT_PATH`) on the https `--gitlab-url` instance, through the same signed, typed-input dispatch route and Poller credential as the GitLab poller, advancing a Jira issue's checkpoint only once its pipelines are created ([GitLab runtime](../guides/user/jira-integration.md#gitlab-runtime)). `--input-driver gitlab-webhook` is the GitLab dispatcher job's webhook fast-path ([ADR 0125](../ADRs/0125-gitlab-hybrid-webhook-poller-dispatch.md)). It reads the native webhook body from the file-type `TRIGGER_PAYLOAD` variable, re-validates it against the GitLab API, and creates each routed stage's pipeline (typed inputs, `FULLSEND_DISPATCH_SECRET` HMAC) with the poller-role credential (the `api` route, the default). Scheduled cron polling and the webhook fast path run as the trigger-only service account: once its dispatch activation is recorded, the managed webhook carries the account's pipeline trigger token ([#8509](https://github.com/fullsend-ai/fullsend/issues/8509)), the scaffold sets `FULLSEND_GITLAB_DISPATCH_ROUTE=child-pipeline`, and the command instead starts each pipeline with the job's own `CI_JOB_TOKEN` through the pipeline trigger API (`source=pipeline`); an unknown route, or `child-pipeline` without `CI_JOB_TOKEN`, fails closed. `fullsend poll --forge gitlab --print-dispatch-routes` prints the routes the CLI supports (`api` and `child-pipeline`) and exits; the scaffold runs it before selecting `child-pipeline`, and a CLI that predates the route rejects the flag, so the job stops before any dispatch. It requires `--project`, which has no `CI_PROJECT_PATH` fallback. It deduplicates against the poller's per-mode state on the `fullsend-poll-state-slash` and `fullsend-poll-state-events` branches, so an event the webhook dispatched is not dispatched again by the poller, and the reverse. Shared poller state is occurrence-aware (label additions are keyed on the resource label event ID, dispatched keys are retained for the webhook freshness window, and a failed label dispatch is handed back to the poller as a pending retry); legacy persisted keys keep working. Older pollers do not recognise the new label keys, so before a rollback or mixed-version run, follow the [ADR 0132](../ADRs/0132-occurrence-aware-shared-poller-state.md) guidance to drain in-flight poll jobs or pin every poller to one version. Both GitLab drivers dispatch the fix stage only for a changes-requested marker note authored by the registered Analyst, whose numeric user ID the scaffold exports as the job-local `FULLSEND_GITLAB_ANALYST_USER_ID`. | +| [`fullsend execution-plan`](execution-plan.md) | Reconcile an experimental immutable multi-target plan with a trusted host driver and persistent local state. | | `fullsend dispatch` | Evaluate harness CEL triggers for one forge event and print the dispatch matrix (`--output-driver gha-matrix` or `json`); used by the dispatch workflow's `Harness dispatch` job. `--route ` (`review`, `retro`, `triage` or `prioritize`) instead decides routing for that built-in agent and prints one JSON line, `{"agent":"","decision":"run\|skip\|bash","reason":"…","harness":"config:\|agents@"}` (`harness` is optional: it is omitted when the harness cannot be resolved or the decision did not need it, as for `bash`): `run` or `skip` when the repository set `agents[].trigger` on the agent's entry ([Choosing when review runs](../guides/user/customizing-agents.md#choosing-when-review-runs), [Choosing when retro runs](../guides/user/customizing-agents.md#choosing-when-retro-runs), [Choosing when triage and prioritize run](../guides/user/customizing-agents.md#choosing-when-triage-and-prioritize-run)), `bash` to leave the decision to the workflow's built-in rules. The dispatch workflow's `Route` job runs it. With `--input-driver gha-event`, a GitHub bot actor's registered fullsend role is looked up first through the mint (a layered `mint_url`, else `FULLSEND_MINT_URL`) with the job's Actions OIDC token, so the job needs `id-token: write` ([ADR 0107](../ADRs/0107-bot-identity-resolution-for-dispatch-authorization.md)); label-added events skip the lookup, and an unregistered bot or a failed lookup is denied (an empty matrix, or a `skip` decision) rather than failing the command. An absent config falls back to `FULLSEND_MINT_URL`, but a config that fails to load or parse is a failed lookup, not a fallback. | | `fullsend lock [agent-name]` | Pin remote dependencies to `lock.yaml`. If `lock.yaml` exists but cannot be parsed or declares an unsupported version, the command exits without writing and leaves the file unchanged. An entry is stale when the harness file or the `harness:` block of the agent's `agents:` entry has changed. When it composes a harness (a new or stale entry, or `--update`), it also prints the harness diagnostics, including [reserved `env.sandbox` keys](run.md#reserved-envsandbox-keys). A current entry is not composed, so its keys are not checked, and `lock` composes without event context, so keys from event-guarded overlays are reported only by `fullsend run`. A harness whose runtime fetch service can start (`allow_runtime_fetch: true`, URL-sourced skill or plugin directories, or a bare, deprecated `allowed_remote_resources` declaration) must have every harness-level `allowed_remote_resources` prefix covered by the config-level allowlist — `config.yaml`'s `allowed_remote_resources` plus the built-in default prefixes (the defaults are included when the list is omitted or non-empty; an explicit `allowed_remote_resources: []` stays deny-all and excludes them); `lock` fails naming an uncovered prefix, and fails closed when no repository config (`config.yaml` or `config.base.yaml`) exists. With a `harness:` block on the agent's entry, the prefixes checked are the ones the block sets. | | `fullsend lint` | Lint `config.yaml` and agent harness definitions — deprecations, misconfigurations, and file checks, with diagnostics for each enabled agent, or for one agent with `fullsend lint `. See [`fullsend lint`](lint.md), and [Checking a trigger before you merge](../guides/user/cel-triggers-reference.md#checking-a-trigger-before-you-merge) for a walkthrough. | diff --git a/docs/cli/execution-plan.md b/docs/cli/execution-plan.md new file mode 100644 index 0000000000..f64bb41665 --- /dev/null +++ b/docs/cli/execution-plan.md @@ -0,0 +1,102 @@ +--- +sidebar_label: execution-plan +--- + +# fullsend execution-plan + +Advance a bounded group of source-bound executions once. This experimental +command persists attempts before dispatch and reconciles existing attempts +before scheduling more work. A trusted host driver supplies authorization and +execution. Fullsend supplies plan identity, concurrency limits, retry accounting +and aggregate completion. + +```sh +fullsend execution-plan \ + --plan /srv/fullsend/plan.json \ + --state-dir /srv/fullsend/state \ + --driver /opt/fullsend/plan-driver +``` + +| Flag | Required | Meaning | +| --- | --- | --- | +| `--plan` | Yes | Reviewed immutable plan JSON, within 4 MiB | +| `--state-dir` | Yes | Private persistent directory for checkpoints and locks | +| `--driver` | Yes | Absolute path to an operator-controlled executable | +| `--driver-timeout` | No | Timeout per call; default `30s`, maximum `5m` | + +The command prints `{"complete":false,"state":{...}}` or a completed state. +A successful exit means reconciliation finished. Check `complete` to determine +whether all required executions succeeded. Authorization blockers, exhausted +attempts and outstanding work keep completion false. Errors exit nonzero; +previous checkpoints remain available for recovery. + +State and stdout contain plan inputs, domain context and execution receipts. +Keep them in restricted storage. Supply credentials through the driver's +protected environment, never through plan fields. + +## Plan input + +```json +{ + "version": 1, + "id": "advisory-123", + "request": "advisory-123", + "authorization": "reviewed-installation-grant", + "harness": "assessment", + "control_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "deadline": "2099-01-01T00:00:00Z", + "max_parallel": 2, + "max_attempts": 2, + "targets": [ + { + "id": "release-1", + "forge": "github", + "host": "github.com", + "repository": "example/project", + "ref": "refs/heads/release-1", + "sha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + } + ] +} +``` + +Replace illustrative identities and SHAs with reviewed real inputs. The +`authorization` field names a grant the driver verifies; writing a value here +cannot grant repository access. `control_sha` identifies trusted configuration +separately from the source under assessment. + +Each target has a stable ID within the plan and an exact source SHA. `forge` +accepts `github`, `gitlab` or `forgejo`; `host` distinguishes installations. +GitLab repository paths may include subgroups. `ref` is a full branch ref. +Optional `context` carries at most 64 KiB of JSON domain data. Drivers treat it +as data, with no authority to choose credentials or executable commands. + +Initial limits allow 1–256 targets, parallelism of 1–32 and 1–10 attempts per +target. These ceilings bound this experimental contract's work and state; +revisit them with measured installation needs before expanding the contract. +The deadline prevents new attempts while existing work remains reconcilable. +A failed attempt consumes its budget; an uncertain attempt consumes both an +attempt and a concurrency slot. + +A plan is immutable, including its targets, order, deadline and limits. Reusing +its ID with changed input fails. Supersession and migration of consumed budgets +are not implemented. Preserve existing state; changing IDs to bypass limits is +not a recovery procedure. + +## Storage and execution scope + +The file store uses a context-aware OS lock and atomic private checkpoints. +It supports processes sharing one persistent filesystem with working `flock` +semantics. The parent of `--state-dir` must already exist durably. Protect the directory +and all its ancestors from untrusted writes. +Separate CI machines need a shared, fenced storage adapter. Copying state files +between jobs does not provide distributed coordination. + +Native forge launch adapters, automatic source checkout and integration with +existing dispatch workflows are not included. Forge names identify targets; +they do not establish that an installed driver supports those targets. The +operator must install a driver that verifies authorization, source checkout +and trusted configuration for every enabled forge. + +See [building a plan driver](../guides/dev/execution-plan-driver.md) for the +protocol and CVE workflow migration boundary. diff --git a/docs/guides/README.md b/docs/guides/README.md index 64d06eb1ff..c660a25767 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -80,3 +80,4 @@ Guides for contributors developing and testing fullsend itself. - [Behaviour test drivers](dev/behaviour-drivers.md) — Implement SCM and CI drivers for behaviour tests - [Testing workflow changes](dev/testing-workflows.md) — Point a test repository at a branch to test workflow, action, and agent changes before release, and run the PR CI checks locally with `make ci-local` - [Tracing internals](dev/tracing.md) — How the distributed tracing implementation works and how to extend it +- [Execution plan drivers](dev/execution-plan-driver.md) — Connect the experimental multi-target coordinator to a trusted execution backend diff --git a/docs/guides/dev/cli-internals.md b/docs/guides/dev/cli-internals.md index caef00fe2e..f9333561f6 100644 --- a/docs/guides/dev/cli-internals.md +++ b/docs/guides/dev/cli-internals.md @@ -212,6 +212,11 @@ fullsend │ └── --base-url # Forge API base URL ├── post-comment # Post issue/PR comments to GitHub (deprecated) │ └── --token # GitHub token (default: $GH_TOKEN / $GITHUB_TOKEN / gh auth token) +├── execution-plan # Experimental multi-target reconciliation +│ ├── --plan # Reviewed immutable plan JSON +│ ├── --state-dir # Private persistent local checkpoints +│ ├── --driver # Trusted host executable +│ └── --driver-timeout # Per-call timeout (default 30s; maximum 5m) ├── eval-measure # Score wild-run traces (eval measurements) │ ├── --telemetry # Path to run-telemetry.jsonl (or --output-dir) │ ├── --output-dir # CI output base or runDir (managed-job form) diff --git a/docs/guides/dev/execution-plan-driver.md b/docs/guides/dev/execution-plan-driver.md new file mode 100644 index 0000000000..5b6822acdd --- /dev/null +++ b/docs/guides/dev/execution-plan-driver.md @@ -0,0 +1,103 @@ +--- +title: Build an execution plan driver +--- + +# Build an execution plan driver + +Fullsend owns a plan's durable attempts and accounting. A driver connects those +attempts to an execution backend. Domain mapping and assessment remain outside +the coordinator. See the [command reference](../../cli/execution-plan.md) for +plan fields, flags, limits and current storage restrictions. + +## Prerequisites + +- An operator-controlled executable, working directory and environment. +- A protected persistent state directory shared by all local reconcilers. +- A source-bound single-target worker and authoritative backend lookup. +- Reviewed authorization policy covering each target and requested harness. + +Keep driver code outside the source checkout being assessed. A target or model +response cannot select the driver, its credentials or trusted configuration. +Go implementations of forge operations must use `forge.Client`. + +## Implement the protocol + +1. Read exactly one JSON request from stdin. Fullsend invokes the executable + directly with no arguments or shell expansion. Each request contains + `version: 1`, `operation`, the complete `plan`, and either `target` for + authorization or `attempt` for submission and lookup. +2. Handle `authorize` by verifying the current grant, target access, harness + permission and trusted control revision. Return `{"authorized":true}` only + after those checks. Errors and missing approval hold the target with an + authorization blocker. Recheck policy inside the launch boundary when the + backend cannot atomically preserve the prior decision. +3. Handle `submit` by launching one exact attempt. Verify repository, branch + and SHA against the admitted target. Keep trusted configuration at + `plan.control_sha` separate from the assessed source. The attempt ID is the + correlation key. Record it where authoritative backend lookup can recover + an accepted launch after its acknowledgement is lost. +4. Handle `lookup` by observing that exact attempt without creating work. An + absent receipt means the outcome remains unknown. An empty search result + cannot authorize a second submission. Return a terminal receipt only when + the external run has stopped consuming execution capacity. +5. Print one JSON response to stdout, within 1 MiB. Fullsend rejects unknown + response fields and trailing JSON. Driver stderr is discarded to avoid + retaining credentials from external diagnostics. Honor process cancellation. + +For submit and lookup, the response contains an optional `receipt`: + +```json +{ + "authorized": false, + "receipt": { + "attempt_id": "the-exact-request-attempt-id", + "plan_digest": "the-exact-request-plan-digest", + "target_id": "release-1", + "source_sha": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "run_id": "authoritative-backend-run-id", + "state": "running" + } +} +``` + +Receipt states are `running`, `succeeded` and `failed`. The `authorized` field +is used only by authorization calls. For an unresolved lookup, return +`{"authorized":false}`. An accepted attempt's backend run ID cannot change. + +Fullsend persists an `uncertain` attempt before calling submit. A timeout, +process loss, invalid receipt or lost response leaves the attempt reserved. +Later reconciliation calls lookup rather than submit. A confirmed failure can +start a new numbered attempt within the original budget. A successful attempt +is retained and not rerun. Each invocation launches at most one new attempt per +target. + +## Keep findings separate from execution + +A successful run means the driver accepted a completed worker result. Domain +consumers still validate assessment evidence and interpret affected, +unaffected or inconclusive findings. Fullsend plan completion grants no coding, +publication, merge or tracker-closure authority. Drivers must not return success +merely because CI exited zero or a tracker exists. + +## Adapt a CVE workflow + +1. Resolve reviewed release mappings into targets. Put public-advisory identity, + component and evidence-bundle descriptors in domain context. Retain disclosure + and destination policy in the trusted CVE integration. +2. Translate an admitted manifest into one immutable execution plan. The + coordinator owns dispatch, attempt budgets, concurrency and completion. +3. Connect the driver to a single-target assessment harness. Validate its + source-bound assessment receipt before reporting execution success. Keep + Jira investigation creation and human coding approval in the CVE workflow. +4. Prove lost-acknowledgement recovery and branch isolation before enabling + recurring execution. Keep existing journal records and consumed budgets. + +> **Planned:** Native CI launch adapters, a shared fenced journal, and budget- +> preserving supersession remain integration work tracked with +> [#9260](https://github.com/fullsend-ai/fullsend/issues/9260). This draft +> coordinator does not migrate an existing CVE installation or its journal. + +The coordinator contract covers targets on GitHub, GitLab and Forgejo. Each +installed driver must explicitly support its selected forge and host or deny +execution. An installation that runs the controller on GitLab and assesses +GitHub source does not need to use the same forge for both roles. diff --git a/internal/cli/execution_plan.go b/internal/cli/execution_plan.go new file mode 100644 index 0000000000..a91d5ff23b --- /dev/null +++ b/internal/cli/execution_plan.go @@ -0,0 +1,70 @@ +package cli + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "time" + + "github.com/spf13/cobra" + + "github.com/fullsend-ai/fullsend/internal/executionplan" +) + +func newExecutionPlanCmd() *cobra.Command { + var planPath, stateDir, driverPath string + var timeout time.Duration + cmd := &cobra.Command{ + Use: "execution-plan", + Short: "Reconcile an experimental multi-target execution plan once", + Long: "Advance a source-bound execution plan using a trusted host driver and local durable state. Native CI adapters and distributed journal storage are not included in this experimental command.", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, _ []string) error { + file, err := os.Open(planPath) + if err != nil { + return fmt.Errorf("open execution plan: %w", err) + } + defer file.Close() //nolint:errcheck + input, err := io.ReadAll(io.LimitReader(file, (4<<20)+1)) + if err != nil || len(input) > 4<<20 { + return errors.New("execution plan must be within 4 MiB") + } + decoder := json.NewDecoder(bytes.NewReader(input)) + decoder.DisallowUnknownFields() + var plan executionplan.Plan + if err := decoder.Decode(&plan); err != nil { + return errors.New("invalid execution plan JSON") + } + var trailing any + if err := decoder.Decode(&trailing); err != io.EOF { + return errors.New("execution plan must contain exactly one JSON object within 4 MiB") + } + if err := plan.Validate(); err != nil { + return err + } + driver := &executionplan.CommandDriver{Executable: driverPath, Timeout: timeout} + if err := driver.Validate(); err != nil { + return err + } + state, err := executionplan.Reconcile(cmd.Context(), plan, &executionplan.FileStore{Dir: stateDir}, driver) + if err != nil { + return err + } + return json.NewEncoder(cmd.OutOrStdout()).Encode(struct { + Complete bool `json:"complete"` + State executionplan.State `json:"state"` + }{Complete: state.Complete(), State: state}) + }, + } + cmd.Flags().StringVar(&planPath, "plan", "", "Path to the reviewed, immutable JSON plan") + cmd.Flags().StringVar(&stateDir, "state-dir", "", "Private persistent local state directory (not a copied CI artifact)") + cmd.Flags().StringVar(&driverPath, "driver", "", "Absolute path to an operator-controlled host driver executable") + cmd.Flags().DurationVar(&timeout, "driver-timeout", 30*time.Second, "Timeout per driver call (maximum 5m)") + for _, name := range []string{"plan", "state-dir", "driver"} { + _ = cmd.MarkFlagRequired(name) + } + return cmd +} diff --git a/internal/cli/execution_plan_test.go b/internal/cli/execution_plan_test.go new file mode 100644 index 0000000000..93ed972693 --- /dev/null +++ b/internal/cli/execution_plan_test.go @@ -0,0 +1,77 @@ +package cli + +import ( + "bytes" + "encoding/json" + "github.com/fullsend-ai/fullsend/internal/executionplan" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestExecutionPlanCommandRejectsBeforeDriver(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "plan.json") + for _, input := range []string{`{}`, `{"version":1,"unknown":true}`, `{} {}`, `null`} { + require.NoError(t, os.WriteFile(path, []byte(input), 0o600)) + cmd := newExecutionPlanCmd() + cmd.SetArgs([]string{"--plan", path, "--state-dir", filepath.Join(dir, "state"), "--driver", "/nonexistent"}) + cmd.SetOut(&bytes.Buffer{}) + require.Error(t, cmd.Execute()) + _, err := os.Stat(filepath.Join(dir, "state")) + require.True(t, os.IsNotExist(err)) + } + cmd := newExecutionPlanCmd() + cmd.SetArgs([]string{"--plan", filepath.Join(dir, "missing"), "--state-dir", dir, "--driver", "/nonexistent"}) + require.Error(t, cmd.Execute()) + cmd = newExecutionPlanCmd() + cmd.SetArgs([]string{"--driver", "/nonexistent"}) + require.Error(t, cmd.Execute()) +} + +func TestExecutionPlanRegistered(t *testing.T) { + cmd, _, err := newRootCmd().Find([]string{"execution-plan"}) + require.NoError(t, err) + require.Equal(t, "execution-plan", cmd.Name()) +} + +func TestExecutionPlanCommandReportsBlockedWork(t *testing.T) { + driver, err := exec.LookPath("false") + require.NoError(t, err) + dir := t.TempDir() + path := filepath.Join(dir, "plan.json") + plan := executionplan.Plan{Version: 1, ID: "case-123", Request: "advisory-123", Authorization: "reviewed-grant", Harness: "assessment", ControlSHA: strings.Repeat("a", 40), Deadline: time.Now().Add(time.Hour), MaxParallel: 1, MaxAttempts: 1, Targets: []executionplan.Target{{ID: "release-1", Forge: "github", Host: "github.com", Repository: "example/project", Ref: "refs/heads/release-1", SHA: strings.Repeat("b", 40)}}} + input, err := json.Marshal(plan) + require.NoError(t, err) + require.NoError(t, os.WriteFile(path, input, 0o600)) + // A valid JSON prefix must not hide trailing data beyond the read limit. + oversized := append(append(append([]byte(nil), input...), bytes.Repeat([]byte(" "), (4<<20)+1-len(input))...), []byte("{}")...) + require.NoError(t, os.WriteFile(path, oversized, 0o600)) + cmd := newExecutionPlanCmd() + cmd.SetArgs([]string{"--plan", path, "--state-dir", filepath.Join(dir, "state"), "--driver", driver}) + require.Error(t, cmd.Execute()) + _, err = os.Stat(filepath.Join(dir, "state")) + require.True(t, os.IsNotExist(err)) + require.NoError(t, os.WriteFile(path, input, 0o600)) + cmd = newExecutionPlanCmd() + cmd.SetArgs([]string{"--plan", path, "--state-dir", filepath.Join(dir, "state"), "--driver", "/nonexistent"}) + require.Error(t, cmd.Execute()) + cmd = newExecutionPlanCmd() + cmd.SetArgs([]string{"--plan", path, "--state-dir", filepath.Join(dir, "state"), "--driver", driver}) + var out bytes.Buffer + cmd.SetOut(&out) + require.NoError(t, cmd.Execute()) + var report struct { + Complete bool + State executionplan.State + } + require.NoError(t, json.Unmarshal(out.Bytes(), &report)) + require.False(t, report.Complete) + require.Equal(t, "authorization", report.State.Targets[0].Blocker) + require.Empty(t, report.State.Targets[0].Attempts) +} diff --git a/internal/cli/root.go b/internal/cli/root.go index 58ee5af267..21a3bf29c3 100644 --- a/internal/cli/root.go +++ b/internal/cli/root.go @@ -85,6 +85,7 @@ func newRootCmd() *cobra.Command { cmd.AddCommand(newMintCmd()) cmd.AddCommand(newFetchSkillCmd()) cmd.AddCommand(newDispatchCmd()) + cmd.AddCommand(newExecutionPlanCmd()) cmd.AddCommand(newRunCmd()) cmd.AddCommand(newScanCmd()) cmd.AddCommand(newReposCmd()) diff --git a/internal/executionplan/command.go b/internal/executionplan/command.go new file mode 100644 index 0000000000..aefc2d8dea --- /dev/null +++ b/internal/executionplan/command.go @@ -0,0 +1,128 @@ +package executionplan + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "time" +) + +const maxDriverOutput = 1 << 20 + +// DriverRequest is sent on stdin to the operator-selected executable. It +// contains no credentials; installation credentials are inherited via environment. +type DriverRequest struct { + Version int `json:"version"` + Operation string `json:"operation"` + Plan Plan `json:"plan"` + Target *Target `json:"target,omitempty"` + Attempt *Attempt `json:"attempt,omitempty"` +} + +// DriverResponse is the driver's single JSON stdout object. An unknown Lookup +// returns an absent receipt. Authorize succeeds only with authorized=true. +type DriverResponse struct { + Authorized bool `json:"authorized"` + Receipt *Receipt `json:"receipt,omitempty"` +} + +// CommandDriver runs a trusted host adapter directly, without shell expansion. +// The executable, its environment and working directory are operator-controlled; +// never select them from a plan, target checkout, issue body or model output. +// Stderr is discarded because adapters may emit credentials in diagnostics. +type CommandDriver struct { + Executable string + Timeout time.Duration +} + +// Authorize asks the adapter to verify the plan grant and target permissions. +func (d *CommandDriver) Authorize(ctx context.Context, p Plan, t Target) error { + r, err := d.call(ctx, DriverRequest{Version: 1, Operation: "authorize", Plan: p, Target: &t}) + if err != nil { + return err + } + if !r.Authorized { + return errors.New("driver denied authorization") + } + return nil +} + +// Submit launches an exact attempt after fullsend has persisted its intent. +func (d *CommandDriver) Submit(ctx context.Context, p Plan, a Attempt) (*Receipt, error) { + r, err := d.call(ctx, DriverRequest{Version: 1, Operation: "submit", Plan: p, Attempt: &a}) + return r.Receipt, err +} + +// Lookup observes an exact attempt without creating work or retrying dispatch. +func (d *CommandDriver) Lookup(ctx context.Context, p Plan, a Attempt) (*Receipt, error) { + r, err := d.call(ctx, DriverRequest{Version: 1, Operation: "lookup", Plan: p, Attempt: &a}) + return r.Receipt, err +} + +// Validate checks operator configuration before a plan is admitted. +func (d *CommandDriver) Validate() error { + if !filepath.IsAbs(d.Executable) { + return errors.New("driver must be an absolute path to a trusted executable") + } + info, err := os.Stat(d.Executable) + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0o111 == 0 { + return errors.New("driver must be an existing executable file") + } + if d.Timeout < 0 || d.Timeout > 5*time.Minute { + return errors.New("driver timeout must be positive and at most five minutes") + } + return nil +} + +func (d *CommandDriver) call(ctx context.Context, q DriverRequest) (DriverResponse, error) { + var response DriverResponse + if err := d.Validate(); err != nil { + return response, err + } + timeout := d.Timeout + if timeout == 0 { + timeout = 30 * time.Second + } + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + input, err := json.Marshal(q) + if err != nil { + return response, err + } + cmd := exec.CommandContext(ctx, d.Executable) + cmd.Stdin = bytes.NewReader(input) + var output boundedBuffer + cmd.Stdout = &output + cmd.Stderr = io.Discard + cmd.WaitDelay = time.Second + if err := cmd.Run(); err != nil { + if ctx.Err() != nil { + return response, ctx.Err() + } + return response, errors.New("execution-plan driver failed; external outcome may be uncertain") + } + decoder := json.NewDecoder(bytes.NewReader(output.buffer.Bytes())) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&response); err != nil { + return DriverResponse{}, errors.New("invalid execution-plan driver response") + } + var extra any + if err := decoder.Decode(&extra); err != io.EOF { + return DriverResponse{}, errors.New("driver must return exactly one JSON object") + } + return response, nil +} + +type boundedBuffer struct{ buffer bytes.Buffer } + +func (b *boundedBuffer) Write(p []byte) (int, error) { + if len(p) > maxDriverOutput-b.buffer.Len() { + return 0, errors.New("driver response exceeds limit") + } + return b.buffer.Write(p) +} diff --git a/internal/executionplan/command_test.go b/internal/executionplan/command_test.go new file mode 100644 index 0000000000..d37d32500a --- /dev/null +++ b/internal/executionplan/command_test.go @@ -0,0 +1,101 @@ +package executionplan + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +// The test binary itself acts as an external driver, exercising the actual +// subprocess I/O boundary without a shell or a live forge credential. +func TestMain(m *testing.M) { + if mode := os.Getenv("FULLSEND_TEST_PLAN_DRIVER"); mode != "" { + var q DriverRequest + if err := json.NewDecoder(os.Stdin).Decode(&q); err != nil { + os.Exit(2) + } + switch mode { + case "fail": + fmt.Fprintln(os.Stderr, "sensitive driver diagnostics") + os.Exit(1) + case "hang": + time.Sleep(time.Minute) + case "large": + fmt.Print(strings.Repeat("x", maxDriverOutput+1)) + case "trailing": + fmt.Print(`{"authorized":true} {}`) + case "unknown-field": + fmt.Print(`{"authorized":true,"unexpected":1}`) + default: + r := DriverResponse{Authorized: mode != "denied"} + if q.Attempt != nil && q.Operation != "lookup" { + a := q.Attempt + r.Receipt = &Receipt{AttemptID: a.ID, PlanDigest: a.PlanDigest, TargetID: a.Target.ID, SourceSHA: a.Target.SHA, RunID: "external-run", State: Succeeded} + } + _ = json.NewEncoder(os.Stdout).Encode(r) + } + os.Exit(0) + } + os.Exit(m.Run()) +} + +func TestCommandDriverRunsSourceBoundPlan(t *testing.T) { + t.Setenv("GORACE", "atexit_sleep_ms=0") + t.Setenv("FULLSEND_TEST_PLAN_DRIVER", "success") + executable, err := os.Executable() + require.NoError(t, err) + p := examplePlan() + d := &CommandDriver{Executable: executable, Timeout: time.Second} + state, err := Reconcile(context.Background(), p, &FileStore{Dir: t.TempDir()}, d) + require.NoError(t, err) + require.True(t, state.Complete()) + receipt, err := d.Lookup(context.Background(), p, state.Targets[0].Attempts[0]) + require.NoError(t, err) + require.Nil(t, receipt) +} + +func TestCommandDriverFailsClosed(t *testing.T) { + executable, err := os.Executable() + require.NoError(t, err) + p := examplePlan() + for _, mode := range []string{"denied", "fail", "hang", "large", "trailing", "unknown-field"} { + t.Run(mode, func(t *testing.T) { + t.Setenv("GORACE", "atexit_sleep_ms=0") + t.Setenv("FULLSEND_TEST_PLAN_DRIVER", mode) + d := &CommandDriver{Executable: executable, Timeout: 100 * time.Millisecond} + err := d.Authorize(context.Background(), p, p.Targets[0]) + require.Error(t, err) + require.NotContains(t, err.Error(), "sensitive") + }) + } + d := &CommandDriver{Executable: "relative-driver"} + require.Error(t, d.Authorize(context.Background(), p, p.Targets[0])) +} + +func TestDriverOutputIsBoundedBeforeDecode(t *testing.T) { + var b boundedBuffer + n, err := b.Write([]byte(strings.Repeat(" ", maxDriverOutput))) + require.NoError(t, err) + require.Equal(t, maxDriverOutput, n) + n, err = b.Write([]byte("x")) + require.Error(t, err) + require.Zero(t, n) + require.Equal(t, maxDriverOutput, b.buffer.Len()) + d := &CommandDriver{Executable: "/nonexistent", Timeout: -time.Second} + require.Error(t, d.Authorize(context.Background(), examplePlan(), examplePlan().Targets[0])) +} + +func TestCommandDriverConfiguration(t *testing.T) { + executable, err := os.Executable() + require.NoError(t, err) + for _, d := range []*CommandDriver{{Executable: "relative"}, {Executable: "/nonexistent"}, {Executable: executable, Timeout: -time.Second}, {Executable: executable, Timeout: 6 * time.Minute}} { + require.Error(t, d.Validate()) + } + require.NoError(t, (&CommandDriver{Executable: executable}).Validate()) +} diff --git a/internal/executionplan/plan.go b/internal/executionplan/plan.go new file mode 100644 index 0000000000..c0a6af0bf3 --- /dev/null +++ b/internal/executionplan/plan.go @@ -0,0 +1,358 @@ +// Package executionplan coordinates bounded, source-bound single-target runs. +// Domain adapters supply reviewed targets; trusted drivers supply authorization +// and execution. A plan never grants permissions by naming a repository. +package executionplan + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "net/url" + "regexp" + "strings" + "time" +) + +var safeID = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$`) +var sourceSHA = regexp.MustCompile(`^(?:[a-f0-9]{40}|[a-f0-9]{64})$`) + +// ErrPlanChanged prevents reusing a plan identity with different inputs or limits. +var ErrPlanChanged = errors.New("execution plan changed: retain existing state; supersession is not implemented") + +// Target is one immutable source snapshot. Context carries domain data, not authority. +type Target struct { + ID string `json:"id"` + Forge string `json:"forge"` + Host string `json:"host"` + Repository string `json:"repository"` + Ref string `json:"ref"` + SHA string `json:"sha"` + Context json.RawMessage `json:"context,omitempty"` +} + +// Plan is an immutable request. Authorization is a reference the driver must verify +// against trusted policy; it is never a caller's assertion of their own privileges. +type Plan struct { + Version int `json:"version"` + ID string `json:"id"` + Request string `json:"request"` + Authorization string `json:"authorization"` + Harness string `json:"harness"` + ControlSHA string `json:"control_sha"` + Deadline time.Time `json:"deadline"` + MaxParallel int `json:"max_parallel"` + MaxAttempts int `json:"max_attempts"` + Targets []Target `json:"targets"` +} + +// Validate rejects incomplete and unbounded plans before any external operation. +func (p Plan) Validate() error { + if p.Version != 1 || !safeID.MatchString(p.ID) || strings.TrimSpace(p.Request) == "" || strings.TrimSpace(p.Authorization) == "" || !safeID.MatchString(p.Harness) || !sourceSHA.MatchString(p.ControlSHA) || p.Deadline.IsZero() { + return errors.New("version 1, safe plan/harness IDs, request, authorization, control SHA and deadline required") + } + // Initial safety ceilings bound state and external work in this experimental + // driver. Larger installations need an explicitly reviewed contract revision. + if len(p.Targets) == 0 || len(p.Targets) > 256 || p.MaxParallel < 1 || p.MaxParallel > 32 || p.MaxAttempts < 1 || p.MaxAttempts > 10 { + return errors.New("require 1..256 targets, parallelism 1..32 and attempts 1..10") + } + seen := map[string]bool{} + for _, t := range p.Targets { + u, err := url.Parse("https://" + t.Host) + if !safeID.MatchString(t.ID) || seen[t.ID] || !sourceSHA.MatchString(t.SHA) || err != nil || u.Hostname() == "" || u.Host != t.Host || u.User != nil || u.Path != "" || u.RawQuery != "" || u.Fragment != "" || strings.ContainsAny(t.Host, " \\\t\r\n") { + return errors.New("target requires a unique safe ID, source SHA and host") + } + if t.Forge != "github" && t.Forge != "gitlab" && t.Forge != "forgejo" { + return errors.New("unsupported source forge") + } + parts := strings.Split(t.Repository, "/") + if len(parts) < 2 { + return errors.New("repository must include owner and name") + } + for _, part := range parts { + if !safeID.MatchString(part) && !repositoryPart(part) { + return errors.New("invalid repository path") + } + } + if !strings.HasPrefix(t.Ref, "refs/heads/") || strings.TrimPrefix(t.Ref, "refs/heads/") == "" || strings.ContainsAny(t.Ref, " \t\r\n~^:?*[\\") || strings.Contains(t.Ref, "..") || strings.Contains(t.Ref, "@{") || strings.HasSuffix(t.Ref, "/") || strings.HasSuffix(t.Ref, ".") || strings.Contains(t.Ref, "//") { + return errors.New("target must name a full branch ref") + } + if len(t.Context) > 65536 || (len(t.Context) > 0 && !json.Valid(t.Context)) { + return errors.New("target context must be bounded JSON") + } + seen[t.ID] = true + } + return nil +} + +func repositoryPart(s string) bool { + if s == "" || s == "." || s == ".." || strings.HasPrefix(s, "-") { + return false + } + for _, r := range s { + if !(r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '_' || r == '-' || r == '.') { + return false + } + } + return len(s) <= 255 +} + +// Digest binds all plan fields, including target order, context and work limits. +func (p Plan) Digest() string { + b, _ := json.Marshal(p) + h := sha256.Sum256(b) + return hex.EncodeToString(h[:]) +} + +// Phase describes execution status, independently of domain findings. +type Phase string + +const ( + Uncertain Phase = "uncertain" + Running Phase = "running" + Succeeded Phase = "succeeded" + Failed Phase = "failed" +) + +// Attempt is an immutable launch request; its ID is also the reconciliation key. +type Attempt struct { + ID string `json:"id"` + PlanDigest string `json:"plan_digest"` + Target Target `json:"target"` + Number int `json:"number"` + State Phase `json:"state"` + Receipt *Receipt `json:"receipt,omitempty"` +} + +// Receipt must come from a trusted execution backend, never from model prose. +// A terminal state asserts that the external run has stopped consuming capacity. +type Receipt struct { + AttemptID string `json:"attempt_id"` + PlanDigest string `json:"plan_digest"` + TargetID string `json:"target_id"` + SourceSHA string `json:"source_sha"` + RunID string `json:"run_id"` + State Phase `json:"state"` +} + +// TargetState retains all attempts, including failures that consume the budget. +type TargetState struct { + Target Target `json:"target"` + Blocker string `json:"blocker,omitempty"` + Attempts []Attempt `json:"attempts"` +} + +// State is the complete persisted accounting for an immutable plan. +type State struct { + Version int `json:"version"` + Plan Plan `json:"plan"` + Digest string `json:"digest"` + Targets []TargetState `json:"targets"` +} + +// Complete requires successful execution for every required target. Consumers +// must separately validate assessment findings and authorize follow-up actions. +func (s State) Complete() bool { + if len(s.Targets) == 0 { + return false + } + for _, t := range s.Targets { + if len(t.Attempts) == 0 || t.Attempts[len(t.Attempts)-1].State != Succeeded { + return false + } + } + return true +} + +// Driver is installed by the operator, outside source/model-controlled inputs. +// Authorize verifies current target permissions, the authorization reference and +// trusted control revision. Submit must bind the actual checkout to Target.SHA. +// Lookup returns nil for an unknown launch; absence NEVER authorizes resubmission. +// All methods must honor cancellation. Forge adapters must use forge.Client. +type Driver interface { + Authorize(context.Context, Plan, Target) error + Submit(context.Context, Plan, Attempt) (*Receipt, error) + Lookup(context.Context, Plan, Attempt) (*Receipt, error) +} + +// Store serializes a whole reconciliation. Save must durably checkpoint the +// current state before returning. Remote implementations require fencing that +// also covers external side effects, not just an optimistic write at the end. +type Store interface { + Update(context.Context, string, func(*State, func() error) error) error +} + +// Reconcile advances a plan once. Checkpointing intent precedes Submit so crashes +// and ambiguous responses recover through Lookup instead of repeating a write. +func Reconcile(ctx context.Context, p Plan, store Store, driver Driver) (State, error) { + var result State + if err := p.Validate(); err != nil { + return result, err + } + if store == nil || driver == nil { + return result, errors.New("store and driver required") + } + err := store.Update(ctx, p.ID, func(s *State, save func() error) error { + defer func() { result = *s }() + if s.Version == 0 { + s.Version = 1 + s.Plan = p + s.Digest = p.Digest() + for _, t := range p.Targets { + s.Targets = append(s.Targets, TargetState{Target: t, Attempts: []Attempt{}}) + } + if err := save(); err != nil { + return err + } + } + if err := s.validate(); err != nil { + return err + } + if s.Digest != p.Digest() { + return ErrPlanChanged + } + // Always inspect outstanding work, even after the deadline or loss of launch + // authorization: observing existing work must not grant new execution rights. + for ti := range s.Targets { + t := &s.Targets[ti] + for ai := range t.Attempts { + a := &t.Attempts[ai] + if a.State == Succeeded || a.State == Failed { + continue + } + r, err := driver.Lookup(ctx, p, *a) + if err != nil { + return fmt.Errorf("lookup target %s: %w", t.Target.ID, err) + } + if r == nil { + continue + } + if err := accept(a, r); err != nil { + return err + } + if err := save(); err != nil { + return err + } + } + } + active := 0 + for _, t := range s.Targets { + for _, a := range t.Attempts { + if a.State == Uncertain || a.State == Running { + active++ + } + } + } + for ti := range s.Targets { + if err := ctx.Err(); err != nil { + return err + } + t := &s.Targets[ti] + t.Blocker = "" + if len(t.Attempts) > 0 && t.Attempts[len(t.Attempts)-1].State != Failed { + continue + } + if len(t.Attempts) >= p.MaxAttempts { + t.Blocker = "exhausted" + continue + } + if !time.Now().Before(p.Deadline) { + t.Blocker = "deadline" + continue + } + if active >= p.MaxParallel { + t.Blocker = "capacity" + continue + } + if err := driver.Authorize(ctx, p, t.Target); err != nil { + if ctx.Err() != nil { + return ctx.Err() + } + t.Blocker = "authorization" + continue + } + // Recheck time after potentially slow authorization. + if !time.Now().Before(p.Deadline) { + t.Blocker = "deadline" + continue + } + n := len(t.Attempts) + 1 + a := Attempt{ID: attemptID(s.Digest, t.Target.ID, n), PlanDigest: s.Digest, Target: t.Target, Number: n, State: Uncertain} + t.Attempts = append(t.Attempts, a) + if err := save(); err != nil { + return err + } + r, err := driver.Submit(ctx, p, a) + if err != nil { + return fmt.Errorf("dispatch target %s uncertain; reconcile before retry: %w", t.Target.ID, err) + } + if r == nil { + return errors.New("dispatch returned no receipt; attempt remains uncertain") + } + if err := accept(&t.Attempts[n-1], r); err != nil { + return err + } + if err := save(); err != nil { + return err + } + if r.State == Running { + active++ + } + } + return save() + }) + // Return a detached last-known snapshot even when a checkpoint or backend fails. + // Store owns the authoritative state; callers must reload before taking actions. + if reader, ok := store.(interface{ Read(string) (State, error) }); ok { + result, _ = reader.Read(p.ID) + } + return result, err +} + +func attemptID(planDigest, target string, number int) string { + h := sha256.Sum256(fmt.Appendf(nil, "%s/%s/%d", planDigest, target, number)) + return hex.EncodeToString(h[:]) +} +func accept(a *Attempt, r *Receipt) error { + if r.AttemptID != a.ID || r.PlanDigest != a.PlanDigest || r.TargetID != a.Target.ID || r.SourceSHA != a.Target.SHA || strings.TrimSpace(r.RunID) == "" || (a.Receipt != nil && r.RunID != a.Receipt.RunID) || (r.State != Running && r.State != Succeeded && r.State != Failed) { + return errors.New("execution receipt does not match admitted attempt") + } + copyReceipt := *r + a.Receipt = ©Receipt + a.State = r.State + return nil +} + +func (s State) validate() error { + if s.Version != 1 || s.Plan.Validate() != nil || s.Digest != s.Plan.Digest() || len(s.Targets) != len(s.Plan.Targets) { + return errors.New("invalid execution plan checkpoint") + } + for i, t := range s.Targets { + b, _ := json.Marshal(t.Target) + expected, _ := json.Marshal(s.Plan.Targets[i]) + if string(b) != string(expected) || len(t.Attempts) > s.Plan.MaxAttempts { + return errors.New("invalid target checkpoint") + } + for j, a := range t.Attempts { + b, _ = json.Marshal(a.Target) + if string(b) != string(expected) || a.ID != attemptID(s.Digest, t.Target.ID, j+1) || a.Number != j+1 || a.PlanDigest != s.Digest || (j < len(t.Attempts)-1 && a.State != Failed) { + return errors.New("invalid attempt checkpoint") + } + if a.State == Uncertain { + if a.Receipt != nil { + return errors.New("uncertain attempt has receipt") + } + continue + } + if a.Receipt == nil || a.State != a.Receipt.State { + return errors.New("attempt missing matching receipt") + } + if err := accept(&a, a.Receipt); err != nil { + return err + } + } + } + return nil +} diff --git a/internal/executionplan/plan_test.go b/internal/executionplan/plan_test.go new file mode 100644 index 0000000000..2f5c8e64c2 --- /dev/null +++ b/internal/executionplan/plan_test.go @@ -0,0 +1,236 @@ +package executionplan + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func examplePlan() Plan { + return Plan{Version: 1, ID: "case-123", Request: "advisory-123", Authorization: "reviewed-grant", Harness: "assessment", ControlSHA: strings.Repeat("a", 40), Deadline: time.Now().Add(time.Hour), MaxParallel: 2, MaxAttempts: 2, Targets: []Target{ + {ID: "release-1", Forge: "github", Host: "github.com", Repository: "example/project", Ref: "refs/heads/release-1", SHA: strings.Repeat("b", 40)}, + {ID: "release-2", Forge: "gitlab", Host: "gitlab.example.org", Repository: "example/project", Ref: "refs/heads/release-2", SHA: strings.Repeat("c", 40)}, + {ID: "release-3", Forge: "forgejo", Host: "forgejo.example.org", Repository: "example/project", Ref: "refs/heads/release-3", SHA: strings.Repeat("d", 40)}, + }} +} + +type testDriver struct { + denied string + receipts map[string]*Receipt + submitted []Attempt + submitErr error + lookupErr error + beforeSubmit func(Attempt) +} + +func (d *testDriver) Authorize(_ context.Context, _ Plan, target Target) error { + if target.ID == d.denied { + return errors.New("denied") + } + return nil +} +func (d *testDriver) Submit(_ context.Context, _ Plan, a Attempt) (*Receipt, error) { + if d.beforeSubmit != nil { + d.beforeSubmit(a) + } + d.submitted = append(d.submitted, a) + r := &Receipt{AttemptID: a.ID, PlanDigest: a.PlanDigest, TargetID: a.Target.ID, SourceSHA: a.Target.SHA, RunID: "run-" + a.ID, State: Running} + if d.receipts == nil { + d.receipts = map[string]*Receipt{} + } + d.receipts[a.ID] = r + if d.submitErr != nil { + return nil, d.submitErr + } + return r, nil +} +func (d *testDriver) Lookup(_ context.Context, _ Plan, a Attempt) (*Receipt, error) { + return d.receipts[a.ID], d.lookupErr +} + +func TestBoundedFanoutAndCompleteAccounting(t *testing.T) { + ctx := context.Background() + p := examplePlan() + store := &FileStore{Dir: t.TempDir()} + d := &testDriver{} + state, err := Reconcile(ctx, p, store, d) + require.NoError(t, err) + require.Len(t, d.submitted, 2) + require.False(t, state.Complete()) + require.Len(t, state.Targets, 3) + for _, r := range d.receipts { + r.State = Succeeded + } + state, err = Reconcile(ctx, p, store, d) + require.NoError(t, err) + require.Len(t, d.submitted, 3) + require.False(t, state.Complete()) + require.Equal(t, Succeeded, state.Targets[0].Attempts[0].State) + d.receipts[d.submitted[2].ID].State = Succeeded + state, err = Reconcile(ctx, p, store, d) + require.NoError(t, err) + require.True(t, state.Complete()) + require.Len(t, d.submitted, 3) +} + +func TestUnknownDispatchIsNeverBlindlyRepeated(t *testing.T) { + ctx := context.Background() + p := examplePlan() + p.MaxParallel = 1 + store := &FileStore{Dir: t.TempDir()} + d := &testDriver{submitErr: errors.New("lost acknowledgement")} + d.beforeSubmit = func(a Attempt) { + // The durable intent must exist before an external effect. + state, err := store.Read(p.ID) + require.NoError(t, err) + require.Equal(t, a.ID, state.Targets[0].Attempts[0].ID) + require.Equal(t, Uncertain, state.Targets[0].Attempts[0].State) + } + _, err := Reconcile(ctx, p, store, d) + require.Error(t, err) + d.beforeSubmit = nil + d.receipts = nil + d.submitErr = nil + state, err := Reconcile(ctx, p, store, d) + require.NoError(t, err) + require.Len(t, d.submitted, 1) + require.Equal(t, Uncertain, state.Targets[0].Attempts[0].State) + require.False(t, state.Complete()) +} + +func TestRecoveryBindsResultsAndRetainsBudgets(t *testing.T) { + ctx := context.Background() + p := examplePlan() + p.Targets = p.Targets[:1] + store := &FileStore{Dir: t.TempDir()} + d := &testDriver{} + _, err := Reconcile(ctx, p, store, d) + require.NoError(t, err) + first := d.submitted[0] + r := d.receipts[first.ID] + r.SourceSHA = strings.Repeat("e", 40) + r.State = Succeeded + _, err = Reconcile(ctx, p, store, d) + require.Error(t, err) + require.Len(t, d.submitted, 1) + r.SourceSHA = first.Target.SHA + r.State = Failed + state, err := Reconcile(ctx, p, store, d) + require.NoError(t, err) + require.Len(t, d.submitted, 2) + require.NotEqual(t, first.ID, d.submitted[1].ID) + require.Len(t, state.Targets[0].Attempts, 2) + d.receipts[d.submitted[1].ID].State = Failed + state, err = Reconcile(ctx, p, store, d) + require.NoError(t, err) + require.False(t, state.Complete()) + require.Len(t, d.submitted, 2) + require.Equal(t, "exhausted", state.Targets[0].Blocker) + changed := p + changed.Targets = append([]Target(nil), p.Targets...) + changed.Targets[0].SHA = strings.Repeat("f", 40) + _, err = Reconcile(ctx, changed, store, d) + require.ErrorIs(t, err, ErrPlanChanged) + state, err = Reconcile(ctx, p, store, d) + require.NoError(t, err) + require.Len(t, state.Targets[0].Attempts, 2) +} + +func TestAuthorizationAndDeadline(t *testing.T) { + ctx := context.Background() + p := examplePlan() + d := &testDriver{denied: "release-1"} + state, err := Reconcile(ctx, p, &FileStore{Dir: t.TempDir()}, d) + require.NoError(t, err) + require.Equal(t, "authorization", state.Targets[0].Blocker) + require.Empty(t, state.Targets[0].Attempts) + require.Len(t, d.submitted, 2) + require.False(t, state.Complete()) + p.Deadline = time.Now().Add(-time.Second) + d = &testDriver{} + state, err = Reconcile(ctx, p, &FileStore{Dir: t.TempDir()}, d) + require.NoError(t, err) + require.Empty(t, d.submitted) + require.Equal(t, "deadline", state.Targets[0].Blocker) +} + +func TestPlanValidation(t *testing.T) { + for _, test := range []struct { + name string + change func(*Plan) + }{ + {"version", func(p *Plan) { p.Version = 2 }}, + {"unsafe-id", func(p *Plan) { p.ID = "../escape" }}, + {"authorization", func(p *Plan) { p.Authorization = "" }}, + {"harness", func(p *Plan) { p.Harness = "../harness" }}, + {"control", func(p *Plan) { p.ControlSHA = "main" }}, + {"deadline", func(p *Plan) { p.Deadline = time.Time{} }}, + {"targets", func(p *Plan) { p.Targets = nil }}, + {"parallel", func(p *Plan) { p.MaxParallel = 0 }}, + {"attempts", func(p *Plan) { p.MaxAttempts = 11 }}, + {"duplicate", func(p *Plan) { p.Targets[1].ID = p.Targets[0].ID }}, + {"host", func(p *Plan) { p.Targets[0].Host = "github.com/path" }}, + {"userinfo", func(p *Plan) { p.Targets[0].Host = "user@github.com" }}, + {"forge", func(p *Plan) { p.Targets[0].Forge = "unsupported" }}, + {"repo", func(p *Plan) { p.Targets[0].Repository = "project" }}, + {"traversal", func(p *Plan) { p.Targets[0].Repository = "example/../project" }}, + {"repo-character", func(p *Plan) { p.Targets[0].Repository = "example/proj$ect" }}, + {"ref", func(p *Plan) { p.Targets[0].Ref = "release-1" }}, + {"ref-traversal", func(p *Plan) { p.Targets[0].Ref = "refs/heads/../main" }}, + {"context", func(p *Plan) { p.Targets[0].Context = []byte(`{`) }}, + } { + t.Run(test.name, func(t *testing.T) { p := examplePlan(); test.change(&p); require.Error(t, p.Validate()) }) + } + p := examplePlan() + p.Targets[0].Repository = "group/subgroup/repo.name" + require.NoError(t, p.Validate()) + for _, part := range []string{"", ".", "..", "-repo", strings.Repeat("x", 256)} { + require.False(t, repositoryPart(part)) + } +} + +func TestLateAuthorizationAndLookupFailureDoNotLaunch(t *testing.T) { + ctx := context.Background() + p := examplePlan() + s := &FileStore{Dir: t.TempDir()} + d := &testDriver{} + _, err := Reconcile(ctx, p, s, d) + require.NoError(t, err) + d.lookupErr = errors.New("backend unavailable") + _, err = Reconcile(ctx, p, s, d) + require.Error(t, err) + require.Len(t, d.submitted, 2) + cancelled, cancel := context.WithCancel(ctx) + cancel() + _, err = Reconcile(cancelled, p, s, d) + require.ErrorIs(t, err, context.Canceled) + _, err = Reconcile(ctx, p, nil, d) + require.Error(t, err) + _, err = Reconcile(ctx, p, s, nil) + require.Error(t, err) + p.Version = 2 + _, err = Reconcile(ctx, p, s, d) + require.Error(t, err) + require.False(t, (State{}).Complete()) +} + +func TestReceiptCannotChangeRunIdentity(t *testing.T) { + ctx := context.Background() + p := examplePlan() + p.Targets = p.Targets[:1] + s := &FileStore{Dir: t.TempDir()} + d := &testDriver{} + _, err := Reconcile(ctx, p, s, d) + require.NoError(t, err) + r := d.receipts[d.submitted[0].ID] + r.RunID = "different-run" + _, err = Reconcile(ctx, p, s, d) + require.Error(t, err) + state, err := s.Read(p.ID) + require.NoError(t, err) + require.Equal(t, Running, state.Targets[0].Attempts[0].State) +} diff --git a/internal/executionplan/store.go b/internal/executionplan/store.go new file mode 100644 index 0000000000..ce491c75e0 --- /dev/null +++ b/internal/executionplan/store.go @@ -0,0 +1,161 @@ +package executionplan + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "syscall" + "time" +) + +// FileStore checkpoints plans in a private operator-owned directory. Its lock +// covers backend calls, and the OS releases it after process loss. Use a shared +// filesystem with working flock semantics for multiple local processes. Separate +// CI machines need a fenced remote Store, not copies of this directory. +// Neither the directory nor its ancestors may be writable by untrusted actors. +type FileStore struct{ Dir string } + +const maxCheckpointBytes = 64 << 20 + +func (s *FileStore) path(id string) (string, error) { + if !safeID.MatchString(id) || s.Dir == "" { + return "", errors.New("state directory and safe plan ID required") + } + return filepath.Join(s.Dir, id+".json"), nil +} + +// Read loads an atomic snapshot without taking the writer lock. +func (s *FileStore) Read(id string) (State, error) { + var state State + path, err := s.path(id) + if err != nil { + return state, err + } + f, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + return state, err + } + defer f.Close() //nolint:errcheck + info, err := f.Stat() + if err != nil { + return state, err + } + if !info.Mode().IsRegular() || info.Size() > maxCheckpointBytes { + return state, errors.New("bounded regular checkpoint required") + } + decoder := json.NewDecoder(io.LimitReader(f, maxCheckpointBytes+1)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&state); err != nil { + return state, fmt.Errorf("decode checkpoint: %w", err) + } + var trailing any + if err := decoder.Decode(&trailing); err != io.EOF { + return state, errors.New("trailing checkpoint data") + } + if err := state.validate(); err != nil { + return state, err + } + return state, nil +} + +// Update holds a context-aware exclusive lock through every checkpoint and +// external operation. Save fsyncs the private temporary file and directory. +func (s *FileStore) Update(ctx context.Context, id string, fn func(*State, func() error) error) error { + path, err := s.path(id) + if err != nil { + return err + } + if err := ctx.Err(); err != nil { + return err + } + // The parent must already exist durably. Sync its directory entry even + // when another reconciler won Mkdir, before either process can dispatch. + if err := os.Mkdir(s.Dir, 0o700); err != nil && !os.IsExist(err) { + return err + } + parent, err := os.Open(filepath.Dir(filepath.Clean(s.Dir))) + if err != nil { + return err + } + syncErr := parent.Sync() + closeErr := parent.Close() + if syncErr != nil { + return syncErr + } + if closeErr != nil { + return closeErr + } + lock, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR|syscall.O_NOFOLLOW, 0o600) + if err != nil { + return err + } + defer lock.Close() //nolint:errcheck + for { + err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if err == nil { + break + } + if !errors.Is(err, syscall.EWOULDBLOCK) && !errors.Is(err, syscall.EAGAIN) { + return err + } + timer := time.NewTimer(10 * time.Millisecond) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } + defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN) //nolint:errcheck + if err := ctx.Err(); err != nil { + return err + } + state, err := s.Read(id) + if err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + return fn(&state, func() error { + if err := ctx.Err(); err != nil { + return err + } + if err := state.validate(); err != nil { + return err + } + b, err := json.MarshalIndent(state, "", " ") + if err != nil { + return err + } + if len(b) > maxCheckpointBytes { + return errors.New("checkpoint exceeds size limit") + } + temp, err := os.CreateTemp(s.Dir, ".execution-plan-*") + if err != nil { + return err + } + defer os.Remove(temp.Name()) //nolint:errcheck + if _, err := temp.Write(b); err != nil { + _ = temp.Close() + return err + } + if err := temp.Sync(); err != nil { + _ = temp.Close() + return err + } + if err := temp.Close(); err != nil { + return err + } + if err := os.Rename(temp.Name(), path); err != nil { + return err + } + dir, err := os.Open(s.Dir) + if err != nil { + return err + } + defer dir.Close() //nolint:errcheck + return dir.Sync() + }) +} diff --git a/internal/executionplan/store_test.go b/internal/executionplan/store_test.go new file mode 100644 index 0000000000..145c01342e --- /dev/null +++ b/internal/executionplan/store_test.go @@ -0,0 +1,141 @@ +package executionplan + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "github.com/stretchr/testify/require" +) + +func TestStoreSerializesAndHonorsCancellation(t *testing.T) { + s := &FileStore{Dir: t.TempDir()} + p := examplePlan() + entered := make(chan struct{}) + release := make(chan struct{}) + done := make(chan error, 1) + go func() { + done <- s.Update(context.Background(), p.ID, func(state *State, save func() error) error { + state.Version = 1 + state.Plan = p + state.Digest = p.Digest() + for _, target := range p.Targets { + state.Targets = append(state.Targets, TargetState{Target: target}) + } + close(entered) + <-release + return save() + }) + }() + <-entered + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond) + defer cancel() + err := s.Update(ctx, p.ID, func(*State, func() error) error { t.Error("overlapping writer"); return nil }) + require.ErrorIs(t, err, context.DeadlineExceeded) + close(release) + require.NoError(t, <-done) + got, err := s.Read(p.ID) + require.NoError(t, err) + require.Equal(t, p.ID, got.Plan.ID) + info, err := os.Stat(filepath.Join(s.Dir, p.ID+".json")) + require.NoError(t, err) + require.Equal(t, os.FileMode(0o600), info.Mode().Perm()) +} + +func TestStoreRejectsCorruptionAndUnsafePaths(t *testing.T) { + s := &FileStore{Dir: t.TempDir()} + ctx := context.Background() + require.Error(t, s.Update(ctx, "../escape", func(*State, func() error) error { return nil })) + require.NoError(t, os.WriteFile(filepath.Join(s.Dir, "case-123.json"), []byte(`{"version":1`), 0o600)) + require.Error(t, s.Update(ctx, "case-123", func(*State, func() error) error { t.Error("corruption overwritten"); return nil })) + require.NoError(t, os.Remove(filepath.Join(s.Dir, "case-123.json"))) + outside := filepath.Join(t.TempDir(), "outside.json") + require.NoError(t, os.WriteFile(outside, []byte("{}"), 0o600)) + require.NoError(t, os.Symlink(outside, filepath.Join(s.Dir, "case-123.json"))) + require.Error(t, s.Update(ctx, "case-123", func(*State, func() error) error { return nil })) +} + +func TestStoreRejectsInvalidWritesAndStorageFailures(t *testing.T) { + ctx := context.Background() + p := examplePlan() + s := &FileStore{Dir: t.TempDir()} + require.Error(t, s.Update(ctx, p.ID, func(state *State, save func() error) error { return save() })) + require.Error(t, s.Update(ctx, p.ID, func(state *State, save func() error) error { + state.Version = 1 + state.Plan = p + state.Digest = p.Digest() + for _, target := range p.Targets { + state.Targets = append(state.Targets, TargetState{Target: target}) + } + savedDir := s.Dir + s.Dir = filepath.Join(savedDir, "missing") + defer func() { s.Dir = savedDir }() + return save() + })) + cancelled, cancel := context.WithCancel(ctx) + require.ErrorIs(t, s.Update(cancelled, p.ID, func(state *State, save func() error) error { + cancel() + return save() + }), context.Canceled) + badDir := filepath.Join(t.TempDir(), "file") + require.NoError(t, os.WriteFile(badDir, []byte("file"), 0o600)) + require.Error(t, (&FileStore{Dir: badDir}).Update(ctx, p.ID, func(*State, func() error) error { return nil })) + lockPath := filepath.Join(s.Dir, p.ID+".json.lock") + require.NoError(t, os.Remove(lockPath)) + require.NoError(t, os.Symlink(badDir, lockPath)) + require.Error(t, s.Update(ctx, p.ID, func(*State, func() error) error { return nil })) +} + +func TestStoreRejectsTrailingAndUnknownCheckpointData(t *testing.T) { + s := &FileStore{Dir: t.TempDir()} + p := examplePlan() + for _, data := range []string{`{} {}`, `{"unknown":true}`, `{"version":3}`} { + require.NoError(t, os.WriteFile(filepath.Join(s.Dir, p.ID+".json"), []byte(data), 0o600)) + _, err := s.Read(p.ID) + require.Error(t, err) + } + require.NoError(t, os.Remove(filepath.Join(s.Dir, p.ID+".json"))) + require.NoError(t, os.Mkdir(filepath.Join(s.Dir, p.ID+".json"), 0o700)) + _, err := s.Read(p.ID) + require.Error(t, err) +} + +func TestCheckpointIntegrityBeforeRecovery(t *testing.T) { + p := examplePlan() + p.Targets = p.Targets[:1] + s := &FileStore{Dir: t.TempDir()} + _, err := Reconcile(context.Background(), p, s, &testDriver{}) + require.NoError(t, err) + baseline, err := s.Read(p.ID) + require.NoError(t, err) + encoded, err := json.Marshal(baseline) + require.NoError(t, err) + for _, test := range []struct { + name string + corrupt func(*State) + }{ + {"missing-target", func(s *State) { s.Targets = nil }}, + {"target-mismatch", func(s *State) { s.Targets[0].Target.Ref = "refs/heads/other" }}, + {"attempt-identity", func(s *State) { s.Targets[0].Attempts[0].ID = "other" }}, + {"missing-receipt", func(s *State) { s.Targets[0].Attempts[0].Receipt = nil }}, + {"uncertain-with-receipt", func(s *State) { s.Targets[0].Attempts[0].State = Uncertain }}, + {"state-mismatch", func(s *State) { s.Targets[0].Attempts[0].State = Succeeded }}, + {"receipt-binding", func(s *State) { s.Targets[0].Attempts[0].Receipt.SourceSHA = "other" }}, + } { + t.Run(test.name, func(t *testing.T) { + var broken State + require.NoError(t, json.Unmarshal(encoded, &broken)) + test.corrupt(&broken) + raw, err := json.Marshal(broken) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(s.Dir, p.ID+".json"), raw, 0o600)) + d := &testDriver{} + _, err = Reconcile(context.Background(), p, s, d) + require.Error(t, err) + require.Empty(t, d.submitted) + }) + } +}