diff --git a/README.md b/README.md index 6a124c3..5414a0d 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,8 @@ Repository commands use the checkout’s `origin` by default. Use `--remote NAME In GitHub Actions, `proofline ci review --annotations` prints unresolved findings as workflow annotations at verified cited lines. Findings without a verified head location appear on the job. The review link contains the full result. +`proofline checkpoint verify` records acceptance evidence from one exact GitHub Actions `push` run attempt at one exact commit. It reads its JSON manifest and workflow file from that commit, never from an uncommitted working-tree edit, and does not use a Proofline sign-in or API. See [Checkpoint evidence](docs/checkpoints.md) for the manifest, trust boundary, artifacts, and exit codes. + For a CodePipeline execution or Amplify job, run `proofline ci deploy --commit SHA --aws-run ID` in a later pipeline. Add `--environment-id UUID` to select its Proofline environment. The output names the AWS provider and run ID. Proofline records successful CodePipeline executions and failed, stopped or cancelled ones it ties to the ECS rollout that served the commit. A reader inside a still-running execution finds no matching deploy, waits until its timeout and exits 2. On a GitHub `workflow_run` event, an explicit `--aws-run` disables the default Actions run and attempt filters. `proofline ci deploy --until 1h` waits until Proofline has recorded the deploy checks of the job's commit through the hour check, then exits 0 when each recorded `HEALTHY` with no gap, 3 when a deploy failed or regressed, and 2 when the result is not established, including when a deploy reads a state this CLI version does not know. After a read that answered, the wait keeps reading through a read that fails in transport, times out or gets a 5xx answer, and exits 4 after five such failures in a row, naming the last error; the first read and a refusal end it at once. Without `--timeout`, a wait for `--until landing`, `--until 20m` or `--until 1h` lasts until that check is due for the selected deploys, and at least 30 minutes, so a landing check that reads the runtime again, up to 75 minutes after landing, is still read; `--until 1d` needs `--timeout`. `--environment-id` (the Proofline environment's UUID, the `environment_id` that `--json` prints for each deploy), `--environment` (the GitHub Environment name), `--task`, `--deployment` (the ID of the GitHub deployment a pipeline created), `--run` and `--attempt` select the deploy, and on a `workflow_run` event the commit, `--run` and `--attempt` default to the completed run's. When `--run` defaults to a completed run that did not succeed, the command waits at most 5 minutes for a deploy from that run, then exits 2 with a last line that names the run's conclusion and says it recorded no deploy; a deploy the run did record gets the usual wait for its check. `--json` prints the response. Each deploy prints one line per check. A deploy that rolled the environment back to an earlier commit first prints a `rollback` line with the page of the deploy it restores, when Proofline recorded one, and the pages of the deploys it rolled back. A deploy whose newest check found its service serving an earlier deploy again first prints a `rolled back` line, and stops printing it once a later check finds none; with `--json` the response carries it as `rolled_back`. Both lines can appear for one deploy. A rollback's exit code comes from its checks like any other deploy's; neither line changes it or means the rollback fixed anything. A deploy whose deploy checks ended without recording the `--until` check ends the wait at once with exit 2, and the last line names the check and the deploy's page; a check that is overdue while the checks still run keeps the wait going until the timeout. diff --git a/docs/checkpoints.example.json b/docs/checkpoints.example.json new file mode 100644 index 0000000..8461a65 --- /dev/null +++ b/docs/checkpoints.example.json @@ -0,0 +1,160 @@ +{ + "schema": "proofline.checkpoint-manifest.v1", + "task": "contact-display-name-migration", + "repository": { + "host": "github.com", + "full_name": "YOUR_USERNAME/proofline-migration-demo" + }, + "milestones": [ + { + "id": "expand", + "purpose": "Add the new field without breaking the baseline application.", + "depends_on": [], + "github": { + "workflow_path": ".github/workflows/acceptance.yml", + "event": "push" + }, + "criteria": [ + { + "id": "schema-upgrade", + "description": "The baseline database upgrades successfully.", + "required": true, + "job_name": "acceptance / schema-upgrade" + }, + { + "id": "legacy-compatibility", + "description": "The baseline application still reads and writes.", + "required": true, + "job_name": "acceptance / legacy-compatibility" + }, + { + "id": "tenant-isolation", + "description": "Tenant-scoped operations preserve other tenants' records.", + "required": true, + "job_name": "acceptance / tenant-isolation" + } + ], + "review": { + "required": false, + "accepted_source": "none" + } + }, + { + "id": "backfill", + "purpose": "Populate display_name with a resumable tenant-scoped backfill.", + "depends_on": ["expand"], + "github": { + "workflow_path": ".github/workflows/acceptance.yml", + "event": "push" + }, + "criteria": [ + { + "id": "backfill-values", + "description": "Migrated values match the expected fixture data.", + "required": true, + "job_name": "acceptance / backfill-values" + }, + { + "id": "backfill-idempotency", + "description": "Repeated execution leaves the intended state unchanged.", + "required": true, + "job_name": "acceptance / backfill-idempotency" + }, + { + "id": "backfill-resume", + "description": "Interrupted work resumes without omitting records.", + "required": true, + "job_name": "acceptance / backfill-resume" + }, + { + "id": "preserve-newer-values", + "description": "The backfill does not overwrite a newer value written during migration.", + "required": true, + "job_name": "acceptance / preserve-newer-values" + }, + { + "id": "tenant-isolation", + "description": "Tenant A's backfill does not mutate tenant B's overlapping contact IDs.", + "required": true, + "job_name": "acceptance / tenant-isolation" + } + ], + "review": { + "required": false, + "accepted_source": "none" + } + }, + { + "id": "switch", + "purpose": "Use the new field while retaining the declared external API contract.", + "depends_on": ["backfill"], + "github": { + "workflow_path": ".github/workflows/acceptance.yml", + "event": "push" + }, + "criteria": [ + { + "id": "new-reader", + "description": "The application uses the new field as intended.", + "required": true, + "job_name": "acceptance / new-reader" + }, + { + "id": "transition-fallback", + "description": "Declared transitional records are handled correctly.", + "required": true, + "job_name": "acceptance / transition-fallback" + }, + { + "id": "api-contract", + "description": "Existing clients receive the declared response contract.", + "required": true, + "job_name": "acceptance / api-contract" + }, + { + "id": "tenant-isolation", + "description": "Tenant-scoped reads and writes remain isolated.", + "required": true, + "job_name": "acceptance / tenant-isolation" + } + ], + "review": { + "required": false, + "accepted_source": "none" + } + }, + { + "id": "contract", + "purpose": "Remove old storage after legacy consumers are retired in the controlled test scenario.", + "depends_on": ["switch"], + "github": { + "workflow_path": ".github/workflows/acceptance.yml", + "event": "push" + }, + "criteria": [ + { + "id": "contract-upgrade", + "description": "The expanded and backfilled schema contracts successfully.", + "required": true, + "job_name": "acceptance / contract-upgrade" + }, + { + "id": "api-contract", + "description": "Current application behavior preserves the required API contract.", + "required": true, + "job_name": "acceptance / api-contract" + }, + { + "id": "tenant-isolation", + "description": "Tenant isolation holds after contraction.", + "required": true, + "job_name": "acceptance / tenant-isolation" + } + ], + "review": { + "required": false, + "accepted_source": "none" + } + } + ] +} diff --git a/docs/checkpoints.md b/docs/checkpoints.md new file mode 100644 index 0000000..2096800 --- /dev/null +++ b/docs/checkpoints.md @@ -0,0 +1,53 @@ +# Checkpoint evidence + +`proofline checkpoint verify` binds a milestone's declared acceptance jobs to one exact GitHub Actions workflow run attempt and commit. It reads existing metadata; it does not run project commands, dispatch or rerun workflows, fetch Git history, approve a deployment, or establish production safety. + +The command supports one `github.com` repository, a trusted `push` producer, and exact job names. Review imports and SARIF are not supported in this acceptance-only version. + +```sh +proofline checkpoint verify \ + --manifest .proofline/checkpoints.json \ + --milestone backfill \ + --repo OWNER/REPOSITORY \ + --commit FULL_SHA \ + --run RUN_ID \ + --attempt 1 \ + --prior expand=/absolute/path/to/expand/checkpoint.json \ + --out /absolute/path/to/new-checkpoint-directory +``` + +The checkout's `origin` must name the same `github.com` repository. A full SHA-1 or SHA-256 object name is required. Without `--base`, an individual commit uses its first parent. With `--base`, the CLI verifies that the exact base is a local ancestor of the selected head. The caller is responsible for preparing complete local history; the command never fetches or changes the checkout. + +The repository-relative manifest path must identify an ordinary Git blob at `--commit`. The version is `proofline.checkpoint-manifest.v1`; [checkpoints.example.json](checkpoints.example.json) shows the complete tenant-migration example. Unknown fields, duplicate IDs or job selectors, dependency cycles, unsupported events or review sources, and manifests larger than 256 KiB are refused. Version 1 supports only `"accepted_source": "none"`. A required review remains visibly incomplete because this version imports no review evidence. + +GitHub credentials are read from `GH_TOKEN`, then `GITHUB_TOKEN`. Public metadata can be read anonymously subject to GitHub's limits. The production client sends credentials only to `https://api.github.com`, refuses redirects, and reads at most ten 100-job pages. Each response is limited to 1 MiB, temporary GET failures receive at most two retries after the first request, and all collection must finish within 30 seconds. + +The CLI validates the repository numeric ID and canonical name, head repository, fork status, run ID, attempt, workflow ID and path, `push` event, exact head SHA, and each job's available run identity before evaluation. A required job passes only when its status is `completed` and conclusion is `success`. `failure` and `timed_out` establish failure; missing, skipped, neutral, cancelled, pending, and unknown results are incomplete. + +Every dependency listed by the milestone must be supplied explicitly with `--prior MILESTONE=PATH`. The prior record must have schema `proofline.checkpoint-evidence.v1`, source class `github_api`, the same task and repository, the named satisfied milestone, and a head that is a local ancestor of the current head. A dependency does not transfer its passing jobs to the current milestone. + +`--out` must not already exist. The CLI stages and atomically publishes a directory containing: + +- `checkpoint.json`, the versioned allowlisted evidence record; +- `summary.md`, a human-readable rendering; +- `SHA256SUMS`, covering the two generated files but not itself. + +`--json` additionally writes exactly the saved `checkpoint.json` to standard output; diagnostics remain on standard error. Policy failures and unavailable evidence are still saved when local inputs and the output destination are valid. Existing output is never overwritten. + +Exit codes are: + +| Exit | Meaning | +|---:|---| +| 0 | The declared acceptance policy is satisfied. | +| 1 | Invocation, manifest, identity, dependency trust, protocol, or artifact writing was rejected. | +| 2 | Required evidence is missing, pending, incomplete, or an unsupported required review is absent. | +| 3 | A required acceptance job or already evaluated dependency establishes policy failure. | +| 4 | Required GitHub evidence could not be collected within the bounded retry/deadline policy. | + +Render a saved record without GitHub or Proofline access: + +```sh +proofline checkpoint report /absolute/path/to/checkpoint.json +``` + +Reporting replays the saved evaluation and exits zero when rendering succeeds, independently of the recorded policy verdict. It states when the evidence was observed and does not claim that the remote run still exists or is unchanged. diff --git a/src/agent/config.rs b/src/agent/config.rs index 43b20c6..79d7f84 100644 --- a/src/agent/config.rs +++ b/src/agent/config.rs @@ -58,6 +58,8 @@ fn arguments(origin: &Origin) -> [String; 3] { fn executable() -> Result { std::env::current_exe() + .map_err(InstallError::Executable)? + .canonicalize() .map_err(InstallError::Executable)? .into_os_string() .into_string() diff --git a/src/agent/tests.rs b/src/agent/tests.rs index 8a67e1d..de37e1e 100644 --- a/src/agent/tests.rs +++ b/src/agent/tests.rs @@ -79,6 +79,10 @@ fn origin() -> Origin { Origin::parse("https://proofline.sh").unwrap() } +fn executable() -> PathBuf { + std::env::current_exe().unwrap().canonicalize().unwrap() +} + fn target(home: &Path, client: Client) -> PathBuf { home.join(client.relative_path()) } @@ -109,7 +113,7 @@ fn configuration(client: Client) -> Vec { fn assert_new_server(client: Client, server: &Value, selected_origin: &str) { assert_eq!( server["command"], - std::env::current_exe().unwrap().to_str().unwrap() + executable().to_str().unwrap() ); assert_eq!( server["args"], @@ -177,7 +181,7 @@ fn all_clients_preserve_private_settings_and_add_only_the_launcher() { .unwrap(); assert_eq!( server["command"].as_str(), - std::env::current_exe().unwrap().to_str() + executable().to_str() ); assert_eq!( server["args"] diff --git a/src/checkpoint.rs b/src/checkpoint.rs new file mode 100644 index 0000000..f88ba1e --- /dev/null +++ b/src/checkpoint.rs @@ -0,0 +1,469 @@ +//! Versioned, read-only checkpoint evidence for one exact GitHub Actions run +//! attempt and one immutable local Git revision. + +mod evaluate; +mod evidence; +mod github; +mod manifest; + +use std::collections::{BTreeMap, BTreeSet}; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use anyhow::{Context as _, bail}; +use clap::{Args, Subcommand}; + +use crate::Verdict; +use crate::git; +use evaluate::{DependencyStatus, Expected, PolicyStatus}; +use evidence::{ + DependencyEvidence, Evidence, RepositoryEvidence, RevisionEvidence, RunEvidence, + SourceEvidence, WorkflowEvidence, +}; + +const WORKFLOW_LIMIT: usize = 1 << 20; + +#[derive(Debug, Subcommand)] +pub(crate) enum Command { + /// Verify one milestone against one exact GitHub workflow run attempt. + Verify(VerifyArgs), + /// Render a saved checkpoint without fetching or reevaluating evidence. + Report(ReportArgs), +} + +#[derive(Debug, Args)] +pub(crate) struct VerifyArgs { + /// Repository-relative manifest path, read from --commit rather than the working tree. + #[arg(long, value_name = "PATH")] + manifest: PathBuf, + /// Milestone ID selected from the committed manifest. + #[arg(long)] + milestone: String, + /// GitHub.com repository in OWNER/NAME form. + #[arg(long)] + repo: String, + /// Exact full SHA-1 or SHA-256 commit tested by the producer run. + #[arg(long)] + commit: String, + /// Exact full ancestor SHA for an explicitly bounded range. + #[arg(long)] + base: Option, + /// GitHub Actions workflow run ID. + #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] + run: u64, + /// Positive workflow run attempt number. + #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] + attempt: u64, + /// Required prior checkpoint as MILESTONE=PATH; repeat for dependencies. + #[arg(long, value_name = "MILESTONE=PATH")] + prior: Vec, + /// New directory in which checkpoint.json, summary.md and checksums are written. + #[arg(long)] + out: PathBuf, + /// Also emit exactly the saved checkpoint JSON to standard output. + #[arg(long)] + json: bool, +} + +#[derive(Debug, Args)] +pub(crate) struct ReportArgs { + /// Saved checkpoint.json to render without network access. + checkpoint: PathBuf, +} + +#[derive(Debug, Clone)] +struct PriorArgument { + milestone: String, + path: PathBuf, +} + +impl FromStr for PriorArgument { + type Err = String; + + fn from_str(value: &str) -> Result { + let (milestone, path) = value + .split_once('=') + .filter(|(milestone, path)| !milestone.is_empty() && !path.is_empty()) + .ok_or_else(|| "write a prior checkpoint as MILESTONE=PATH".to_owned())?; + if milestone.len() > 100 + || !milestone + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + { + return Err("prior milestone has an invalid ID".to_owned()); + } + Ok(Self { + milestone: milestone.to_owned(), + path: PathBuf::from(path), + }) + } +} + +#[derive(Debug)] +struct LocalContext { + task: String, + milestone: manifest::Milestone, + repository: String, + revision: RevisionEvidence, + manifest: SourceEvidence, + workflow: SourceEvidence, + dependencies: Vec, + dependency_status: DependencyStatus, +} + +pub(crate) async fn run(command: Command) -> anyhow::Result { + match command { + Command::Verify(args) => verify(args).await, + Command::Report(args) => report(&args.checkpoint), + } +} + +async fn verify(args: VerifyArgs) -> anyhow::Result { + manifest::repository_name(&args.repo)?; + let requested_head = git::commit_sha(&args.commit)?; + let requested_base = args.base.as_deref().map(git::commit_sha).transpose()?; + let cwd = std::env::current_dir()?; + let root = git::root(&cwd).await?; + let local_repository = git::remote_repository_in(&root, "origin").await?; + if !local_repository.host.eq_ignore_ascii_case("github.com") + || !local_repository.full_name.eq_ignore_ascii_case(&args.repo) + { + bail!( + "the checkout's origin is {}/{}, not github.com/{}", + local_repository.host, + local_repository.full_name, + args.repo + ); + } + if args.manifest.is_absolute() { + bail!("--manifest must be repository-relative"); + } + let manifest_path = args + .manifest + .to_str() + .context("--manifest must be valid UTF-8")?; + let manifest_blob = + git::blob_at_commit(&root, &requested_head, manifest_path, manifest::MAX_BYTES).await?; + let manifest = manifest::Manifest::parse(&manifest_blob.bytes)?; + if !manifest + .repository + .full_name + .eq_ignore_ascii_case(&args.repo) + { + bail!( + "checkpoint manifest names repository {:?}, not {:?}", + manifest.repository.full_name, + args.repo + ); + } + let milestone = manifest.milestone(&args.milestone)?.clone(); + let workflow_blob = git::blob_at_commit( + &root, + &manifest_blob.commit, + &milestone.github.workflow_path, + WORKFLOW_LIMIT, + ) + .await?; + let revision = revision(&root, &manifest_blob.commit, requested_base.as_deref()).await?; + let (dependencies, dependency_status) = + dependencies(&root, &manifest, &milestone, &revision.head, &args.prior).await?; + let context = LocalContext { + task: manifest.task, + milestone, + repository: args.repo, + revision, + manifest: source(&manifest_blob), + workflow: source(&workflow_blob), + dependencies, + dependency_status, + }; + + let collected = github::Collector::github()? + .collect(&context.repository, args.run, args.attempt) + .await; + let (record, verdict) = match collected { + Ok(collected) => from_collected(&context, collected, args.run, args.attempt), + Err(github::CollectError::Rejected(reason)) => { + let evaluation = evaluate::without_remote( + &context.milestone, + context.dependency_status, + PolicyStatus::Rejected, + reason, + ); + ( + record(&context, None, evaluation), + Verdict::CheckpointRejected, + ) + } + Err(github::CollectError::Unavailable(reason)) => { + let policy = match context.dependency_status { + DependencyStatus::Rejected => PolicyStatus::Rejected, + DependencyStatus::Unsatisfied => PolicyStatus::Unsatisfied, + DependencyStatus::Satisfied | DependencyStatus::Missing => { + PolicyStatus::Unavailable + } + }; + let evaluation = evaluate::without_remote( + &context.milestone, + context.dependency_status, + policy, + reason, + ); + let verdict = verdict(policy); + (record(&context, None, evaluation), verdict) + } + }; + let output = evidence::persist(&args.out, &record)?; + if args.json { + record.write_stdout()?; + } + crate::say(&format!( + "checkpoint {} written to {}", + policy_name(record.evaluation.policy), + output.display() + )); + Ok(verdict) +} + +fn from_collected( + context: &LocalContext, + collected: github::Collected, + run_id: u64, + attempt: u64, +) -> (Evidence, Verdict) { + let evaluated = if context + .dependencies + .iter() + .all(|dependency| dependency.github_repository_id == collected.run.repository.id) + { + evaluate::evaluate( + &context.milestone, + &collected, + Expected { + repository: &context.repository, + head: &context.revision.head, + run_id, + attempt, + }, + context.dependency_status, + ) + } else { + Err("a dependency record names a different GitHub repository ID".to_owned()) + }; + let evaluation = match evaluated { + Ok(evaluation) => evaluation, + Err(reason) => evaluate::without_remote( + &context.milestone, + context.dependency_status, + PolicyStatus::Rejected, + reason, + ), + }; + let result = verdict(evaluation.policy); + (record(context, Some(&collected), evaluation), result) +} + +fn record( + context: &LocalContext, + collected: Option<&github::Collected>, + evaluation: evaluate::Evaluation, +) -> Evidence { + let repository = RepositoryEvidence { + host: "github.com".to_owned(), + requested_full_name: context.repository.clone(), + canonical_full_name: collected.map(|value| value.run.repository.full_name.clone()), + github_id: collected.map(|value| value.run.repository.id), + }; + let workflow = collected.map(|value| WorkflowEvidence { + id: value.workflow.id, + path: value.workflow.path.clone(), + state: value.workflow.state.clone(), + html_url: github::safe_link(value.workflow.html_url.as_deref()), + source: context.workflow.clone(), + }); + let run = collected.map(|value| RunEvidence { + id: value.run.id, + attempt: value.run.run_attempt, + event: value.run.event.clone(), + head_sha: value.run.head_sha.clone(), + status: value.run.status.clone(), + conclusion: value.run.conclusion.clone(), + html_url: github::safe_link(value.run.html_url.as_deref()), + created_at: value.run.created_at.clone(), + updated_at: value.run.updated_at.clone(), + run_started_at: value.run.run_started_at.clone(), + }); + Evidence { + schema: evidence::FORMAT.to_owned(), + cli_version: env!("CARGO_PKG_VERSION").to_owned(), + source_class: "github_api".to_owned(), + task: context.task.clone(), + milestone: context.milestone.id.clone(), + purpose: context.milestone.purpose.clone(), + repository, + revision: context.revision.clone(), + manifest: context.manifest.clone(), + workflow, + run, + dependencies: context.dependencies.clone(), + evaluation, + verification_scope: "acceptance_checks_only".to_owned(), + limitations: vec![ + "GitHub associates the run with a commit; this is not cryptographic proof of every command the workflow executed.".to_owned(), + "The CLI trusts the committed workflow's job names and test semantics and does not read logs or artifacts.".to_owned(), + "This record does not establish production rollout safety or a hosted Proofline review.".to_owned(), + "The offline report describes saved observations and does not refresh current GitHub state.".to_owned(), + ], + observed_at_unix: Evidence::now(), + } +} + +async fn revision(root: &Path, head: &str, base: Option<&str>) -> anyhow::Result { + if let Some(base) = base { + if base.eq_ignore_ascii_case(head) { + bail!("--base and --commit must name different commits"); + } + if !git::is_ancestor(root, base, head).await? { + bail!("--base {base} is not an ancestor of --commit {head}"); + } + Ok(RevisionEvidence { + head: head.to_owned(), + base: base.to_owned(), + kind: "range".to_owned(), + convention: "explicit_ancestor_to_head".to_owned(), + }) + } else { + let change = git::pushed_commit(root, head).await?; + Ok(RevisionEvidence { + head: change.head_commit_sha, + base: change.base_commit_sha, + kind: "commit".to_owned(), + convention: "first_parent".to_owned(), + }) + } +} + +async fn dependencies( + root: &Path, + manifest: &manifest::Manifest, + milestone: &manifest::Milestone, + head: &str, + supplied: &[PriorArgument], +) -> anyhow::Result<(Vec, DependencyStatus)> { + let mut priors = BTreeMap::new(); + for prior in supplied { + if priors + .insert(prior.milestone.as_str(), &prior.path) + .is_some() + { + bail!( + "--prior names milestone {:?} more than once", + prior.milestone + ); + } + } + let expected: BTreeSet<_> = milestone.depends_on.iter().map(String::as_str).collect(); + if let Some(extra) = priors.keys().find(|id| !expected.contains(**id)) { + bail!( + "--prior supplies milestone {extra:?}, which {:?} does not depend on", + milestone.id + ); + } + let mut records = Vec::new(); + let mut status = DependencyStatus::Satisfied; + for id in &milestone.depends_on { + let Some(path) = priors.get(id.as_str()) else { + status = combine(status, DependencyStatus::Missing); + continue; + }; + let Ok((prior, bytes)) = Evidence::read(path) else { + status = combine(status, DependencyStatus::Rejected); + continue; + }; + let github_repository_id = prior.repository.github_id; + let identity_matches = prior.source_class == "github_api" + && prior.task == manifest.task + && prior.milestone == *id + && prior.repository.host.eq_ignore_ascii_case("github.com") + && prior + .repository + .requested_full_name + .eq_ignore_ascii_case(&manifest.repository.full_name) + && prior + .repository + .canonical_full_name + .as_deref() + .is_some_and(|name| name.eq_ignore_ascii_case(&manifest.repository.full_name)) + && github_repository_id.is_some(); + let ancestry = git::commit_sha(&prior.revision.head) + .ok() + .is_some_and(|prior_head| prior_head != head); + let ancestry = if identity_matches && ancestry { + git::is_ancestor(root, &prior.revision.head, head).await? + } else { + false + }; + if !identity_matches || !ancestry { + status = combine(status, DependencyStatus::Rejected); + } else if prior.evaluation.policy != PolicyStatus::Satisfied { + status = combine(status, DependencyStatus::Unsatisfied); + } + if let Some(github_repository_id) = github_repository_id { + records.push(DependencyEvidence { + milestone: id.clone(), + sha256: evidence::sha256(&bytes), + head: prior.revision.head, + policy: prior.evaluation.policy, + source_class: prior.source_class, + github_repository_id, + }); + } + } + Ok((records, status)) +} + +const fn combine(current: DependencyStatus, candidate: DependencyStatus) -> DependencyStatus { + use DependencyStatus::{Missing, Rejected, Satisfied, Unsatisfied}; + match (current, candidate) { + (Rejected, _) | (_, Rejected) => Rejected, + (Unsatisfied, _) | (_, Unsatisfied) => Unsatisfied, + (Missing, _) | (_, Missing) => Missing, + (Satisfied, Satisfied) => Satisfied, + } +} + +fn source(blob: &git::CommitBlob) -> SourceEvidence { + SourceEvidence { + commit: blob.commit.clone(), + path: blob.path.clone(), + git_object: blob.object_id.clone(), + sha256: evidence::sha256(&blob.bytes), + } +} + +fn report(path: &Path) -> anyhow::Result { + let (evidence, _) = Evidence::read(path)?; + write!(std::io::stdout().lock(), "{}", evidence.summary())?; + Ok(Verdict::Done) +} + +const fn verdict(policy: PolicyStatus) -> Verdict { + match policy { + PolicyStatus::Satisfied => Verdict::Done, + PolicyStatus::Unsatisfied => Verdict::CheckpointFailed, + PolicyStatus::Incomplete => Verdict::NotComplete, + PolicyStatus::Rejected => Verdict::CheckpointRejected, + PolicyStatus::Unavailable => Verdict::Unavailable, + } +} + +const fn policy_name(policy: PolicyStatus) -> &'static str { + match policy { + PolicyStatus::Satisfied => "SATISFIED", + PolicyStatus::Unsatisfied => "UNSATISFIED", + PolicyStatus::Incomplete => "INCOMPLETE", + PolicyStatus::Rejected => "REJECTED", + PolicyStatus::Unavailable => "UNAVAILABLE", + } +} diff --git a/src/checkpoint/evaluate.rs b/src/checkpoint/evaluate.rs new file mode 100644 index 0000000..af0fa8a --- /dev/null +++ b/src/checkpoint/evaluate.rs @@ -0,0 +1,445 @@ +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +use super::github; +use super::manifest::Milestone; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub(super) enum AcceptanceStatus { + Passed, + Failed, + Incomplete, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub(super) enum CheckStatus { + Passed, + Failed, + Incomplete, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub(super) enum DependencyStatus { + Satisfied, + Missing, + Rejected, + Unsatisfied, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub(super) enum PolicyStatus { + Satisfied, + Unsatisfied, + Incomplete, + Rejected, + Unavailable, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct CriterionObservation { + pub(super) id: String, + pub(super) description: String, + pub(super) required: bool, + pub(super) job_name: String, + pub(super) status: CheckStatus, + pub(super) reason: String, + pub(super) job_id: Option, + pub(super) github_status: Option, + pub(super) github_conclusion: Option, + pub(super) job_url: Option, + pub(super) started_at: Option, + pub(super) completed_at: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct AcceptanceEvaluation { + pub(super) status: AcceptanceStatus, + pub(super) criteria: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ReviewEvaluation { + pub(super) required: bool, + pub(super) status: String, + pub(super) source: String, + pub(super) reason: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Evaluation { + pub(super) acceptance: AcceptanceEvaluation, + pub(super) review: ReviewEvaluation, + pub(super) dependency_status: DependencyStatus, + pub(super) policy: PolicyStatus, + pub(super) reasons: Vec, +} + +pub(super) struct Expected<'a> { + pub(super) repository: &'a str, + pub(super) head: &'a str, + pub(super) run_id: u64, + pub(super) attempt: u64, +} + +pub(super) fn evaluate( + milestone: &Milestone, + collected: &github::Collected, + expected: Expected<'_>, + dependency_status: DependencyStatus, +) -> Result { + validate_identity(milestone, collected, &expected)?; + let mut jobs: BTreeMap<&str, Vec<&github::Job>> = BTreeMap::new(); + for job in &collected.jobs { + jobs.entry(&job.name).or_default().push(job); + } + if let Some((name, _)) = jobs.iter().find(|(_, matches)| matches.len() > 1) { + return Err(format!( + "GitHub job name {name:?} is ambiguous in the selected workflow attempt" + )); + } + + let criteria: Vec<_> = milestone + .criteria + .iter() + .map(|criterion| { + let job = jobs + .get(criterion.job_name.as_str()) + .and_then(|matches| matches.first().copied()); + observe(criterion, job) + }) + .collect(); + let required: Vec<_> = criteria + .iter() + .filter(|criterion| criterion.required) + .collect(); + let acceptance_status = if required + .iter() + .any(|criterion| criterion.status == CheckStatus::Failed) + { + AcceptanceStatus::Failed + } else if required + .iter() + .any(|criterion| criterion.status == CheckStatus::Incomplete) + { + AcceptanceStatus::Incomplete + } else { + AcceptanceStatus::Passed + }; + let review = ReviewEvaluation { + required: milestone.review.required, + status: "ABSENT".to_owned(), + source: "none".to_owned(), + reason: if milestone.review.required { + "the milestone requires review evidence, but acceptance-only v1 imports none".to_owned() + } else { + "the milestone does not require review evidence".to_owned() + }, + }; + let mut reasons = Vec::new(); + if acceptance_status == AcceptanceStatus::Failed { + reasons.push("one or more required acceptance jobs established a failure".to_owned()); + } else if acceptance_status == AcceptanceStatus::Incomplete { + reasons.push( + "one or more required acceptance jobs were not successful and complete".to_owned(), + ); + } + match dependency_status { + DependencyStatus::Satisfied => {} + DependencyStatus::Missing => { + reasons.push("one or more required dependency records were not supplied".to_owned()); + } + DependencyStatus::Rejected => { + reasons.push("one or more dependency records failed identity validation".to_owned()); + } + DependencyStatus::Unsatisfied => { + reasons.push("one or more dependency records did not satisfy their policy".to_owned()); + } + } + if review.required { + reasons.push("required review evidence is absent".to_owned()); + } + let policy = if dependency_status == DependencyStatus::Rejected { + PolicyStatus::Rejected + } else if acceptance_status == AcceptanceStatus::Failed + || dependency_status == DependencyStatus::Unsatisfied + { + PolicyStatus::Unsatisfied + } else if acceptance_status == AcceptanceStatus::Incomplete + || dependency_status == DependencyStatus::Missing + || review.required + { + PolicyStatus::Incomplete + } else { + PolicyStatus::Satisfied + }; + Ok(Evaluation { + acceptance: AcceptanceEvaluation { + status: acceptance_status, + criteria, + }, + review, + dependency_status, + policy, + reasons, + }) +} + +pub(super) fn without_remote( + milestone: &Milestone, + dependency_status: DependencyStatus, + policy: PolicyStatus, + reason: String, +) -> Evaluation { + let criteria = milestone + .criteria + .iter() + .map(|criterion| CriterionObservation { + id: criterion.id.clone(), + description: criterion.description.clone(), + required: criterion.required, + job_name: criterion.job_name.clone(), + status: CheckStatus::Incomplete, + reason: "GitHub job evidence was not accepted for evaluation".to_owned(), + job_id: None, + github_status: None, + github_conclusion: None, + job_url: None, + started_at: None, + completed_at: None, + }) + .collect(); + Evaluation { + acceptance: AcceptanceEvaluation { + status: AcceptanceStatus::Incomplete, + criteria, + }, + review: ReviewEvaluation { + required: milestone.review.required, + status: "ABSENT".to_owned(), + source: "none".to_owned(), + reason: "review imports are outside acceptance-only v1".to_owned(), + }, + dependency_status, + policy, + reasons: vec![reason], + } +} + +fn validate_identity( + milestone: &Milestone, + collected: &github::Collected, + expected: &Expected<'_>, +) -> Result<(), String> { + let run = &collected.run; + if run.id != expected.run_id || run.run_attempt != expected.attempt { + return Err("GitHub run or attempt identity changed during collection".to_owned()); + } + if !run + .repository + .full_name + .eq_ignore_ascii_case(expected.repository) + { + return Err(format!( + "GitHub run belongs to repository {:?}, not {:?}", + run.repository.full_name, expected.repository + )); + } + let head_repository = run + .head_repository + .as_ref() + .ok_or_else(|| "GitHub run does not identify its head repository".to_owned())?; + if run.repository.fork + || head_repository.id != run.repository.id + || !head_repository + .full_name + .eq_ignore_ascii_case(&run.repository.full_name) + || head_repository.fork + { + return Err("forked GitHub producer runs are unsupported".to_owned()); + } + if run.event != "push" || run.event != milestone.github.event { + return Err(format!( + "GitHub run event {:?} is unsupported; expected push", + run.event + )); + } + if !run.head_sha.eq_ignore_ascii_case(expected.head) { + return Err(format!( + "GitHub run head {} does not match requested commit {}", + run.head_sha, expected.head + )); + } + if collected.workflow.id != run.workflow_id + || collected.workflow.path != milestone.github.workflow_path + { + return Err(format!( + "GitHub workflow {:?} does not match manifest path {:?}", + collected.workflow.path, milestone.github.workflow_path + )); + } + Ok(()) +} + +fn observe( + criterion: &super::manifest::Criterion, + job: Option<&github::Job>, +) -> CriterionObservation { + let (status, reason) = match job { + None => ( + CheckStatus::Incomplete, + "the selected workflow attempt did not contain this job".to_owned(), + ), + Some(job) if job.status == "completed" && job.conclusion.as_deref() == Some("success") => ( + CheckStatus::Passed, + "the job completed successfully".to_owned(), + ), + Some(job) + if job.status == "completed" + && matches!(job.conclusion.as_deref(), Some("failure" | "timed_out")) => + { + ( + CheckStatus::Failed, + format!( + "the job completed with conclusion {}", + job.conclusion.as_deref().unwrap_or("unknown") + ), + ) + } + Some(job) => ( + CheckStatus::Incomplete, + format!( + "the job has status {} and conclusion {}", + job.status, + job.conclusion.as_deref().unwrap_or("none") + ), + ), + }; + CriterionObservation { + id: criterion.id.clone(), + description: criterion.description.clone(), + required: criterion.required, + job_name: criterion.job_name.clone(), + status, + reason, + job_id: job.map(|job| job.id), + github_status: job.map(|job| job.status.clone()), + github_conclusion: job.and_then(|job| job.conclusion.clone()), + job_url: github::safe_link(job.and_then(|job| job.html_url.as_deref())), + started_at: job.and_then(|job| job.started_at.clone()), + completed_at: job.and_then(|job| job.completed_at.clone()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::checkpoint::manifest::{Criterion, GitHubPolicy, ReviewPolicy}; + + fn milestone(required_review: bool) -> Milestone { + Milestone { + id: "backfill".to_owned(), + purpose: "Backfill".to_owned(), + depends_on: Vec::new(), + github: GitHubPolicy { + workflow_path: ".github/workflows/check.yml".to_owned(), + event: "push".to_owned(), + }, + criteria: vec![Criterion { + id: "tests".to_owned(), + description: "Tests".to_owned(), + required: true, + job_name: "acceptance / tests".to_owned(), + }], + review: ReviewPolicy { + required: required_review, + accepted_source: "none".to_owned(), + }, + } + } + + fn collected(conclusion: Option<&str>) -> github::Collected { + let repository = github::Repository { + id: 7, + full_name: "acme/demo".to_owned(), + fork: false, + }; + github::Collected { + run: github::Run { + id: 10, + run_attempt: 1, + workflow_id: 20, + event: "push".to_owned(), + head_sha: "a".repeat(40), + status: "completed".to_owned(), + conclusion: conclusion.map(str::to_owned), + html_url: None, + repository: repository.clone(), + head_repository: Some(repository), + created_at: None, + updated_at: None, + run_started_at: None, + }, + workflow: github::Workflow { + id: 20, + path: ".github/workflows/check.yml".to_owned(), + state: "active".to_owned(), + html_url: None, + }, + jobs: vec![github::Job { + id: 30, + run_id: Some(10), + run_attempt: Some(1), + head_sha: Some("a".repeat(40)), + name: "acceptance / tests".to_owned(), + status: "completed".to_owned(), + conclusion: conclusion.map(str::to_owned), + html_url: None, + started_at: None, + completed_at: None, + }], + } + } + + fn expected() -> Expected<'static> { + Expected { + repository: "acme/demo", + head: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + run_id: 10, + attempt: 1, + } + } + + #[test] + fn known_failure_wins_over_missing_policy_dimensions() { + let evaluation = evaluate( + &milestone(true), + &collected(Some("failure")), + expected(), + DependencyStatus::Missing, + ) + .unwrap(); + assert_eq!(evaluation.acceptance.status, AcceptanceStatus::Failed); + assert_eq!(evaluation.policy, PolicyStatus::Unsatisfied); + } + + #[test] + fn successful_required_jobs_satisfy_acceptance_only_policy() { + let evaluation = evaluate( + &milestone(false), + &collected(Some("success")), + expected(), + DependencyStatus::Satisfied, + ) + .unwrap(); + assert_eq!(evaluation.policy, PolicyStatus::Satisfied); + } +} diff --git a/src/checkpoint/evidence.rs b/src/checkpoint/evidence.rs new file mode 100644 index 0000000..a940969 --- /dev/null +++ b/src/checkpoint/evidence.rs @@ -0,0 +1,363 @@ +use std::fmt::Write as _; +use std::io::Write as _; +use std::path::{Path, PathBuf}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context as _, bail}; +use serde::{Deserialize, Serialize}; +use sha2::{Digest as _, Sha256}; + +use super::evaluate::{AcceptanceStatus, Evaluation, PolicyStatus}; + +pub(super) const FORMAT: &str = "proofline.checkpoint-evidence.v1"; +const MAX_EVIDENCE_BYTES: u64 = 2 << 20; + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Evidence { + pub(super) schema: String, + pub(super) cli_version: String, + pub(super) source_class: String, + pub(super) task: String, + pub(super) milestone: String, + pub(super) purpose: String, + pub(super) repository: RepositoryEvidence, + pub(super) revision: RevisionEvidence, + pub(super) manifest: SourceEvidence, + pub(super) workflow: Option, + pub(super) run: Option, + pub(super) dependencies: Vec, + pub(super) evaluation: Evaluation, + pub(super) verification_scope: String, + pub(super) limitations: Vec, + pub(super) observed_at_unix: u64, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RepositoryEvidence { + pub(super) host: String, + pub(super) requested_full_name: String, + pub(super) canonical_full_name: Option, + pub(super) github_id: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RevisionEvidence { + pub(super) head: String, + pub(super) base: String, + pub(super) kind: String, + pub(super) convention: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct SourceEvidence { + pub(super) commit: String, + pub(super) path: String, + pub(super) git_object: String, + pub(super) sha256: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct WorkflowEvidence { + pub(super) id: u64, + pub(super) path: String, + pub(super) state: String, + pub(super) html_url: Option, + pub(super) source: SourceEvidence, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct RunEvidence { + pub(super) id: u64, + pub(super) attempt: u64, + pub(super) event: String, + pub(super) head_sha: String, + pub(super) status: String, + pub(super) conclusion: Option, + pub(super) html_url: Option, + pub(super) created_at: Option, + pub(super) updated_at: Option, + pub(super) run_started_at: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct DependencyEvidence { + pub(super) milestone: String, + pub(super) sha256: String, + pub(super) head: String, + pub(super) policy: PolicyStatus, + pub(super) source_class: String, + pub(super) github_repository_id: u64, +} + +impl Evidence { + pub(super) fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_secs() + } + + pub(super) fn read(path: &Path) -> anyhow::Result<(Self, Vec)> { + let metadata = std::fs::metadata(path) + .with_context(|| format!("could not read checkpoint evidence {}", path.display()))?; + if !metadata.is_file() || metadata.len() > MAX_EVIDENCE_BYTES { + bail!( + "checkpoint evidence {} is not an ordinary file of at most {MAX_EVIDENCE_BYTES} bytes", + path.display() + ); + } + let bytes = std::fs::read(path) + .with_context(|| format!("could not read checkpoint evidence {}", path.display()))?; + let evidence: Self = + serde_json::from_slice(&bytes).context("invalid checkpoint evidence")?; + if evidence.schema != FORMAT { + bail!( + "unsupported checkpoint evidence schema {:?}", + evidence.schema + ); + } + Ok((evidence, bytes)) + } + + pub(super) fn json(&self) -> anyhow::Result> { + let mut bytes = serde_json::to_vec_pretty(self)?; + bytes.push(b'\n'); + Ok(bytes) + } + + pub(super) fn summary(&self) -> String { + let mut output = String::new(); + output.push_str("# Proofline checkpoint\n\n"); + field(&mut output, "Task", &self.task); + field(&mut output, "Milestone", &self.milestone); + field( + &mut output, + "Repository", + self.repository + .canonical_full_name + .as_deref() + .unwrap_or(&self.repository.requested_full_name), + ); + field(&mut output, "Head", &self.revision.head); + field(&mut output, "Policy", policy(self.evaluation.policy)); + field( + &mut output, + "Acceptance", + acceptance(self.evaluation.acceptance.status), + ); + field(&mut output, "Observed", &self.observed_at_unix.to_string()); + output.push_str("\n## Acceptance criteria\n\n"); + output.push_str("| Criterion | Required | Result | GitHub job |\n"); + output.push_str("|---|---:|---|---|\n"); + for criterion in &self.evaluation.acceptance.criteria { + writeln!( + output, + "| {} | {} | {:?} | {} |", + markdown(&criterion.id), + if criterion.required { "yes" } else { "no" }, + criterion.status, + markdown(&criterion.job_name) + ) + .expect("writing to a String cannot fail"); + } + if !self.evaluation.reasons.is_empty() { + output.push_str("\n## Result details\n\n"); + for reason in &self.evaluation.reasons { + output.push_str("- "); + output.push_str(&markdown(reason)); + output.push('\n'); + } + } + output.push_str("\n## Trust scope and limitations\n\n"); + output.push_str("Verification scope: `acceptance_checks_only`.\n\n"); + for limitation in &self.limitations { + output.push_str("- "); + output.push_str(&markdown(limitation)); + output.push('\n'); + } + output + } + + pub(super) fn write_stdout(&self) -> anyhow::Result<()> { + std::io::stdout().lock().write_all(&self.json()?)?; + Ok(()) + } +} + +pub(super) fn persist(out: &Path, evidence: &Evidence) -> anyhow::Result { + let out = if out.is_absolute() { + out.to_owned() + } else { + std::env::current_dir()?.join(out) + }; + if out.exists() { + bail!( + "checkpoint output directory already exists: {}", + out.display() + ); + } + let parent = out + .parent() + .context("checkpoint output directory has no parent")?; + if !parent.is_dir() { + bail!( + "checkpoint output parent does not exist: {}", + parent.display() + ); + } + let stage = tempfile::Builder::new() + .prefix(".proofline-checkpoint-") + .tempdir_in(parent)?; + let checkpoint = evidence.json()?; + let summary = evidence.summary().into_bytes(); + std::fs::write(stage.path().join("checkpoint.json"), &checkpoint)?; + std::fs::write(stage.path().join("summary.md"), &summary)?; + let checksums = format!( + "{} checkpoint.json\n{} summary.md\n", + sha256(&checkpoint), + sha256(&summary) + ); + std::fs::write(stage.path().join("SHA256SUMS"), checksums)?; + std::fs::rename(stage.path(), &out).with_context(|| { + format!( + "could not atomically publish checkpoint output {}", + out.display() + ) + })?; + Ok(out) +} + +pub(super) fn sha256(bytes: &[u8]) -> String { + let digest = Sha256::digest(bytes); + digest.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn field(output: &mut String, name: &str, value: &str) { + output.push_str("**"); + output.push_str(name); + output.push_str(":** `"); + output.push_str(&markdown(value)); + output.push_str("` \n"); +} + +fn markdown(value: &str) -> String { + crate::text::one_line(value) + .replace('\\', "\\\\") + .replace('`', "\\`") + .replace('|', "\\|") +} + +const fn policy(status: PolicyStatus) -> &'static str { + match status { + PolicyStatus::Satisfied => "SATISFIED", + PolicyStatus::Unsatisfied => "UNSATISFIED", + PolicyStatus::Incomplete => "INCOMPLETE", + PolicyStatus::Rejected => "REJECTED", + PolicyStatus::Unavailable => "UNAVAILABLE", + } +} + +const fn acceptance(status: AcceptanceStatus) -> &'static str { + match status { + AcceptanceStatus::Passed => "PASSED", + AcceptanceStatus::Failed => "FAILED", + AcceptanceStatus::Incomplete => "INCOMPLETE", + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::checkpoint::evaluate::{ + AcceptanceEvaluation, CheckStatus, CriterionObservation, DependencyStatus, ReviewEvaluation, + }; + + fn sample() -> Evidence { + Evidence { + schema: FORMAT.to_owned(), + cli_version: "test".to_owned(), + source_class: "github_api".to_owned(), + task: "task".to_owned(), + milestone: "expand".to_owned(), + purpose: "purpose".to_owned(), + repository: RepositoryEvidence { + host: "github.com".to_owned(), + requested_full_name: "acme/demo".to_owned(), + canonical_full_name: Some("acme/demo".to_owned()), + github_id: Some(1), + }, + revision: RevisionEvidence { + head: "a".repeat(40), + base: "b".repeat(40), + kind: "commit".to_owned(), + convention: "first_parent".to_owned(), + }, + manifest: SourceEvidence { + commit: "a".repeat(40), + path: ".proofline/checkpoints.json".to_owned(), + git_object: "c".repeat(40), + sha256: "d".repeat(64), + }, + workflow: None, + run: None, + dependencies: Vec::new(), + evaluation: Evaluation { + acceptance: AcceptanceEvaluation { + status: AcceptanceStatus::Incomplete, + criteria: vec![CriterionObservation { + id: "unsafe|id".to_owned(), + description: "description".to_owned(), + required: true, + job_name: "job\u{1b}[2J".to_owned(), + status: CheckStatus::Incomplete, + reason: "missing".to_owned(), + job_id: None, + github_status: None, + github_conclusion: None, + job_url: None, + started_at: None, + completed_at: None, + }], + }, + review: ReviewEvaluation { + required: false, + status: "ABSENT".to_owned(), + source: "none".to_owned(), + reason: "optional".to_owned(), + }, + dependency_status: DependencyStatus::Satisfied, + policy: PolicyStatus::Incomplete, + reasons: vec!["missing".to_owned()], + }, + verification_scope: "acceptance_checks_only".to_owned(), + limitations: vec!["limited".to_owned()], + observed_at_unix: 1, + } + } + + #[test] + fn summary_escapes_markdown_and_terminal_controls() { + let summary = sample().summary(); + assert!(summary.contains("unsafe\\|id"), "{summary}"); + assert!(!summary.contains('\u{1b}'), "{summary:?}"); + } + + #[test] + fn persistence_refuses_overwrite_and_checks_generated_files() { + let directory = tempfile::tempdir().unwrap(); + let out = directory.path().join("checkpoint"); + persist(&out, &sample()).unwrap(); + assert!(out.join("checkpoint.json").is_file()); + let sums = std::fs::read_to_string(out.join("SHA256SUMS")).unwrap(); + assert!(sums.contains("checkpoint.json")); + assert!(!sums.contains("SHA256SUMS SHA256SUMS")); + assert!(persist(&out, &sample()).is_err()); + } +} diff --git a/src/checkpoint/github.rs b/src/checkpoint/github.rs new file mode 100644 index 0000000..bb8c071 --- /dev/null +++ b/src/checkpoint/github.rs @@ -0,0 +1,464 @@ +use std::collections::BTreeSet; +use std::time::Duration; + +use reqwest::StatusCode; +use secrecy::{ExposeSecret as _, SecretString}; +use serde::de::DeserializeOwned; +use serde::{Deserialize, Serialize}; +use url::Url; + +const API: &str = "https://api.github.com/"; +const RESPONSE_LIMIT: usize = 1 << 20; +const PAGE_SIZE: usize = 100; +const PAGE_LIMIT: usize = 10; +const COLLECTION_DEADLINE: Duration = Duration::from_secs(30); +const ATTEMPTS: usize = 3; + +#[derive(Debug, thiserror::Error)] +pub(super) enum CollectError { + #[error("{0}")] + Rejected(String), + #[error("{0}")] + Unavailable(String), +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub(super) struct Repository { + pub(super) id: u64, + pub(super) full_name: String, + #[serde(default)] + pub(super) fork: bool, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub(super) struct Run { + pub(super) id: u64, + pub(super) run_attempt: u64, + pub(super) workflow_id: u64, + pub(super) event: String, + pub(super) head_sha: String, + pub(super) status: String, + pub(super) conclusion: Option, + pub(super) html_url: Option, + pub(super) repository: Repository, + pub(super) head_repository: Option, + pub(super) created_at: Option, + pub(super) updated_at: Option, + pub(super) run_started_at: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub(super) struct Workflow { + pub(super) id: u64, + pub(super) path: String, + pub(super) state: String, + pub(super) html_url: Option, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub(super) struct Job { + pub(super) id: u64, + pub(super) run_id: Option, + pub(super) run_attempt: Option, + pub(super) head_sha: Option, + pub(super) name: String, + pub(super) status: String, + pub(super) conclusion: Option, + pub(super) html_url: Option, + pub(super) started_at: Option, + pub(super) completed_at: Option, +} + +#[derive(Debug, Clone)] +pub(super) struct Collected { + pub(super) run: Run, + pub(super) workflow: Workflow, + pub(super) jobs: Vec, +} + +#[derive(Debug, Deserialize)] +struct JobsPage { + total_count: usize, + jobs: Vec, +} + +#[derive(Debug)] +pub(super) struct Collector { + client: reqwest::Client, + origin: Url, + token: Option, +} + +impl Collector { + pub(super) fn github() -> anyhow::Result { + let token = std::env::var("GH_TOKEN") + .ok() + .filter(|value| !value.trim().is_empty()) + .or_else(|| { + std::env::var("GITHUB_TOKEN") + .ok() + .filter(|value| !value.trim().is_empty()) + }) + .map(SecretString::from); + Self::new(Url::parse(API)?, token) + } + + fn new(origin: Url, token: Option) -> anyhow::Result { + let client = crate::api::client_builder() + .connect_timeout(Duration::from_secs(10)) + .redirect(reqwest::redirect::Policy::none()) + .user_agent(concat!("proofline-checkpoint/", env!("CARGO_PKG_VERSION"))) + .build()?; + Ok(Self { + client, + origin, + token, + }) + } + + pub(super) async fn collect( + &self, + repository: &str, + run_id: u64, + attempt: u64, + ) -> Result { + tokio::time::timeout( + COLLECTION_DEADLINE, + self.collect_within_deadline(repository, run_id, attempt), + ) + .await + .unwrap_or_else(|_| { + Err(CollectError::Unavailable( + "GitHub evidence collection exceeded 30 seconds".to_owned(), + )) + }) + } + + async fn collect_within_deadline( + &self, + repository: &str, + run_id: u64, + attempt: u64, + ) -> Result { + let run: Run = self + .get(self.url(&[ + "repos", + repository.split('/').next().unwrap_or_default(), + repository.split('/').nth(1).unwrap_or_default(), + "actions", + "runs", + &run_id.to_string(), + "attempts", + &attempt.to_string(), + ])?) + .await?; + if run.id != run_id || run.run_attempt != attempt { + return Err(CollectError::Rejected(format!( + "GitHub returned run {} attempt {} for requested run {run_id} attempt {attempt}", + run.id, run.run_attempt + ))); + } + let workflow: Workflow = self + .get(self.url(&[ + "repos", + repository.split('/').next().unwrap_or_default(), + repository.split('/').nth(1).unwrap_or_default(), + "actions", + "workflows", + &run.workflow_id.to_string(), + ])?) + .await?; + if workflow.id != run.workflow_id { + return Err(CollectError::Rejected(format!( + "GitHub returned workflow {} for run workflow {}", + workflow.id, run.workflow_id + ))); + } + + let mut jobs = Vec::new(); + let mut job_ids = BTreeSet::new(); + let mut expected_total = None; + for page in 1..=PAGE_LIMIT { + let mut url = self.url(&[ + "repos", + repository.split('/').next().unwrap_or_default(), + repository.split('/').nth(1).unwrap_or_default(), + "actions", + "runs", + &run_id.to_string(), + "attempts", + &attempt.to_string(), + "jobs", + ])?; + url.query_pairs_mut() + .append_pair("per_page", &PAGE_SIZE.to_string()) + .append_pair("page", &page.to_string()); + let response: JobsPage = self.get(url).await?; + if let Some(total) = expected_total { + if total != response.total_count { + return Err(CollectError::Unavailable( + "GitHub changed the job count during pagination".to_owned(), + )); + } + } else { + expected_total = Some(response.total_count); + } + let count = response.jobs.len(); + for job in response.jobs { + if !job_ids.insert(job.id) { + return Err(CollectError::Rejected(format!( + "GitHub returned job {} more than once", + job.id + ))); + } + if job.run_id.is_some_and(|id| id != run_id) + || job.run_attempt.is_some_and(|value| value != attempt) + || job + .head_sha + .as_deref() + .is_some_and(|sha| !sha.eq_ignore_ascii_case(&run.head_sha)) + { + return Err(CollectError::Rejected(format!( + "GitHub job {} does not belong to the selected run identity", + job.id + ))); + } + jobs.push(job); + } + let total = expected_total.unwrap_or_default(); + if jobs.len() >= total { + if jobs.len() != total { + return Err(CollectError::Rejected( + "GitHub returned more jobs than its declared total".to_owned(), + )); + } + break; + } + if count < PAGE_SIZE { + return Err(CollectError::Unavailable( + "GitHub ended job pagination before the declared total".to_owned(), + )); + } + } + if jobs.len() != expected_total.unwrap_or_default() { + return Err(CollectError::Unavailable(format!( + "GitHub job pagination exceeded the {PAGE_LIMIT}-page limit" + ))); + } + Ok(Collected { + run, + workflow, + jobs, + }) + } + + fn url(&self, segments: &[&str]) -> Result { + let mut url = self.origin.clone(); + let mut path = url.path_segments_mut().map_err(|()| { + CollectError::Rejected("GitHub API origin cannot contain path segments".to_owned()) + })?; + path.clear(); + path.extend(segments); + drop(path); + Ok(url) + } + + async fn get(&self, url: Url) -> Result { + for request_attempt in 0..ATTEMPTS { + let mut request = self + .client + .get(url.clone()) + .header("Accept", "application/vnd.github+json") + .header("X-GitHub-Api-Version", "2022-11-28"); + if let Some(token) = &self.token { + request = request.bearer_auth(token.expose_secret()); + } + let response = match request.send().await { + Ok(response) => response, + Err(error) if request_attempt + 1 < ATTEMPTS => { + retry_delay(request_attempt, None).await; + if error.is_builder() { + return Err(CollectError::Rejected( + "GitHub request could not be constructed".to_owned(), + )); + } + continue; + } + Err(error) => { + return Err(CollectError::Unavailable(if error.is_timeout() { + "GitHub request timed out".to_owned() + } else { + "GitHub could not be reached".to_owned() + })); + } + }; + let status = response.status(); + if status.is_success() { + let bytes = bounded_body(response).await?; + return serde_json::from_slice(&bytes).map_err(|_| { + CollectError::Rejected("GitHub returned malformed metadata".to_owned()) + }); + } + let rate_limited = status == StatusCode::TOO_MANY_REQUESTS + || status == StatusCode::FORBIDDEN + && (response.headers().get("retry-after").is_some() + || response + .headers() + .get("x-ratelimit-remaining") + .is_some_and(|value| value == "0")); + let temporary = rate_limited || status.is_server_error(); + if temporary && request_attempt + 1 < ATTEMPTS { + let retry_after = response + .headers() + .get("retry-after") + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()); + retry_delay(request_attempt, retry_after).await; + continue; + } + if temporary { + return Err(CollectError::Unavailable(if rate_limited { + "GitHub rate limited evidence collection".to_owned() + } else { + format!("GitHub evidence service returned HTTP {status}") + })); + } + return Err(CollectError::Rejected(match status { + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => { + "GitHub refused the evidence credential".to_owned() + } + StatusCode::NOT_FOUND => { + "GitHub could not find the selected repository, run, attempt or workflow" + .to_owned() + } + _ => format!("GitHub refused evidence collection with HTTP {status}"), + })); + } + Err(CollectError::Unavailable( + "GitHub evidence collection exhausted its retry budget".to_owned(), + )) + } +} + +async fn bounded_body(mut response: reqwest::Response) -> Result, CollectError> { + if response + .content_length() + .is_some_and(|length| length > RESPONSE_LIMIT as u64) + { + return Err(CollectError::Rejected( + "GitHub metadata response exceeded 1 MiB".to_owned(), + )); + } + let mut body = Vec::new(); + while let Some(chunk) = response.chunk().await.map_err(|error| { + CollectError::Unavailable(if error.is_timeout() { + "GitHub metadata body timed out".to_owned() + } else { + "GitHub metadata body could not be read".to_owned() + }) + })? { + if body.len().saturating_add(chunk.len()) > RESPONSE_LIMIT { + return Err(CollectError::Rejected( + "GitHub metadata response exceeded 1 MiB".to_owned(), + )); + } + body.extend_from_slice(&chunk); + } + Ok(body) +} + +async fn retry_delay(attempt: usize, retry_after: Option) { + let fallback = 200_u64.saturating_mul(1_u64 << attempt); + let milliseconds = retry_after + .map_or(fallback, |seconds| seconds.saturating_mul(1_000)) + .min(2_000); + tokio::time::sleep(Duration::from_millis(milliseconds)).await; +} + +pub(super) fn safe_link(value: Option<&str>) -> Option { + let url = Url::parse(value?).ok()?; + (url.scheme() == "https" && url.host_str() == Some("github.com")).then(|| url.to_string()) +} + +#[cfg(test)] +impl Collector { + pub(super) fn test(origin: Url) -> anyhow::Result { + Self::new(origin, None) + } +} + +#[cfg(test)] +mod tests { + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + + use super::*; + + #[tokio::test] + async fn attempt_specific_collection_keeps_run_workflow_and_job_identity() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + for _ in 0..3 { + let (mut stream, _) = listener.accept().await.unwrap(); + let mut request = vec![0_u8; 8_192]; + let read = stream.read(&mut request).await.unwrap(); + let request = String::from_utf8_lossy(&request[..read]); + let first = request.lines().next().unwrap_or_default(); + let body = if first.contains("/jobs?") { + serde_json::json!({ + "total_count": 1, + "jobs": [{ + "id": 30, + "run_id": 10, + "run_attempt": 2, + "head_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "name": "acceptance / tests", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/acme/demo/actions/runs/10/job/30", + "started_at": "2026-11-30T00:00:00Z", + "completed_at": "2026-11-30T00:01:00Z" + }] + }) + } else if first.contains("/workflows/") { + serde_json::json!({ + "id": 20, + "path": ".github/workflows/check.yml", + "state": "active", + "html_url": "https://github.com/acme/demo/actions/workflows/check.yml" + }) + } else { + serde_json::json!({ + "id": 10, + "run_attempt": 2, + "workflow_id": 20, + "event": "push", + "head_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "status": "completed", + "conclusion": "success", + "html_url": "https://github.com/acme/demo/actions/runs/10", + "repository": {"id": 7, "full_name": "acme/demo", "fork": false}, + "head_repository": {"id": 7, "full_name": "acme/demo", "fork": false}, + "created_at": "2026-11-30T00:00:00Z", + "updated_at": "2026-11-30T00:01:00Z", + "run_started_at": "2026-11-30T00:00:00Z" + }) + }; + let body = serde_json::to_vec(&body).unwrap(); + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + body.len() + ); + stream.write_all(response.as_bytes()).await.unwrap(); + stream.write_all(&body).await.unwrap(); + } + }); + let collector = + Collector::test(Url::parse(&format!("http://{address}/")).unwrap()).unwrap(); + let collected = collector.collect("acme/demo", 10, 2).await.unwrap(); + assert_eq!(collected.run.head_sha, "a".repeat(40)); + assert_eq!(collected.workflow.id, 20); + assert_eq!(collected.jobs.len(), 1); + server.await.unwrap(); + } +} diff --git a/src/checkpoint/manifest.rs b/src/checkpoint/manifest.rs new file mode 100644 index 0000000..98a1459 --- /dev/null +++ b/src/checkpoint/manifest.rs @@ -0,0 +1,312 @@ +use std::collections::{BTreeMap, BTreeSet}; + +use anyhow::{Context as _, bail}; +use serde::{Deserialize, Serialize}; + +pub(super) const FORMAT: &str = "proofline.checkpoint-manifest.v1"; +pub(super) const MAX_BYTES: usize = 256 << 10; +const MAX_MILESTONES: usize = 32; +const MAX_CRITERIA: usize = 32; + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Manifest { + pub(super) schema: String, + pub(super) task: String, + pub(super) repository: Repository, + pub(super) milestones: Vec, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Repository { + pub(super) host: String, + pub(super) full_name: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Milestone { + pub(super) id: String, + pub(super) purpose: String, + pub(super) depends_on: Vec, + pub(super) github: GitHubPolicy, + pub(super) criteria: Vec, + pub(super) review: ReviewPolicy, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct GitHubPolicy { + pub(super) workflow_path: String, + pub(super) event: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct Criterion { + pub(super) id: String, + pub(super) description: String, + pub(super) required: bool, + pub(super) job_name: String, +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(super) struct ReviewPolicy { + pub(super) required: bool, + pub(super) accepted_source: String, +} + +impl Manifest { + pub(super) fn parse(bytes: &[u8]) -> anyhow::Result { + if bytes.len() > MAX_BYTES { + bail!("checkpoint manifest is larger than {MAX_BYTES} bytes"); + } + let manifest: Self = + serde_json::from_slice(bytes).context("invalid checkpoint manifest")?; + manifest.validate()?; + Ok(manifest) + } + + pub(super) fn milestone(&self, id: &str) -> anyhow::Result<&Milestone> { + self.milestones + .iter() + .find(|milestone| milestone.id == id) + .with_context(|| format!("checkpoint manifest has no milestone {id:?}")) + } + + fn validate(&self) -> anyhow::Result<()> { + if self.schema != FORMAT { + bail!("unsupported checkpoint manifest schema {:?}", self.schema); + } + identifier("task", &self.task)?; + if !self.repository.host.eq_ignore_ascii_case("github.com") { + bail!("checkpoint manifests support only github.com repositories"); + } + repository_name(&self.repository.full_name)?; + if self.milestones.is_empty() || self.milestones.len() > MAX_MILESTONES { + bail!("checkpoint manifest must contain between 1 and {MAX_MILESTONES} milestones"); + } + + let mut ids = BTreeSet::new(); + for milestone in &self.milestones { + identifier("milestone", &milestone.id)?; + if !ids.insert(milestone.id.as_str()) { + bail!("duplicate checkpoint milestone {:?}", milestone.id); + } + text("milestone purpose", &milestone.purpose, 500)?; + if milestone.github.event != "push" { + bail!( + "milestone {:?} uses unsupported GitHub event {:?}; v1 supports only push", + milestone.id, + milestone.github.event + ); + } + git_path("workflow path", &milestone.github.workflow_path)?; + if milestone.criteria.is_empty() || milestone.criteria.len() > MAX_CRITERIA { + bail!( + "milestone {:?} must contain between 1 and {MAX_CRITERIA} criteria", + milestone.id + ); + } + let mut criterion_ids = BTreeSet::new(); + let mut job_names = BTreeSet::new(); + let mut required = 0_usize; + for criterion in &milestone.criteria { + identifier("criterion", &criterion.id)?; + if !criterion_ids.insert(criterion.id.as_str()) { + bail!( + "milestone {:?} has duplicate criterion {:?}", + milestone.id, + criterion.id + ); + } + text("criterion description", &criterion.description, 1_000)?; + text("GitHub job name", &criterion.job_name, 500)?; + if !job_names.insert(criterion.job_name.as_str()) { + bail!( + "milestone {:?} selects GitHub job {:?} more than once", + milestone.id, + criterion.job_name + ); + } + required += usize::from(criterion.required); + } + if required == 0 { + bail!("milestone {:?} has no required criterion", milestone.id); + } + if milestone.review.accepted_source != "none" { + bail!( + "milestone {:?} requests unsupported review source {:?}; acceptance-only v1 supports none", + milestone.id, + milestone.review.accepted_source + ); + } + let mut dependencies = BTreeSet::new(); + for dependency in &milestone.depends_on { + identifier("dependency", dependency)?; + if dependency == &milestone.id { + bail!("milestone {:?} depends on itself", milestone.id); + } + if !dependencies.insert(dependency.as_str()) { + bail!( + "milestone {:?} names dependency {:?} more than once", + milestone.id, + dependency + ); + } + } + } + for milestone in &self.milestones { + for dependency in &milestone.depends_on { + if !ids.contains(dependency.as_str()) { + bail!( + "milestone {:?} depends on unknown milestone {:?}", + milestone.id, + dependency + ); + } + } + } + self.reject_cycles() + } + + fn reject_cycles(&self) -> anyhow::Result<()> { + fn visit<'a>( + id: &'a str, + dependencies: &BTreeMap<&'a str, &'a [String]>, + visiting: &mut BTreeSet<&'a str>, + visited: &mut BTreeSet<&'a str>, + ) -> anyhow::Result<()> { + if visited.contains(id) { + return Ok(()); + } + if !visiting.insert(id) { + bail!("checkpoint milestone dependency cycle includes {id:?}"); + } + for dependency in dependencies.get(id).copied().unwrap_or_default() { + visit(dependency, dependencies, visiting, visited)?; + } + visiting.remove(id); + visited.insert(id); + Ok(()) + } + + let dependencies: BTreeMap<_, _> = self + .milestones + .iter() + .map(|milestone| (milestone.id.as_str(), milestone.depends_on.as_slice())) + .collect(); + let mut visiting = BTreeSet::new(); + let mut visited = BTreeSet::new(); + for id in dependencies.keys() { + visit(id, &dependencies, &mut visiting, &mut visited)?; + } + Ok(()) + } +} + +pub(super) fn repository_name(value: &str) -> anyhow::Result<()> { + let mut parts = value.split('/'); + let owner = parts.next().unwrap_or_default(); + let repository = parts.next().unwrap_or_default(); + if owner.is_empty() + || repository.is_empty() + || parts.next().is_some() + || value.len() > 200 + || value.chars().any(|character| { + character.is_control() + || !(character.is_ascii_alphanumeric() || matches!(character, '-' | '_' | '.')) + && character != '/' + }) + { + bail!("repository must be an OWNER/NAME on github.com"); + } + Ok(()) +} + +fn identifier(kind: &str, value: &str) -> anyhow::Result<()> { + if value.is_empty() + || value.len() > 100 + || !value + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.')) + { + bail!("{kind} ID {value:?} must contain 1-100 ASCII letters, digits, '.', '_' or '-'"); + } + Ok(()) +} + +fn text(kind: &str, value: &str, limit: usize) -> anyhow::Result<()> { + if value.trim().is_empty() + || value.chars().count() > limit + || value.chars().any(char::is_control) + { + bail!("{kind} must contain 1-{limit} characters without controls"); + } + Ok(()) +} + +fn git_path(kind: &str, value: &str) -> anyhow::Result<()> { + if value.is_empty() + || value.len() > 1_000 + || value.starts_with('/') + || value.contains('\\') + || value.chars().any(char::is_control) + || value.split('/').any(|part| matches!(part, "" | "." | "..")) + { + bail!("{kind} {value:?} is not an ordinary repository-relative path"); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn valid() -> serde_json::Value { + serde_json::json!({ + "schema": FORMAT, + "task": "migration", + "repository": {"host": "github.com", "full_name": "acme/demo"}, + "milestones": [{ + "id": "expand", + "purpose": "Add the field.", + "depends_on": [], + "github": {"workflow_path": ".github/workflows/check.yml", "event": "push"}, + "criteria": [{ + "id": "tests", "description": "Tests pass.", "required": true, + "job_name": "acceptance / tests" + }], + "review": {"required": false, "accepted_source": "none"} + }] + }) + } + + #[test] + fn strict_valid_manifest_is_accepted() { + Manifest::parse(&serde_json::to_vec(&valid()).unwrap()).unwrap(); + } + + #[test] + fn unknown_fields_and_cycles_are_rejected() { + let mut unknown = valid(); + unknown["extra"] = serde_json::json!(true); + assert!(Manifest::parse(&serde_json::to_vec(&unknown).unwrap()).is_err()); + + let mut cyclic = valid(); + let first = &mut cyclic["milestones"][0]; + first["depends_on"] = serde_json::json!(["contract"]); + cyclic["milestones"].as_array_mut().unwrap().push(serde_json::json!({ + "id": "contract", + "purpose": "Contract.", + "depends_on": ["expand"], + "github": {"workflow_path": ".github/workflows/check.yml", "event": "push"}, + "criteria": [{"id": "tests", "description": "Tests pass.", "required": true, "job_name": "acceptance / contract"}], + "review": {"required": false, "accepted_source": "none"} + })); + let error = Manifest::parse(&serde_json::to_vec(&cyclic).unwrap()).unwrap_err(); + assert!(error.to_string().contains("cycle"), "{error:#}"); + } +} diff --git a/src/git.rs b/src/git.rs index c88f567..8de1390 100644 --- a/src/git.rs +++ b/src/git.rs @@ -21,6 +21,12 @@ pub enum GitError { UnknownRemote, #[error("{0:?} is not a full commit SHA")] NotSha(String), + #[error("{0:?} is not an ordinary repository-relative Git path")] + InvalidBlobPath(String), + #[error("{path:?} is not an ordinary file at commit {commit}")] + NotBlob { path: String, commit: String }, + #[error("the Git blob {path:?} is larger than {limit} bytes")] + BlobTooLarge { path: String, limit: usize }, #[error( "the checkout has no base to review against: set an upstream branch with `git branch --set-upstream-to`, or run `git remote set-head {0} --auto`" )] @@ -62,6 +68,16 @@ pub struct PushedChange { pub head_commit_sha: String, } +/// One ordinary file read from an immutable commit, without consulting the +/// index or working tree. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct CommitBlob { + pub(crate) commit: String, + pub(crate) path: String, + pub(crate) object_id: String, + pub(crate) bytes: Vec, +} + /// The one commit `revision` names in the checkout at `dir`. A revision /// that starts with `-` would be read as an option, so it is refused. async fn resolve(dir: &Path, revision: &str) -> Result { @@ -205,6 +221,113 @@ async fn git_in(dir: &Path, index: Option<&Path>, args: &[&str]) -> Result Result { + line_in(dir, &["rev-parse", "--show-toplevel"]) + .await + .map(PathBuf::from) +} + +/// Reads one ordinary blob at `revision`. The tree lookup and blob read are +/// separate argument-vector Git calls, so a path is never interpreted as a +/// revision expression or shell text. +pub(crate) async fn blob_at_commit( + dir: &Path, + revision: &str, + path: &str, + limit: usize, +) -> Result { + if path.is_empty() + || path.len() > 1_000 + || path.starts_with('/') + || path.contains(['\0', '\\']) + || path.chars().any(char::is_control) + || path.split('/').any(|part| matches!(part, "" | "." | "..")) + { + return Err(GitError::InvalidBlobPath(path.to_owned())); + } + let commit = resolve(dir, revision).await?; + let entries = git_in( + dir, + None, + &[ + "--literal-pathspecs", + "ls-tree", + "-z", + "--full-tree", + &commit, + "--", + path, + ], + ) + .await?; + let mut object_id = None; + for entry in entries + .split(|byte| *byte == 0) + .filter(|entry| !entry.is_empty()) + { + let Some(tab) = entry.iter().position(|byte| *byte == b'\t') else { + return Err(GitError::NotBlob { + path: path.to_owned(), + commit, + }); + }; + if &entry[tab + 1..] != path.as_bytes() { + continue; + } + let metadata = String::from_utf8_lossy(&entry[..tab]); + let mut fields = metadata.split_ascii_whitespace(); + let mode = fields.next(); + let kind = fields.next(); + let object = fields.next(); + if matches!(mode, Some("100644" | "100755")) + && kind == Some("blob") + && fields.next().is_none() + { + object_id = object.map(str::to_owned); + } + } + let object_id = object_id.ok_or_else(|| GitError::NotBlob { + path: path.to_owned(), + commit: commit.clone(), + })?; + let bytes = git_in(dir, None, &["cat-file", "blob", &object_id]).await?; + if bytes.len() > limit { + return Err(GitError::BlobTooLarge { + path: path.to_owned(), + limit, + }); + } + Ok(CommitBlob { + commit, + path: path.to_owned(), + object_id, + bytes, + }) +} + +/// Whether `ancestor` is an ancestor of `head`. Missing history is an error, +/// not an assumed relationship. +pub(crate) async fn is_ancestor(dir: &Path, ancestor: &str, head: &str) -> Result { + let ancestor = resolve(dir, ancestor).await?; + let head = resolve(dir, head).await?; + let output = Command::new("git") + .arg("-C") + .arg(dir) + .args(["merge-base", "--is-ancestor", &ancestor, &head]) + .output() + .await + .map_err(|error| GitError::Unavailable(error.to_string()))?; + match output.status.code() { + Some(0) => Ok(true), + Some(1) => Ok(false), + _ => Err(GitError::Failed { + command: format!("merge-base --is-ancestor {ancestor} {head}"), + stderr: String::from_utf8_lossy(&output.stderr).trim().to_owned(), + }), + } +} + async fn line_in(dir: &Path, args: &[&str]) -> Result { let output = git_in(dir, None, args).await?; Ok(String::from_utf8_lossy(&output).trim().to_owned()) @@ -559,6 +682,15 @@ pub(crate) async fn remote_repository(remote: &str) -> Result Result { + let url = line_in(dir, &["remote", "get-url", "--", remote]).await?; + RemoteRepository::parse(&url).ok_or(GitError::UnknownRemote) +} + /// The checkout's `HEAD` commit. pub async fn head() -> Result { let sha = git(&["rev-parse", "--verify", "HEAD^{commit}"]).await?; @@ -737,6 +869,22 @@ mod tests { "{unknown}" ); } + + std::fs::write(dir.join("manifest.json"), "{\"committed\":true}\n").unwrap(); + run(dir, &["add", "manifest.json"]); + run(dir, &["commit", "-qm", "manifest"]); + let manifest_commit = run(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + std::fs::write(dir.join("manifest.json"), "working tree\n").unwrap(); + let blob = blob_at_commit(dir, &manifest_commit, "manifest.json", 1_024) + .await + .unwrap(); + assert_eq!(blob.bytes, b"{\"committed\":true}\n"); + assert!(is_ancestor(dir, &root, &manifest_commit).await.unwrap()); + assert!(!is_ancestor(dir, &manifest_commit, &root).await.unwrap()); + assert!(matches!( + blob_at_commit(dir, &manifest_commit, "../manifest.json", 1_024).await, + Err(GitError::InvalidBlobPath(_)) + )); } #[tokio::test] diff --git a/src/lib.rs b/src/lib.rs index 8bf7a9e..b477aea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ mod agent; mod annotations; pub mod api; +mod checkpoint; mod config; mod coverage; pub mod credentials; @@ -88,6 +89,9 @@ pub struct Cli { #[derive(Debug, Subcommand)] enum Command { + /// Bind milestone policy to one exact GitHub Actions run attempt. + #[command(subcommand)] + Checkpoint(checkpoint::Command), /// Read, propose and apply configuration through the hosted tools. #[command(subcommand)] Config(config::Command), @@ -454,6 +458,10 @@ pub enum Verdict { Blocked, /// A deploy failed or one of its checks recorded a regression. Regressed, + /// Required checkpoint evidence established that its declared policy failed. + CheckpointFailed, + /// Checkpoint identity or protocol validation rejected the supplied evidence. + CheckpointRejected, } /// Runs one command. `token` is `PROOFLINE_TOKEN`, read by the caller. @@ -481,6 +489,9 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result {} } + if let Command::Checkpoint(command) = cli.command { + return checkpoint::run(command).await; + } let origin = Origin::parse(&cli.base_url)?; match cli.command { Command::Completions { shell } => { @@ -672,6 +683,7 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result hooks::run(args, origin, token, cli.org).await, + Command::Checkpoint(_) => unreachable!("checkpoint commands return before origin parsing"), } } @@ -1457,7 +1469,12 @@ async fn show( Verdict::Unavailable => say( "Proofline returned the completed review without `open_items`, so --fail-on could not be measured. It is not a pass.", ), - Verdict::Done | Verdict::NotComplete | Verdict::Blocked | Verdict::Regressed => {} + Verdict::Done + | Verdict::NotComplete + | Verdict::Blocked + | Verdict::Regressed + | Verdict::CheckpointFailed + | Verdict::CheckpointRejected => {} } return Ok(verdict); } @@ -1767,7 +1784,12 @@ fn say_ci_ending( Verdict::Unavailable => say( "Proofline returned the completed review without `open_items`, so --fail-on could not be measured. It is not a pass.", ), - Verdict::Done | Verdict::NotComplete | Verdict::Blocked | Verdict::Regressed => {} + Verdict::Done + | Verdict::NotComplete + | Verdict::Blocked + | Verdict::Regressed + | Verdict::CheckpointFailed + | Verdict::CheckpointRejected => {} }, Some(ended) => say_not_complete(ended), } diff --git a/src/main.rs b/src/main.rs index 04ae422..a67d8ef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -53,8 +53,10 @@ fn main() -> ExitCode { // `--fail-on`: the review is complete and a finding reaches the // caller's threshold. `ci deploy`: a deploy failed or a check // recorded a regression. - Ok(Verdict::ThresholdReached | Verdict::Regressed) => ExitCode::from(3), - Ok(Verdict::Blocked) => ExitCode::FAILURE, + Ok(Verdict::ThresholdReached | Verdict::Regressed | Verdict::CheckpointFailed) => { + ExitCode::from(3) + } + Ok(Verdict::Blocked | Verdict::CheckpointRejected) => ExitCode::FAILURE, Err(error) => { eprintln!("proofline: {error:#}"); ExitCode::FAILURE diff --git a/src/update.rs b/src/update.rs index 306f5a3..ee2f66d 100644 --- a/src/update.rs +++ b/src/update.rs @@ -109,7 +109,7 @@ pub fn on_invocation() { /// Arguments whose commands print for a script, Git or a long-running /// session, so an update notice there would corrupt what they read. -const QUIET_ARGUMENTS: [&str; 20] = [ +const QUIET_ARGUMENTS: [&str; 21] = [ "reviews", "routing", "run", @@ -130,6 +130,7 @@ const QUIET_ARGUMENTS: [&str; 20] = [ "ci", "hook", "hooks", + "checkpoint", ]; /// The newer cached version an invocation announces, if any. diff --git a/tests/checkpoint.rs b/tests/checkpoint.rs new file mode 100644 index 0000000..de748ea --- /dev/null +++ b/tests/checkpoint.rs @@ -0,0 +1,127 @@ +//! Checkpoint reporting is offline and independent of Proofline configuration. + +use std::process::Command; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde_json::json; + +fn record() -> serde_json::Value { + json!({ + "schema": "proofline.checkpoint-evidence.v1", + "cli_version": "test", + "source_class": "github_api", + "task": "migration", + "milestone": "expand", + "purpose": "Add the field.", + "repository": { + "host": "github.com", + "requested_full_name": "acme/demo", + "canonical_full_name": "acme/demo", + "github_id": 7 + }, + "revision": { + "head": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "base": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "kind": "commit", + "convention": "first_parent" + }, + "manifest": { + "commit": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "path": ".proofline/checkpoints.json", + "git_object": "cccccccccccccccccccccccccccccccccccccccc", + "sha256": "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd" + }, + "workflow": null, + "run": null, + "dependencies": [], + "evaluation": { + "acceptance": { + "status": "PASSED", + "criteria": [{ + "id": "tests", + "description": "Tests pass.", + "required": true, + "job_name": "acceptance / tests", + "status": "PASSED", + "reason": "the job completed successfully", + "job_id": 11, + "github_status": "completed", + "github_conclusion": "success", + "job_url": "https://github.com/acme/demo/actions/runs/10/job/11", + "started_at": "2026-11-30T00:00:00Z", + "completed_at": "2026-11-30T00:01:00Z" + }] + }, + "review": { + "required": false, + "status": "ABSENT", + "source": "none", + "reason": "the milestone does not require review evidence" + }, + "dependency_status": "SATISFIED", + "policy": "SATISFIED", + "reasons": [] + }, + "verification_scope": "acceptance_checks_only", + "limitations": ["offline"], + "observed_at_unix": 1 + }) +} + +#[test] +fn report_is_offline_and_ignores_proofline_origin_token_and_updater() { + let directory = tempfile::tempdir().unwrap(); + let checkpoint = directory.path().join("checkpoint.json"); + std::fs::write(&checkpoint, serde_json::to_vec_pretty(&record()).unwrap()).unwrap(); + let cache = directory.path().join("proofline"); + std::fs::create_dir_all(&cache).unwrap(); + let checked = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_secs(); + std::fs::write( + cache.join("update.json"), + format!("{{\"checked\":{checked},\"latest\":\"9.0.0\"}}"), + ) + .unwrap(); + + let output = Command::new(env!("CARGO_BIN_EXE_proofline")) + .args(["--base-url", "invalid", "checkpoint", "report"]) + .arg(&checkpoint) + .env_remove("PROOFLINE_NO_UPDATE_CHECK") + .env("PROOFLINE_TOKEN", "PROOFLINE_SECRET_CANARY") + .env("HOME", directory.path()) + .env("XDG_CACHE_HOME", directory.path()) + .env("LOCALAPPDATA", directory.path()) + .output() + .unwrap(); + + assert!(output.status.success(), "{output:?}"); + assert!(output.stderr.is_empty(), "{output:?}"); + let report = String::from_utf8(output.stdout).unwrap(); + assert!(report.contains("**Policy:** `SATISFIED`"), "{report}"); + assert!(!report.contains("PROOFLINE_SECRET_CANARY")); + assert!(!report.contains("9.0.0")); +} + +#[test] +fn report_refuses_unknown_evidence_fields() { + let directory = tempfile::tempdir().unwrap(); + let checkpoint = directory.path().join("checkpoint.json"); + let mut value = record(); + value["unknown"] = json!(true); + std::fs::write(&checkpoint, serde_json::to_vec(&value).unwrap()).unwrap(); + let output = Command::new(env!("CARGO_BIN_EXE_proofline")) + .args(["checkpoint", "report"]) + .arg(checkpoint) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + assert!(output.stdout.is_empty()); + assert!( + String::from_utf8(output.stderr) + .unwrap() + .contains("invalid checkpoint evidence") + ); +}