From 4a95a94b2c86d6bf092293019e132a3564da2c28 Mon Sep 17 00:00:00 2001 From: Andrew Krock Date: Thu, 1 Oct 2026 01:02:10 -0400 Subject: [PATCH 001/123] docs(evidence): record approved issue 777 CI gate plan --- TODOS.md | 68 ++ ...ssue-777-policy-driven-ci-evidence-gate.md | 158 ++++ ...-driven-ci-evidence-gate-implementation.md | 748 ++++++++++++++++++ 3 files changed, 974 insertions(+) create mode 100644 docs/designs/issue-777-policy-driven-ci-evidence-gate.md create mode 100644 docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md diff --git a/TODOS.md b/TODOS.md index fcb1657b6..2831fc65e 100644 --- a/TODOS.md +++ b/TODOS.md @@ -62,3 +62,71 @@ - **What:** Add a source analyzer and optional codemod for legacy dotted AppSurface configuration-key call sites. **Why:** Runtime diagnostics can identify executed paths, but they cannot prove that every attribute, direct read, audit registration, provider mapping, and dormant branch has migrated. **Pros:** Gives maintainers a compile-time inventory and automates safe `.` to `:` replacements. **Cons:** The analyzer would freeze grammar and API assumptions too early if built before the typed key and migration diagnostics stabilize. **Context:** The logical-key contract deliberately keeps only one permanent colon syntax and uses bounded compatibility input; the analyzer should consume the final parser rules rather than reimplementing them. **Effort estimate:** L (human team) -> M with CC+gstack. **Priority:** P2. **Depends on / blocked by:** Stable `AppSurfaceConfigKey`, application-boundary parser, diagnostic codes, and release-train policy. - **What:** Add a credentialed Google Secret Manager contract proof for explicit mappings, convention ids, versions, and exact provenance. **Why:** The fake transport proves AppSurface behavior but cannot prove deployed IAM, API resource validation, or response-name behavior. **Pros:** Catches provider drift before a release and validates the exact native-resource contract. **Cons:** Requires a dedicated project, credential rotation, cleanup, cost controls, and a trust-boundary design for CI. **Context:** Keep the default provider suite deterministic and value-safe; run the live proof as a separate protected release verification rather than enumerating unclaimed secrets. **Effort estimate:** M (human team) -> S with CC+gstack. **Priority:** P2. **Depends on / blocked by:** Stable Google codec/resource-claim contract and approved CI credential design. + +## EvidenceHost follow-ups (#777) + +### Reusable EvidenceHost workflow for another repository + +**What:** Design a versioned consumer input/output and reusable GitHub workflow after AppSurface's required gate has a second adopter. +**Why:** The first reference should prove the trust boundary before it becomes a compatibility promise. +**Pros:** Easier adoption and one maintained workflow contract. +**Cons:** Public versioning, support and security obligations may outgrow the first adopter's needs. +**Context:** [The #777 design](docs/designs/issue-777-policy-driven-ci-evidence-gate.md) deliberately keeps the runner AppSurface-owned; start from its validated policy/producer matrix, pilot results and [implementation plan](docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md). +**Effort:** L +**Priority:** P3 +**Depends on:** #777 shipped and a real second adopter. + +### Fork check publisher without same-repository promotion + +**What:** Evaluate a base-owned PR-eligible check publisher for fork contributions if the measured exact-SHA promotion cost is too high. +**Why:** #777's fork observation is intentionally ineligible for its required gate. +**Pros:** Could reduce maintainer promotion work while retaining a verified head-attached check. +**Cons:** Adds a new authenticated publication and provenance boundary. +**Context:** Use the #777 pilot's fork frequency, turnaround and failure records; never turn a manual dispatch or label into an eligible claim. +**Effort:** L +**Priority:** P3 +**Depends on:** #777 fork pilot and a measured maintainer burden. + +### Self-hosted EvidenceHost runner support + +**What:** Add an external reaper and runner isolation proof for persistent or self-hosted EvidenceHost runners. +**Why:** #777 relies on ephemeral VM destruction when its local-only resources lose their runner. +**Pros:** Broader deployment options for repositories with a self-hosted compute need. +**Cons:** A persistent runner needs a new cleanup lifetime, network boundary and operations owner. +**Context:** Keep GitHub-hosted ephemeral PR jobs as the #777 reference; use a concrete adopter and failure model before changing that guarantee. +**Effort:** L +**Priority:** P3 +**Depends on:** #777 rollout and a self-hosted runner adopter. + +### Merge-queue EvidenceHost event support + +**What:** Add `merge_group` event handling and revalidate required-check identity when AppSurface adopts merge queue. +**Why:** A PR-head check cannot automatically authorize a synthetic merge-group revision. +**Pros:** EvidenceHost can stay a required gate when queueing is enabled. +**Cons:** New event identity, source-diff and freshness semantics require live proof. +**Context:** #777 gates ordinary PRs with strict freshness. Reuse its capture/verify boundary for a separately defined merge-group identity. +**Effort:** M +**Priority:** P3 +**Depends on:** #777 rollout and a merge-queue adoption decision. + +### Evidence-backed release publication + +**What:** Design a publisher that consumes only object-bound, digest-matching `ReleaseComplete` artifacts under a verified immutable tag rule. +**Why:** #777's release invocation is non-mutating; a claim alone cannot close a moving-tag check/use window. +**Pros:** Publication could inherit the same verified evidence identity. +**Cons:** Introduces an irreversible release side effect and a new authorization boundary. +**Context:** Start with #777's V2 tag binding and protected release pilot. Revalidate remote tag immutability and artifact bytes immediately before and throughout publication use. +**Effort:** L +**Priority:** P3 +**Depends on:** #777 release proof, immutable tag policy and separate publisher approval. + +### Hosted EvidenceHost dashboard + +**What:** Consider a hosted view only if maintainers cannot diagnose real gate failures from the bounded GitHub summary, manifest and runbook. +**Why:** A dashboard would add hosting and retention before the first adopter proves a need. +**Pros:** Could centralize long-term evidence trends for multiple adopters. +**Cons:** Adds cost, permissions, sensitive-data handling and another source of truth. +**Context:** #777 records local and GitHub artifacts only. Collect actual diagnostic failures before proposing a service. +**Effort:** XL +**Priority:** P4 +**Depends on:** Measured multi-adopter diagnostic need after #777. diff --git a/docs/designs/issue-777-policy-driven-ci-evidence-gate.md b/docs/designs/issue-777-policy-driven-ci-evidence-gate.md new file mode 100644 index 000000000..1709ff1c3 --- /dev/null +++ b/docs/designs/issue-777-policy-driven-ci-evidence-gate.md @@ -0,0 +1,158 @@ +# Design: AppSurface policy-driven CI evidence gate + +Generated by /office-hours on 2026-09-30 +Branch: `main` +Repo: `forge-trust/AppSurface` +Status: APPROVED (office-hours, 2026-09-30) +Mode: Builder +Issue: [#777](https://github.com/forge-trust/AppSurface/issues/777) +Builds on: [EvidenceHost contract-first design](appsurface-evidencehost-contract-first.md) and completed [#775](https://github.com/forge-trust/AppSurface/issues/775) + +## Problem Statement + +AppSurface has an [Evidence planner, CLI, and host contract](../../start-here/evidencehost.md), but no AppSurface CI workflow calls `appsurface evidence`. A maintainer cannot point at a live, safe reference run that proves a checked-in policy selected the work for an exact change and that the resulting manifest supports the CI verdict. Current independent workflows still decide what to run in YAML. The AppSurface repository also has no required status check in its active default-branch ruleset, so publishing a green example alone would not create a merge gate. + +The first adopter is AppSurface's own maintainers. The intended outcome is a working required PR check plus a release invocation of the same evidence runner. It should be possible to copy the documented pattern later, but this issue does not promise a general reusable workflow interface for other repositories. + +## What Makes This Cool + +The workflow says *which revisions and policy were evaluated, why a profile was selected, what every obligation required, and whether the evidence actually closed it*. A docs-only change receives an explicit `NoEvidenceRequired` claim. A code change whose selected producer or disposable resource fails cannot become green because some other CI job passed. The console, GitHub summary, and machine manifest render one verdict from one plan. A fork can still be inspected, but it cannot borrow a trusted claim. + +## Constraints + +- [#777](https://github.com/forge-trust/AppSurface/issues/777) is an AppSurface-owned reference path, not a new CI scheduler, deployment system, generic plugin loader, or cross-job aggregation format. +- The [existing EvidenceHost design](appsurface-evidencehost-contract-first.md) owns the contract boundary: base-owned policy and explicit host registrations; separate trusted-tool and subject checkouts; [coverage core](evidence-coverage-core-extraction.md) reuse; typed producer/resource/obligation closure; bounded cleanup; observation-only execution for untrusted inputs. +- The current [planning CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) accepts policy and path/diff inputs but has no authoritative base/head arguments. Its run command can execute the built-in coverage producer; it cannot yet execute every resource-backed AppSurface profile. The [plan contract](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs) records a normalized diff digest but not base/head or the exact source diff bytes. These are implementation gaps, not values YAML can invent. +- Required-check behavior depends on GitHub event and ruleset semantics. The current default-branch ruleset requires reviews but no CI status. A planned gate must be proven on an actual PR before that ruleset changes. +- No production credentials, mutable release operations, or head-controlled workflow/host/policy instructions enter the evidence run. The reference release profile remains non-mutating. + +## Premises + +1. **Selection is policy-owned and revision-bound.** The authoritative plan includes full base and head Git object IDs, SHA-256 of the exact captured source diff bytes, normalized change digest, policy digest, profile, and plan digest. CI regenerates and verifies the source diff from those objects with fixed Git options before `explain` and `run`; both commands consume the same immutable snapshot. A self-consistent manifest without this external revision check is insufficient. +2. **Only the manifest decides the gate.** A PR passes only for a verified, current-base-and-head, gate-eligible `TargetedComplete` or explicit `NoEvidenceRequired` claim. `NoEvidenceRequired` is not a synonym for a skipped job. Missing producer, resource, obligation, required artifact, cleanup, or envelope state produces no complete claim and a failed gate. A release pipeline requires `ReleaseComplete` with release eligibility; a PR check cannot reinterpret a targeted claim as release complete. Policy selects the candidate profile from the diff; trusted event context separately determines whether that profile may issue a PR or release claim. +3. **The trusted control plane is base-owned.** The workflow, policy, host registrations, runner, and envelope verifier come from the protected base/trusted-tool revision. The head is only the subject under test. No subject file can choose a command, image, mount, token, network capability, producer, or artifact root. +4. **Fork and other untrusted inputs remain observational.** They receive no privileged capability or complete claim. The required check fails until reviewed content is promoted to a trusted same-repository branch and a new PR-eligible run evaluates that exact promoted head. A manual `workflow_dispatch` report alone cannot satisfy the PR's required check. +5. **The reference proves all AppSurface-selected profiles.** The host must actually run every producer/resource required by the checked-in AppSurface policy, including its non-mutating release profile. Unsupported profile or missing registration fails closed; YAML never silently downgrades the profile. + +## Cross-Model Perspective + +A fresh `combo/sub` review supported a base-owned evidence path but challenged the original claim that a policy, diff, and plan digest alone identify the tested change. It observed that two revision pairs can yield the same normalized paths and that a GitHub event's merge checkout can differ from the requested head. We accepted the challenge: exact base/head identities and the captured diff-byte digest belong in the plan and manifest contract, and CI must independently regenerate the diff before execution. The reviewer also suggested a trusted manual rerun for forks; GitHub's required-check rules make that insufficient as a PR gate, so promotion to a same-repository branch is the explicit path. + +## Approaches Considered + +- **A — Narrow live PR gate (M; about 2–4 human days / 4–8 agent hours).** Gets coverage and no-evidence cases live sooner, but leaves resource-backed and release-profile completeness unproved. Rejected because the selected reference would still demonstrate only the easy branch of EvidenceHost. +- **B — Complete AppSurface EvidenceHost gate (L; about 1–2 human weeks / 1–2 agent days). Selected.** Builds one revision-bound runner and explicit AppSurface host registrations, exercises every policy-selected profile, then makes the PR check required after live proof. The extra work is concentrated in real host execution and trust isolation. +- **C — Versioned reusable workflow (XL; about 2–3 human weeks / 3–5 agent days).** Adds a public consumer input/output and compatibility surface before the first live adopter. Deferred until AppSurface's own path is stable. + +## Recommended Approach + +### 1. Capture and bind the exact change + +The PR controller reads the event's target-base tip and head SHA as data, validates full commit IDs, fetches both objects by SHA, and computes a fixed-options `git diff` between them. It records the source bytes once in a bounded file, independently regenerates the same bytes from the fetched objects, and fails if they differ. The comparison is deliberately the explicit pair rather than an implicit checkout, merge commit, or ambient Git state. This may select extra work when the base advances; that is a conservative cost, never a missing-evidence shortcut. The ordinary build workflow remains responsible for merge-commit compatibility. The plan also records the PR number, target-base tip, workflow/run identity, and head SHA as bounded provenance fields, but these are not substitutes for Git object verification. Immediately before the final verdict, the controller rereads the PR's current target-base tip and head via the GitHub API and rejects either mismatch as stale; a completed run is never retroactively reinterpreted for a new pair. + +Extend the versioned Evidence contracts and the [CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) with authoritative `--base-revision`, `--head-revision`, and `--diff-file` inputs. A new schema version records `SourceDiffDigest` separately from the existing normalized `DiffDigest`; plan and manifest digests cover both revisions and both digests. `explain`, `run`, and `verify` use the same canonical plan identity. Gate mode rejects path-only input, abbreviated SHAs, missing Git objects, a mismatched source diff, stale policy, or a head changed since the event. Local non-gate CLI use can keep its existing path/diff ergonomics and must not imply gate eligibility. Publish the schema migration and compatibility rules in the [Evidence contract reference](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md) and [EvidenceHost guide](../../guides/evidencehost-cookbook.md). + +### 2. Execute a closed AppSurface policy in one host + +Check in an AppSurface policy whose every repository path is accounted for by an explicit rule or conservative fallback. It distinguishes docs-only `NoEvidenceRequired` from code/coverage, resource-backed integration, and non-mutating release profiles. Renames evaluate both sides; deletions and mixed docs/code changes cannot collapse to docs-only. Policy selects only named, base-registered resources, producers, obligations, assertions, and artifact slots. A release profile runs only in a protected release context; selecting it in a PR context fails as an event/profile mismatch rather than issuing a release claim. + +A dedicated AppSurface host runner composes the [EvidenceHost bootstrap](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/EvidenceHostBootstrap.cs) with explicit first-party registrations. It invokes the extracted coverage core through its existing seam, provisions disposable required resources through Aspire adapters, and runs the selected AppSurface integration and package/release evidence as typed producers with bounded readiness, execution, artifact, and cleanup behavior. It does not treat existing separate workflow job conclusions as producer results. The host owns one manifest even on producer failure where the contract permits one. A missing registration or resource returns an incomplete/invalid manifest and nonzero gate exit. Any capability that AppSurface cannot run safely stays outside the policy until a concrete, tested producer exists; the conservative fallback cannot declare it satisfied. + +For the protected release invocation, the subject is the peeled commit of a protected annotated release tag, not the workflow's ambient checkout or a user-supplied branch name. The trusted release verifier reads the tag object and commit from Git, checks the tag/version against the existing protected release-publish validation, and records the tag object ID, peeled commit, comparison-base commit, and SHA-256 of each policy-declared release package or archive in the plan and manifest. A package producer hashes the exact output it verified; publishing may consume only those digest-matching artifacts if the claim is used to authorize publication. A changed tag, rebuilt artifact with different bytes, missing declared artifact, or mismatched release event invalidates `ReleaseComplete`. Release policy still selects the candidate profile from the explicit comparison-base/tag-commit diff; the protected event and artifact checks grant release eligibility separately. + +### 3. Separate trusted control and subject execution + +The PR workflow uses a base-owned, PR-eligible trigger such as `pull_request_target` only after a live pilot verifies event availability, check association with the PR's current head, and repository event policy. It uses pinned actions, minimal read permissions, `persist-credentials: false`, no secrets, and separate read-only trusted-tool and subject checkouts. The supported runner is an ephemeral GitHub-hosted VM. The trusted controller runs outside a rootless OCI subject container pinned by image digest. The container receives only a read-only subject source mount and a dedicated writable scratch mount. It has a non-root UID, read-only root filesystem, dropped capabilities, no-new-privileges, bounded CPU/memory/PIDs, and no token, Docker/Podman socket, host home, trusted-tool mount, or runner credential files. For a profile without dependencies it has no network; a resource-backed profile uses a per-run internal network with only its declared disposable services and explicit egress denial, including denial of the host gateway and cloud metadata endpoint. Trusted code starts the container with argument arrays, validates its exit status and declared artifacts copied out of scratch, and treats all subject output as untrusted data. The base-owned envelope verifier checks this exact mount/network/capability configuration, runner class, root identities, subject/trusted revisions, and capability evidence immediately before resource provisioning. Inputs from PR titles, paths, or head files are never interpolated into shell commands. If the runner cannot enforce these properties, trusted claims are disabled. + +The controller owns resource labels and an external supervisor process, independent of the EvidenceHost process, with a per-run 10-minute cleanup deadline. Normal `finally` cleanup and an `if: always()` CI step ask the supervisor to stop containers/services, remove the per-run network and scratch data, and attest completion; failed or timed-out cleanup prevents a complete claim. A forced EvidenceHost-process kill is tested with the supervisor still alive and must converge within the declared deadline. If the entire VM is lost, no final manifest/check success can be issued, and its local-only resources die with the ephemeral VM; provider VM-destruction latency is outside the 10-minute claim. Persistent/self-hosted runners and external shared resources are unsupported until they have a separately demonstrated external reaper. + +For fork or otherwise untrusted heads, the workflow may emit a bounded observation report from a dependency-free safe subset; it always records `ObservationOnly` and exits the required gate nonzero. Maintainers can review and promote an exact commit to a same-repository branch, then run the normal PR path on a replacement or updated PR. The fork PR's observation does not become green by approval label or manual dispatch. If GitHub's policy prevents the intended PR trigger or attaches its check to the wrong revision, rollout stops before ruleset activation; use a separately designed base-owned PR-eligible check publisher rather than weakening the trust boundary. + +### 4. Derive one bounded output and turn it into a gate + +After host completion, verify the manifest against the captured plan, source diff, policy, selected profile, artifact hashes, trust envelope, and current PR head. One renderer produces the terminal verdict, GitHub step summary, and machine JSON from that verified result. It prints claim kind, eligible gate, profile/rule rationale, base/head short IDs, selected/closed/missing obligation IDs, and stable diagnostic codes; it never prints secret values, raw producer logs, arbitrary file contents, or unbounded changed-path lists. It truncates and counts long collections deterministically and stays below GitHub's [1 MiB step-summary limit](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands). Artifact upload and summary writing are presentation steps, not verdict sources; an upload failure cannot turn an incomplete run green. A pre-plan validation failure emits a bounded diagnostic and failed status without inventing a manifest. + +The gate job has a stable name, runs on PR `opened`, `synchronize`, `reopened`, `ready_for_review`, and base-target `edited` events without path filters or job-level skipping, and explicitly exits nonzero for `None`, `ObservationOnly`, invalid, incomplete, stale, cancelled, or wrong-scope claims. This avoids GitHub's [skipped-job success semantics](https://docs.github.com/en/pull-requests/reference/status-checks). Keep the existing build/test checks while the new gate runs in observation mode. After successful same-repository, docs-only, failing, and fork PR pilots prove the check attaches to the current PR head, add that exact check to the default-branch ruleset with [strict required-check freshness](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets). When the target base advances after a run, GitHub must block merging until the PR branch is updated; that head update emits `synchronize` and a new base/head-bound check. The live pilot must prove this behavior, including a base update while the head is unchanged, before enforcement. If merge queue is adopted, add `merge_group` support and revalidate before queue activation. A manual release invocation uses the same runner and release-specific verifier but is never counted as the PR's required check. + +## Open Questions + +- Which concrete AppSurface integration and package/release assertions can be safely executed inside the first host? The implementer must inventory the current [build](../../.github/workflows/build.yml), [package gate](../../.github/workflows/package-gate.yml), and [release contract](../../.github/workflows/release-contract.yml) workflows and name each policy obligation before wiring the host. Missing capability blocks that profile's promotion; it does not become an empty success. +- Does the live GitHub event policy permit the selected base-owned PR trigger, and does its named check satisfy the current-head required-check rule in this repository? This is a rollout experiment, not an assumed platform guarantee. + +## Success Criteria + +1. On a live AppSurface PR, `explain` and `run` report the same plan digest for verified base/head/diff/policy inputs; altering any one makes the gate fail before a complete claim. A new head causes a new run; a base update makes the strict required check stale until the head is updated and rerun. The final verifier checks both current SHAs, so an old manifest cannot satisfy either new revision. +2. Docs-only, code, mixed/renamed/deleted, resource-backed, and release fixtures select their candidate profiles solely from policy; trusted PR or protected release context separately determines claim eligibility. Docs-only produces explicit `NoEvidenceRequired`; unrecognized paths select the conservative profile or fail. +3. Positive host runs yield verified `TargetedComplete` or `ReleaseComplete` claims as appropriate. Injected missing producer, unavailable resource, failed assertion, absent required artifact, cleanup failure, or envelope mismatch yields no complete claim and a failed gate. Release fixtures also prove tag-object/peeled-commit and package-digest binding against the protected release invocation. Fork/untrusted runs yield `ObservationOnly` and a failed required check. +4. Terminal, GitHub summary, and manifest agree on the claim and missing obligations. Secret canaries and oversized/malicious paths do not leak or exceed output limits. Normal cancellation and a forced host-process kill clean up the disposable topology within the in-VM 10-minute bound; entire-VM loss yields no complete claim and leaves no shared resource. +5. A real PR demonstrates the stable evidence check on the current head, a base-advance freshness block, and the default-branch ruleset requires it with strict freshness. The repository can merge a qualifying trusted PR and blocks an incomplete or fork-observation PR. Existing checks remain green, formatting and changed-code branch tests pass, and solution coverage is run when practical. + +## Distribution Plan + +Deliver the reference as a checked-in AppSurface workflow, policy, explicit host runner, versioned Evidence contract/CLI changes, and an [EvidenceHost adoption guide](../../start-here/evidencehost.md). A consumer starts by copying the documented checkout/policy/runner pattern and replacing the explicit host registrations; it must prove completeness of every selected test profile before enforcing its own required check. The existing AppSurface package release pipeline publishes the contract and CLI changes. The CI workflow runs on PRs; the protected release pipeline invokes its release profile. No deployment or automatic release is introduced here. + +## Dependencies + +[#775](https://github.com/forge-trust/AppSurface/issues/775) supplies the current contract and coverage seam. The GitHub required-check rollout depends on a live PR pilot and a repository administrator updating the active default-branch ruleset. An AppSurface resource-backed and release producer inventory is needed before those profiles can become required. The older [EvidenceHost contract-first design](appsurface-evidencehost-contract-first.md) remains the architecture source for consumer-owned hosts and trust-envelope semantics. + +## The Assignment + +Take one real AppSurface PR that changes code and record its exact target-base tip, head SHA, and selected policy profile. Use it as the pilot fixture for verifying that the planned base-owned check reports against the current head before asking an administrator to make the check required. + +## Next Steps + +1. Inventory existing AppSurface CI evidence and write the complete checked-in policy/registration matrix; identify any selected profile that lacks a safe producer. +2. Add revision/source-diff binding to contracts, CLI, planner, verifier, and documentation; test deterministic identity and tampering/compatibility cases. +3. Implement the explicit AppSurface host runner and typed producers, then prove complete and failure branches including resource, cleanup, and release envelope behavior. +4. Add the base-owned PR workflow and protected release invocation, bounded renderer, fork observation path, and trust-isolation tests. +5. Pilot real PR check association and event policy; only then enable the exact required check in the ruleset and document the consumer adoption path. + +## What I noticed about how you think + +- You answered “AppSurface CI gates” when asked for the first proof. That makes this a real repository behavior, with branch protection as the finish line. +- You chose the stricter fork outcome: observation can inform review, but it cannot silently satisfy a required evidence check. +- You accepted the second opinion's revision-binding challenge and chose the complete EvidenceHost path. The design now has to prove the exact tested change and the harder resource/release branches, not just produce a polished YAML example. + + +## Reviewer Concerns + +Disposition: CONCERNS_RECORDED + +Stop: CONVERGENCE + +### R2-1 — completeness + +**Problem** + +> The release plan records a comparison-base commit, but the design does not define which trusted revision supplies that base or how the release event binds to it. Since policy selects the release profile from the tag-commit diff, different baselines can select different obligations while still producing a revision-bound manifest. + +**Remedy** + +> Define a deterministic, trusted source and selection rule for the release comparison base, bind that base to the protected release event, and test missing, changed, and mismatched baseline cases before allowing a ReleaseComplete claim. + +### R2-2 — completeness + +**Problem** + +> The design says a changed tag invalidates ReleaseComplete, but it does not specify a final check of the tag ref/object (or an enforced immutability guarantee) between evidence capture, verdict issuance, and publication use. A tag that moves after capture could leave a claim authorizing artifacts for a commit the release tag no longer identifies. + +**Remedy** + +> Require the trusted verifier to recheck the protected tag ref, tag object ID, and peeled commit immediately before issuing ReleaseComplete and before any publication consumes the claim, or specify and verify an equivalent immutable-tag guarantee; include a retagging race test. + +### R2-3 — feasibility + +**Problem** + +> The subject can write arbitrary content to scratch, and trusted code copies declared artifacts out, but the copy-out boundary has no path-containment, file-type, or size rules. A malicious subject could use symlinks or special files to make the trusted copier escape scratch or process unbounded data, undermining the stated isolation boundary. + +**Remedy** + +> Specify a no-follow extraction protocol that accepts only normalized relative paths resolving inside scratch and regular files, enforces per-file and aggregate count/size limits, and tests traversal, symlink, special-file, and oversized-artifact cases. + +### Prior finding evidence + +**R1-3 → R2-3 (persisting)** + +> Recommended Approach 3 specifies the ephemeral VM, rootless OCI container, mounts, credential/socket exclusions, resource network and egress limits, and envelope checks, but only says declared artifacts are copied from subject-writable scratch; it does not constrain that transfer so it cannot follow paths outside scratch or expose trusted host data. See R2-3. + diff --git a/docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md b/docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md new file mode 100644 index 000000000..1e15e048e --- /dev/null +++ b/docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md @@ -0,0 +1,748 @@ + +## Implementation plan +# Design: AppSurface policy-driven CI evidence gate + +Generated by /office-hours on 2026-09-30 +Branch: `main` +Repo: `forge-trust/AppSurface` +Status: APPROVED (office-hours, 2026-09-30) +Mode: Builder +Issue: [#777](https://github.com/forge-trust/AppSurface/issues/777) +Builds on: [EvidenceHost contract-first design](appsurface-evidencehost-contract-first.md) and completed [#775](https://github.com/forge-trust/AppSurface/issues/775) + +## Problem Statement + +AppSurface has an [Evidence planner, CLI, and host contract](../../start-here/evidencehost.md), but no AppSurface CI workflow calls `appsurface evidence`. A maintainer cannot point at a live, safe reference run that proves a checked-in policy selected the work for an exact change and that the resulting manifest supports the CI verdict. Current independent workflows still decide what to run in YAML. The AppSurface repository also has no required status check in its active default-branch ruleset, so publishing a green example alone would not create a merge gate. + +The first adopter is AppSurface's own maintainers. The intended outcome is a working required PR check plus a release invocation of the same evidence runner. It should be possible to copy the documented pattern later, but this issue does not promise a general reusable workflow interface for other repositories. + +## What Makes This Cool + +The workflow says *which revisions and policy were evaluated, why a profile was selected, what every obligation required, and whether the evidence actually closed it*. A docs-only change receives an explicit `NoEvidenceRequired` claim. A code change whose selected producer or disposable resource fails cannot become green because some other CI job passed. The console, GitHub summary, and machine manifest render one verdict from one plan. A fork can still be inspected, but it cannot borrow a trusted claim. + +## Constraints + +- [#777](https://github.com/forge-trust/AppSurface/issues/777) is an AppSurface-owned reference path, not a new CI scheduler, deployment system, generic plugin loader, or cross-job aggregation format. +- The [existing EvidenceHost design](appsurface-evidencehost-contract-first.md) owns the contract boundary: base-owned policy and explicit host registrations; separate trusted-tool and subject checkouts; [coverage core](evidence-coverage-core-extraction.md) reuse; typed producer/resource/obligation closure; bounded cleanup; observation-only execution for untrusted inputs. +- The current [planning CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) accepts policy and path/diff inputs but has no authoritative base/head arguments. Its run command can execute the built-in coverage producer; it cannot yet execute every resource-backed AppSurface profile. The [plan contract](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs) records a normalized diff digest but not base/head or the exact source diff bytes. These are implementation gaps, not values YAML can invent. +- Required-check behavior depends on GitHub event and ruleset semantics. The current default-branch ruleset requires reviews but no CI status. A planned gate must be proven on an actual PR before that ruleset changes. +- No production credentials, mutable release operations, or head-controlled workflow/host/policy instructions enter the evidence run. The reference release profile remains non-mutating. + +## Premises + +1. **Selection is policy-owned and revision-bound.** The authoritative plan includes full base and head Git object IDs, SHA-256 of the exact captured source diff bytes, normalized change digest, policy digest, profile, and plan digest. CI regenerates and verifies the source diff from those objects with fixed Git options before `explain` and `run`; both commands consume the same immutable snapshot. A self-consistent manifest without this external revision check is insufficient. +2. **Only the manifest decides the gate.** A PR passes only for a verified, current-base-and-head, gate-eligible `TargetedComplete` or explicit `NoEvidenceRequired` claim. `NoEvidenceRequired` is not a synonym for a skipped job. Missing producer, resource, obligation, required artifact, cleanup, or envelope state produces no complete claim and a failed gate. A release pipeline requires `ReleaseComplete` with release eligibility; a PR check cannot reinterpret a targeted claim as release complete. Policy selects the candidate profile from the diff; trusted event context separately determines whether that profile may issue a PR or release claim. +3. **The trusted control plane is base-owned.** The workflow, policy, host registrations, runner, and envelope verifier come from the protected base/trusted-tool revision. The head is only the subject under test. No subject file can choose a command, image, mount, token, network capability, producer, or artifact root. +4. **Fork and other untrusted inputs remain observational.** They receive no privileged capability or complete claim. The required check fails until reviewed content is promoted to a trusted same-repository branch and a new PR-eligible run evaluates that exact promoted head. A manual `workflow_dispatch` report alone cannot satisfy the PR's required check. +5. **The reference proves all AppSurface-selected profiles.** The host must actually run every producer/resource required by the checked-in AppSurface policy, including its non-mutating release profile. Unsupported profile or missing registration fails closed; YAML never silently downgrades the profile. + +## Cross-Model Perspective + +A fresh `combo/sub` review supported a base-owned evidence path but challenged the original claim that a policy, diff, and plan digest alone identify the tested change. It observed that two revision pairs can yield the same normalized paths and that a GitHub event's merge checkout can differ from the requested head. We accepted the challenge: exact base/head identities and the captured diff-byte digest belong in the plan and manifest contract, and CI must independently regenerate the diff before execution. The reviewer also suggested a trusted manual rerun for forks; GitHub's required-check rules make that insufficient as a PR gate, so promotion to a same-repository branch is the explicit path. + +## Approaches Considered + +- **A — Narrow live PR gate (M; about 2–4 human days / 4–8 agent hours).** Gets coverage and no-evidence cases live sooner, but leaves resource-backed and release-profile completeness unproved. Rejected because the selected reference would still demonstrate only the easy branch of EvidenceHost. +- **B — Complete AppSurface EvidenceHost gate (L; about 1–2 human weeks / 1–2 agent days). Selected.** Builds one revision-bound runner and explicit AppSurface host registrations, exercises every policy-selected profile, then makes the PR check required after live proof. The extra work is concentrated in real host execution and trust isolation. +- **C — Versioned reusable workflow (XL; about 2–3 human weeks / 3–5 agent days).** Adds a public consumer input/output and compatibility surface before the first live adopter. Deferred until AppSurface's own path is stable. + +## Recommended Approach + +### 1. Capture and bind the exact change + +The PR controller reads the event's target-base tip and head SHA as data, validates full commit IDs, fetches both objects by SHA, and computes a fixed-options `git diff` between them. It records the source bytes once in a bounded file, independently regenerates the same bytes from the fetched objects, and fails if they differ. The comparison is deliberately the explicit pair rather than an implicit checkout, merge commit, or ambient Git state. This may select extra work when the base advances; that is a conservative cost, never a missing-evidence shortcut. The ordinary build workflow remains responsible for merge-commit compatibility. The plan also records the PR number, target-base tip, workflow/run identity, and head SHA as bounded provenance fields, but these are not substitutes for Git object verification. Immediately before the final verdict, the controller rereads the PR's current target-base tip and head via the GitHub API and rejects either mismatch as stale; a completed run is never retroactively reinterpreted for a new pair. + +Extend the versioned Evidence contracts and the [CLI](../../Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs) with authoritative `--base-revision`, `--head-revision`, and `--diff-file` inputs. A new schema version records `SourceDiffDigest` separately from the existing normalized `DiffDigest`; plan and manifest digests cover both revisions and both digests. `explain`, `run`, and `verify` use the same canonical plan identity. Gate mode rejects path-only input, abbreviated SHAs, missing Git objects, a mismatched source diff, stale policy, or a head changed since the event. Local non-gate CLI use can keep its existing path/diff ergonomics and must not imply gate eligibility. Publish the schema migration and compatibility rules in the [Evidence contract reference](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md) and [EvidenceHost guide](../../guides/evidencehost-cookbook.md). + +### 2. Execute a closed AppSurface policy in one host + +Check in an AppSurface policy whose every repository path is accounted for by an explicit rule or conservative fallback. It distinguishes docs-only `NoEvidenceRequired` from code/coverage, resource-backed integration, and non-mutating release profiles. Renames evaluate both sides; deletions and mixed docs/code changes cannot collapse to docs-only. Policy selects only named, base-registered resources, producers, obligations, assertions, and artifact slots. A release profile runs only in a protected release context; selecting it in a PR context fails as an event/profile mismatch rather than issuing a release claim. + +A dedicated AppSurface host runner composes the [EvidenceHost bootstrap](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/EvidenceHostBootstrap.cs) with explicit first-party registrations. It invokes the extracted coverage core through its existing seam, provisions disposable required resources through Aspire adapters, and runs the selected AppSurface integration and package/release evidence as typed producers with bounded readiness, execution, artifact, and cleanup behavior. It does not treat existing separate workflow job conclusions as producer results. The host owns one manifest even on producer failure where the contract permits one. A missing registration or resource returns an incomplete/invalid manifest and nonzero gate exit. Any capability that AppSurface cannot run safely stays outside the policy until a concrete, tested producer exists; the conservative fallback cannot declare it satisfied. + +For the protected release invocation, the subject is the peeled commit of a protected annotated release tag, not the workflow's ambient checkout or a user-supplied branch name. The trusted release verifier reads the tag object and commit from Git, checks the tag/version against the existing protected release-publish validation, and records the tag object ID, peeled commit, comparison-base commit, and SHA-256 of each policy-declared release package or archive in the plan and manifest. A package producer hashes the exact output it verified; publishing may consume only those digest-matching artifacts if the claim is used to authorize publication. A changed tag, rebuilt artifact with different bytes, missing declared artifact, or mismatched release event invalidates `ReleaseComplete`. Release policy still selects the candidate profile from the explicit comparison-base/tag-commit diff; the protected event and artifact checks grant release eligibility separately. + +### 3. Separate trusted control and subject execution + +The PR workflow uses a base-owned, PR-eligible trigger such as `pull_request_target` only after a live pilot verifies event availability, check association with the PR's current head, and repository event policy. It uses pinned actions, minimal read permissions, `persist-credentials: false`, no secrets, and separate read-only trusted-tool and subject checkouts. The supported runner is an ephemeral GitHub-hosted VM. The trusted controller runs outside a rootless OCI subject container pinned by image digest. The container receives only a read-only subject source mount and a dedicated writable scratch mount. It has a non-root UID, read-only root filesystem, dropped capabilities, no-new-privileges, bounded CPU/memory/PIDs, and no token, Docker/Podman socket, host home, trusted-tool mount, or runner credential files. For a profile without dependencies it has no network; a resource-backed profile uses a per-run internal network with only its declared disposable services and explicit egress denial, including denial of the host gateway and cloud metadata endpoint. Trusted code starts the container with argument arrays, validates its exit status and declared artifacts copied out of scratch, and treats all subject output as untrusted data. The base-owned envelope verifier checks this exact mount/network/capability configuration, runner class, root identities, subject/trusted revisions, and capability evidence immediately before resource provisioning. Inputs from PR titles, paths, or head files are never interpolated into shell commands. If the runner cannot enforce these properties, trusted claims are disabled. + +The controller owns resource labels and an external supervisor process, independent of the EvidenceHost process, with a per-run 10-minute cleanup deadline. Normal `finally` cleanup and an `if: always()` CI step ask the supervisor to stop containers/services, remove the per-run network and scratch data, and attest completion; failed or timed-out cleanup prevents a complete claim. A forced EvidenceHost-process kill is tested with the supervisor still alive and must converge within the declared deadline. If the entire VM is lost, no final manifest/check success can be issued, and its local-only resources die with the ephemeral VM; provider VM-destruction latency is outside the 10-minute claim. Persistent/self-hosted runners and external shared resources are unsupported until they have a separately demonstrated external reaper. + +For fork or otherwise untrusted heads, the workflow may emit a bounded observation report from a dependency-free safe subset; it always records `ObservationOnly` and exits the required gate nonzero. Maintainers can review and promote an exact commit to a same-repository branch, then run the normal PR path on a replacement or updated PR. The fork PR's observation does not become green by approval label or manual dispatch. If GitHub's policy prevents the intended PR trigger or attaches its check to the wrong revision, rollout stops before ruleset activation; use a separately designed base-owned PR-eligible check publisher rather than weakening the trust boundary. + +### 4. Derive one bounded output and turn it into a gate + +After host completion, verify the manifest against the captured plan, source diff, policy, selected profile, artifact hashes, trust envelope, and current PR head. One renderer produces the terminal verdict, GitHub step summary, and machine JSON from that verified result. It prints claim kind, eligible gate, profile/rule rationale, base/head short IDs, selected/closed/missing obligation IDs, and stable diagnostic codes; it never prints secret values, raw producer logs, arbitrary file contents, or unbounded changed-path lists. It truncates and counts long collections deterministically and stays below GitHub's [1 MiB step-summary limit](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-commands). Artifact upload and summary writing are presentation steps, not verdict sources; an upload failure cannot turn an incomplete run green. A pre-plan validation failure emits a bounded diagnostic and failed status without inventing a manifest. + +The gate job has a stable name, runs on PR `opened`, `synchronize`, `reopened`, `ready_for_review`, and base-target `edited` events without path filters or job-level skipping, and explicitly exits nonzero for `None`, `ObservationOnly`, invalid, incomplete, stale, cancelled, or wrong-scope claims. This avoids GitHub's [skipped-job success semantics](https://docs.github.com/en/pull-requests/reference/status-checks). Keep the existing build/test checks while the new gate runs in observation mode. After successful same-repository, docs-only, failing, and fork PR pilots prove the check attaches to the current PR head, add that exact check to the default-branch ruleset with [strict required-check freshness](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-rulesets/available-rules-for-rulesets). When the target base advances after a run, GitHub must block merging until the PR branch is updated; that head update emits `synchronize` and a new base/head-bound check. The live pilot must prove this behavior, including a base update while the head is unchanged, before enforcement. If merge queue is adopted, add `merge_group` support and revalidate before queue activation. A manual release invocation uses the same runner and release-specific verifier but is never counted as the PR's required check. + +## Open Questions + +- Which concrete AppSurface integration and package/release assertions can be safely executed inside the first host? The implementer must inventory the current [build](../../.github/workflows/build.yml), [package gate](../../.github/workflows/package-gate.yml), and [release contract](../../.github/workflows/release-contract.yml) workflows and name each policy obligation before wiring the host. Missing capability blocks that profile's promotion; it does not become an empty success. +- Does the live GitHub event policy permit the selected base-owned PR trigger, and does its named check satisfy the current-head required-check rule in this repository? This is a rollout experiment, not an assumed platform guarantee. + +## Success Criteria + +1. On a live AppSurface PR, `explain` and `run` report the same plan digest for verified base/head/diff/policy inputs; altering any one makes the gate fail before a complete claim. A new head causes a new run; a base update makes the strict required check stale until the head is updated and rerun. The final verifier checks both current SHAs, so an old manifest cannot satisfy either new revision. +2. Docs-only, code, mixed/renamed/deleted, resource-backed, and release fixtures select their candidate profiles solely from policy; trusted PR or protected release context separately determines claim eligibility. Docs-only produces explicit `NoEvidenceRequired`; unrecognized paths select the conservative profile or fail. +3. Positive host runs yield verified `TargetedComplete` or `ReleaseComplete` claims as appropriate. Injected missing producer, unavailable resource, failed assertion, absent required artifact, cleanup failure, or envelope mismatch yields no complete claim and a failed gate. Release fixtures also prove tag-object/peeled-commit and package-digest binding against the protected release invocation. Fork/untrusted runs yield `ObservationOnly` and a failed required check. +4. Terminal, GitHub summary, and manifest agree on the claim and missing obligations. Secret canaries and oversized/malicious paths do not leak or exceed output limits. Normal cancellation and a forced host-process kill clean up the disposable topology within the in-VM 10-minute bound; entire-VM loss yields no complete claim and leaves no shared resource. +5. A real PR demonstrates the stable evidence check on the current head, a base-advance freshness block, and the default-branch ruleset requires it with strict freshness. The repository can merge a qualifying trusted PR and blocks an incomplete or fork-observation PR. Existing checks remain green, formatting and changed-code branch tests pass, and solution coverage is run when practical. + +## Distribution Plan + +Deliver the reference as a checked-in AppSurface workflow, policy, explicit host runner, versioned Evidence contract/CLI changes, and an [EvidenceHost adoption guide](../../start-here/evidencehost.md). A consumer starts by copying the documented checkout/policy/runner pattern and replacing the explicit host registrations; it must prove completeness of every selected test profile before enforcing its own required check. The existing AppSurface package release pipeline publishes the contract and CLI changes. The CI workflow runs on PRs; the protected release pipeline invokes its release profile. No deployment or automatic release is introduced here. + +## Dependencies + +[#775](https://github.com/forge-trust/AppSurface/issues/775) supplies the current contract and coverage seam. The GitHub required-check rollout depends on a live PR pilot and a repository administrator updating the active default-branch ruleset. An AppSurface resource-backed and release producer inventory is needed before those profiles can become required. The older [EvidenceHost contract-first design](appsurface-evidencehost-contract-first.md) remains the architecture source for consumer-owned hosts and trust-envelope semantics. + +## The Assignment + +Take one real AppSurface PR that changes code and record its exact target-base tip, head SHA, and selected policy profile. Use it as the pilot fixture for verifying that the planned base-owned check reports against the current head before asking an administrator to make the check required. + +## Next Steps + +1. Inventory existing AppSurface CI evidence and write the complete checked-in policy/registration matrix; identify any selected profile that lacks a safe producer. +2. Add revision/source-diff binding to contracts, CLI, planner, verifier, and documentation; test deterministic identity and tampering/compatibility cases. +3. Implement the explicit AppSurface host runner and typed producers, then prove complete and failure branches including resource, cleanup, and release envelope behavior. +4. Add the base-owned PR workflow and protected release invocation, bounded renderer, fork observation path, and trust-isolation tests. +5. Pilot real PR check association and event policy; only then enable the exact required check in the ruleset and document the consumer adoption path. + +## What I noticed about how you think + +- You answered “AppSurface CI gates” when asked for the first proof. That makes this a real repository behavior, with branch protection as the finish line. +- You chose the stricter fork outcome: observation can inform review, but it cannot silently satisfy a required evidence check. +- You accepted the second opinion's revision-binding challenge and chose the complete EvidenceHost path. The design now has to prove the exact tested change and the harder resource/release branches, not just produce a polished YAML example. + + +## Reviewer Concerns + +Disposition: CONCERNS_RECORDED + +Stop: CONVERGENCE + +### R2-1 — completeness + +**Problem** + +> The release plan records a comparison-base commit, but the design does not define which trusted revision supplies that base or how the release event binds to it. Since policy selects the release profile from the tag-commit diff, different baselines can select different obligations while still producing a revision-bound manifest. + +**Remedy** + +> Define a deterministic, trusted source and selection rule for the release comparison base, bind that base to the protected release event, and test missing, changed, and mismatched baseline cases before allowing a ReleaseComplete claim. + +### R2-2 — completeness + +**Problem** + +> The design says a changed tag invalidates ReleaseComplete, but it does not specify a final check of the tag ref/object (or an enforced immutability guarantee) between evidence capture, verdict issuance, and publication use. A tag that moves after capture could leave a claim authorizing artifacts for a commit the release tag no longer identifies. + +**Remedy** + +> Require the trusted verifier to recheck the protected tag ref, tag object ID, and peeled commit immediately before issuing ReleaseComplete and before any publication consumes the claim, or specify and verify an equivalent immutable-tag guarantee; include a retagging race test. + +### R2-3 — feasibility + +**Problem** + +> The subject can write arbitrary content to scratch, and trusted code copies declared artifacts out, but the copy-out boundary has no path-containment, file-type, or size rules. A malicious subject could use symlinks or special files to make the trusted copier escape scratch or process unbounded data, undermining the stated isolation boundary. + +**Remedy** + +> Specify a no-follow extraction protocol that accepts only normalized relative paths resolving inside scratch and regular files, enforces per-file and aggregate count/size limits, and tests traversal, symlink, special-file, and oversized-artifact cases. + +### Prior finding evidence + +**R1-3 → R2-3 (persisting)** + +> Recommended Approach 3 specifies the ephemeral VM, rootless OCI container, mounts, credential/socket exclusions, resource network and egress limits, and envelope checks, but only says declared artifacts are copied from subject-writable scratch; it does not constrain that transfer so it cannot follow paths outside scratch or expose trusted host data. See R2-3. + + + +- Preserve the approved AppSurface-only EvidenceHost gate and its existing PR, fork, resource, release, documentation, and rollout requirements; no generic reusable workflow or deployment scope is added. +- For release policy selection, use the canonical V2 release-evidence `ContentSourceCommit` as the sole comparison-base commit. Read and validate it from the tag-bound prepared artifacts through `ReleaseTaggedProjectionResolver`; require a full canonical commit ID, existence in Git, ancestry to the peeled tag commit, and agreement with the protected release invocation's validated version, tag, and base branch. Bind the commit and source-diff digest into the release plan and manifest. Missing, invalid, non-ancestor, or changed preparation-base evidence fails before `ReleaseComplete`; test each case and a forged alternate base. +- The trusted verifier must reread the remote protected tag ref, annotated tag object ID, and peeled commit immediately before `ReleaseComplete` and again immediately before a publisher consumes that claim. Each must equal the plan's captured identity; a retag or missing tag fails closed. Test a tag move between capture and verdict and between verdict and publication. +- Copy subject artifacts from scratch with a no-follow, descriptor-relative extraction protocol. Allow only normalized relative declared paths resolving within scratch and regular files; reject symlinks, hardlink ambiguity, devices, FIFOs, sockets, traversal, duplicate/case-colliding names, and files changed during reading. Enforce documented file-count, per-file, aggregate-byte, and time limits before hashing/copying. Test traversal, symlink, special file, oversized file, count/aggregate overflow, and mutation races. Never use a shell `cp` or tar extraction as this trust-boundary operation. +- Before implementation, inventory each policy profile and prove its named producer, disposable resource, assertion, cleanup and artifact slot against the current workflows. A profile with a missing safe producer remains fail-closed and cannot be required or promoted. Keep the policy and registration matrix as a reviewable deliverable. +- Stage rollout so the new check first runs in non-required observation mode on same-repository, docs-only, failure, base-advance, and fork pilot PRs. Verify head association and event availability, then require the exact stable check with strict freshness. Preserve the existing checks. Document the ruleset activation, stop/rollback procedure, and admin owner. +- Set checked-in AppSurface extraction limits for the first runner: at most 64 declared regular artifacts, 256 MiB per file (also constrained by each slot's `MaximumBytes`), 512 MiB aggregate copied bytes, and 120 seconds total extraction time. Apply whichever per-slot or runner limit is lower. Reject before allocation when declared bounds already exceed a limit, and enforce streamed read-time bounds; changes to these limits require a reviewed policy/runner change and matching boundary tests. +- Rollback trigger: a claim attached to the wrong SHA, a false complete claim, subject isolation/credential exposure, cleanup failure, unavailable PR event, or a ruleset-induced block of otherwise qualifying PRs. For gate correctness or availability failures without suspected isolation or credential exposure, the repository administrator removes only the new exact check from the active ruleset to restore pre-gate merge eligibility for in-flight PRs after GitHub applies the ruleset; disable the workflow if continued execution is unsafe. For suspected isolation or credential exposure, follow the immediate contain/cancel sequence below before the ruleset change. Confirm existing checks still govern, document affected PRs/runs, fix root cause, rerun the full same-repository/docs/failure/fork/base-advance pilot, and re-enable the required check only after observed head association and freshness pass. +- Treat the office-hours 1–2 human-week / 1–2 agent-day effort line as a provisional comparison among approaches, not a delivery commitment. Re-estimate after the policy/producer inventory, with separate contract/CLI, host/isolation, release, live-pilot, and administrator-activation milestones; the latter two depend on GitHub event policy and administrator availability. +- For suspected subject isolation or credential exposure, disable/contain the new workflow so no new subject runs start, cancel active runs, then have the administrator remove the exact required check from the ruleset to restore prior merge behavior. For other gate correctness/availability failures, remove the required check promptly and disable the workflow if continued execution is unsafe. Record affected runs and preserve existing checks. Re-enable only after a root-cause fix, a trigger-specific regression proof (including envelope, resource, release, or cleanup branch as applicable), the full same-repository/docs/failure/fork/base-advance live pilot, and administrator verification of head association and strict freshness. +- Map every rollback trigger to re-enable proof: wrong-SHA attachment requires a controlled head/base update and current-head check-association assertion; false-complete claim requires injected missing obligation/failed assertion plus a nonzero gate assertion; isolation or credential exposure requires a hostile subject probe for mount, token, socket and network denial plus cancellation proof; cleanup failure requires supervisor kill/timeout injection and incomplete claim; unavailable PR event requires a live event-policy and check-attachment pilot; ruleset blocking a qualifying PR requires a live docs-only and code PR that pass the exact check under strict freshness. Release-related triggers additionally require retag/rebuilt-artifact regression. Record links to each proof in the rollout log before administrator re-enables the check. +- Treat changes to the base-owned workflow, policy, runner, envelope verifier, and host registrations as control-plane changes. The current trusted controller must classify these paths conservatively, require the old policy's obligations, and validate the proposed policy as data against old-versus-new selection fixtures for docs/code/rename/deletion/resource/release and unrecognized paths. A shadow run of the proposed controller/host in an unprivileged, non-claiming envelope must pass before merging; the proposed files cannot be trusted by their own PR run. Require explicit maintainer review of any reduced obligation or changed trust capability, a post-merge smoke run before continued enforcement, and a regression where deletion/weakening of a rule cannot let its own PR pass under the old gate. +- Use `ReleaseTaggedProjectionResolver`'s validated tagged projection and V2 evidence bundle as the sole source of the release preparation base. Verify the bundle's subject digest covers the V2 preparation-base commit, the V2 release manifest `PreparationBaseCommit` agrees, the annotated tag's `AppSurface-Release-Evidence-Subject-Sha256` trailer matches that digest, and the protected release invocation validates version/tag/base-branch reachability. Bind the validated bundle digest, tag object ID, peeled commit and preparation-base commit into the evidence plan. Reject a raw or alternate-ancestor field even if it is a valid Git ancestor; test forged prepared evidence, mismatched manifest source, and mismatched tag trailer. +- In the policy/registration matrix, name each existing workflow obligation's canonical command or implementation, whether EvidenceHost calls that exact seam, which old job remains necessary after activation, and expected steady-state ownership. During the pilot compare duplicate result and runtime; do not remove an existing required job until equivalent branch/failure behavior is proven and a separate migration is reviewed. +- Keep fork `ObservationOnly` and same-repository promotion as the approved gate behavior. The pilot records the number of fork PRs, maintainer promotion steps and elapsed turnaround, and the runbook documents the exact SHA promotion path. A base-owned external check publisher is a future separate design if that measured cost justifies it; it cannot silently upgrade the observation claim in #777. + + + + +- Put a revision-bound AppSurface gate quickstart on the [EvidenceHost start page](../../start-here/evidencehost.md), linked from the repository and CLI entry points. It must use a checked-in policy, one maintained fixture with two full commit IDs and exact diff bytes, and copyable `appsurface evidence explain` commands with expected profile, rationale, obligations, source-diff digest and plan digest. State prerequisites and distinguish the local `--path` sample from gate-eligible evidence. The chosen first-result clock runs from a normal checkout with the CLI installed to that verified explanation; target 2–5 minutes, measured in a fresh maintainer rehearsal. Report full producer/CI runtime separately. +- Define the gate input contract for `explain`, `run`, and `verify` in the CLI and contract references: both full `--base-revision` and `--head-revision` plus `--diff-file` are required together for a revision-bound PR candidate; missing/mixed/abbreviated inputs, absent Git objects, or bytes that fail independent diff regeneration are errors. A local path/diff plan remains usable but cannot claim gate eligibility. Document how the trusted controller supplies its immutable snapshot, how the host executes selected resource-backed producers, and which fields and plan digest the three commands must agree on. Show real command/output templates for a docs-only and a code fixture, with no implication that local `explain` alone can satisfy GitHub's required check. +- Give every gate diagnostic a stable code and a bounded human message with the observed identifier, what failed, likely cause, next action and a nearby link to its canonical reference or troubleshooting section. Demonstrate at least stale base/head, source-diff or plan mismatch, missing producer/resource, unsafe artifact, isolation-envelope failure, cleanup failure, and moved release tag. Keep terminal, summary and machine JSON codes consistent while never printing raw subject output or credentials. Test that the guidance is accurate for those injected branches and that long/malicious values remain bounded. +- Add one tested end-to-end AppSurface adoption walkthrough in the [cookbook](../../guides/evidencehost-cookbook.md): policy rule and explicit registration, local explain, host run, manifest verify, expected claim/verdict, then live check and strict-freshness pilot. Name which code is the reusable contract/CLI and which is AppSurface's reference runner. Include the exact-SHA same-repository promotion procedure for a fork and the fact that its original observation remains ineligible. Link the policy/producer matrix and the operator rollback guide. +- Publish a versioned v1-local to revision-bound gate migration table covering schema compatibility, plan/manifest identity changes, CLI input rules, and what old consumers must change or can keep. Separate consumer-tailorable policy/profile/registration/diagnostic display choices from fixed trust invariants: independent Git diff verification, base-owned authority, complete obligations, isolation, bounded extraction, cleanup attestation, and fresh PR/tag checks. Test the documented fixture and examples against the built CLI and host before enabling the required check. +- Measure and record the selected 2–5 minute first-result journey with a fresh maintainer starting at the documented start page; include discovery, commands, errors and reading the useful explanation. Separately record local full profile execution time, live PR gate latency, fork-promotion effort, and duplicate existing-CI time during the pilot. Treat these as rollout observations, not new telemetry infrastructure or an automatic release gate. + + + +- Preserve the complete AppSurface-only gate and non-mutating release reference, but place the base-owned controller/verifier and untrusted subject execution on separate ephemeral GitHub-hosted job VMs. The subject job has `permissions: {}`, no secrets or OIDC permission, no persisted checkout credential, and receives only the exact captured subject tree and bounded plan data; it never receives the trusted policy/runner as writable input. A private same-workflow artifact handoff carries bounded result bytes, not a generic cross-job aggregation API. The verifier treats every subject result and artifact as untrusted, independently recreates the plan from the base-owned policy and exact Git objects, validates run/job provenance, complete obligations, artifact hashes and cleanup, then performs fresh PR-head/base checks before its stable required-check verdict. No subject job or artifact can directly set that verdict. Pilot actual current-head association and event-policy availability before enforcement. Keep the OCI boundary inside the unprivileged subject VM and hostile-probe it; an inability to enforce it prevents a complete claim. +- Specify one versioned, byte-exact Git change protocol for the gate. Fetch and resolve full commit object IDs into a trusted bare/object-only checkout; invoke Git with argument arrays, pinned runner Git version, neutral trusted configuration, disabled external diff/textconv/color and fixed rename/submodule/binary options. Retain a bounded exact source diff for its digest, and derive selection paths separately from a NUL-delimited `git diff --name-status -z` representation of the same objects. Parse statuses and both rename/copy paths, including mode-only, symlink, binary and submodule changes; reject malformed/truncated/invalid-UTF-8/unrepresentable records rather than selecting an empty profile. Independently regenerate both representations before verdict. Enforce an initial 20 MiB source-diff cap, 10,000 changed records and 4 KiB path-byte cap, or revise these only through a reviewed policy/runner limit change. Test unusual names, zero diff, mixed changes, renames, deletions, type/mode-only and submodule records, oversized input and object/ref races. +- Do not let the v1 `EvidencePlanner` mixed-profile fallback erase a resource or producer obligation. For every trusted PR policy, validate that its conservative profile contains every producer, resource, assertion, artifact and obligation required by each targeted profile it may replace; an incompatible policy is invalid before any run. Test docs+code, docs+resource, resource+code, rename across classes, unknown path and control-plane changes for superset closure. Give legitimate release-preparation PRs a targeted PR profile while the protected release invocation selects its non-mutating release profile from its validated preparation-base/tag diff. If one policy cannot express both contexts without letting an event choose a profile in YAML, use a base-owned, versioned PR/release policy pair selected only by validated event kind; each policy still resolves its candidate profile from its exact diff and both digests enter the plan. An event/profile mismatch always fails. +- Treat the current self-consistency-only `EvidenceManifestBuilder.Verify` and CLI `verify` as necessary but insufficient for a CI authorization. Add a trusted gate verifier that checks the base-owned policy digest, independently regenerated Git diff and status set, immutable plan identity, subject-job provenance, execution envelope and external fresh GitHub/tag identity. Legacy v1 local claims retain documented compatibility but never authorize the new required check merely because their manifest says `PullRequestGate`. Test a fully recomputed forged plan/manifest, wrong policy source, wrong subject job, moved base/head/tag and a valid local-only manifest that the external gate rejects. +- Reuse `ReleaseTaggedProjectionResolver` as the sole release-evidence authority without copying its parser into the new host. Because it is currently internal to a non-packable release executable, expose a narrow, versioned, read-only machine result from the existing `inspect` path containing the validated V2 preparation base, evidence bundle digest, tag object ID and peeled commit, or extract that exact validation seam into a private shared assembly used by both callers. Prove identical success/failure behavior in the release tool and EvidenceHost. A release claim remains non-mutating; any future publisher that consumes it must verify tag immutability for the publication lifetime and use only artifacts bound to the captured object and digests. Without that protection, the claim cannot authorize publication. Test a tag move after the last pre-publication read as well as the two earlier race windows. +- Make dependency supply part of the subject envelope: use a pinned, base-owned SDK/OCI image and reviewed immutable package cache or controlled allowlisted mirror, with locked dependency integrity checks. Restore and all head-controlled build hooks run only inside the unprivileged subject boundary; cache misses, lock mismatches or mirror failure yield unavailable/incomplete evidence, never trusted-host restore or silent network expansion. Pilot a cold-cache run and a dependency-changing PR, and record the image/cache refresh path in the policy matrix. +- Give each policy-selected profile a checked-in, measurable maximum: capture/planning, resource readiness, producer execution, API retry, cleanup and total workflow deadlines. The total job deadline must leave room for the independent 10-minute cleanup and final verification; reject a policy whose declared worst-case work exceeds it. Cancel stale same-PR runs on a new head while allowing their supervisor cleanup to finish; do not cancel another PR's run or mark a cancelled run complete. Test overlapping pushes, a push during cleanup, unavailable/rate-limited GitHub API, each cancellation phase and a stuck producer. Set final numeric budgets after the producer inventory and before any required-check activation, using observed pilot duration rather than an arbitrary promise. +- Keep shadow control-plane validation entirely base-owned: the old trusted controller supplies the harness, path classifier, fixtures and expected outcomes. Subject changes to policy, workflow, runner, host registrations or test fixtures are data to that harness, never authority. Test deleted/weakened rules, edited/removed fixtures and an unrecognized control-plane path; each remains subject to the old obligations. New controller code runs only in an unprivileged non-claiming shadow and becomes authoritative after merge plus smoke proof. +- Preserve the already approved descriptor-relative extraction boundary, but do not route untrusted scratch paths through the current `EvidenceArtifactWriter`'s path-based write or `ReadAllBytes` verification. Stream no-follow copies into a private trusted root, hash bytes as copied, reject mutation and enforce both per-slot/per-producer v1 limits and the runner's 64-file/256 MiB per-file/512 MiB total/120-second caps. Extend the writer/verifier through a narrow streaming seam if necessary; document the lower applicable limit and test 256 MiB memory behavior without allocating entire artifacts. + +## Review record + + +- Preserve the approved AppSurface-only EvidenceHost gate and its existing PR, fork, resource, release, documentation, and rollout requirements; no generic reusable workflow or deployment scope is added. +- For release policy selection, use the canonical V2 release-evidence `ContentSourceCommit` as the sole comparison-base commit. Read and validate it from the tag-bound prepared artifacts through `ReleaseTaggedProjectionResolver`; require a full canonical commit ID, existence in Git, ancestry to the peeled tag commit, and agreement with the protected release invocation's validated version, tag, and base branch. Bind the commit and source-diff digest into the release plan and manifest. Missing, invalid, non-ancestor, or changed preparation-base evidence fails before `ReleaseComplete`; test each case and a forged alternate base. +- The trusted verifier must reread the remote protected tag ref, annotated tag object ID, and peeled commit immediately before `ReleaseComplete` and again immediately before a publisher consumes that claim. Each must equal the plan's captured identity; a retag or missing tag fails closed. Test a tag move between capture and verdict and between verdict and publication. +- Copy subject artifacts from scratch with a no-follow, descriptor-relative extraction protocol. Allow only normalized relative declared paths resolving within scratch and regular files; reject symlinks, hardlink ambiguity, devices, FIFOs, sockets, traversal, duplicate/case-colliding names, and files changed during reading. Enforce documented file-count, per-file, aggregate-byte, and time limits before hashing/copying. Test traversal, symlink, special file, oversized file, count/aggregate overflow, and mutation races. Never use a shell `cp` or tar extraction as this trust-boundary operation. +- Before implementation, inventory each policy profile and prove its named producer, disposable resource, assertion, cleanup and artifact slot against the current workflows. A profile with a missing safe producer remains fail-closed and cannot be required or promoted. Keep the policy and registration matrix as a reviewable deliverable. +- Stage rollout so the new check first runs in non-required observation mode on same-repository, docs-only, failure, base-advance, and fork pilot PRs. Verify head association and event availability, then require the exact stable check with strict freshness. Preserve the existing checks. Document the ruleset activation, stop/rollback procedure, and admin owner. +- Set checked-in AppSurface extraction limits for the first runner: at most 64 declared regular artifacts, 256 MiB per file (also constrained by each slot's `MaximumBytes`), 512 MiB aggregate copied bytes, and 120 seconds total extraction time. Apply whichever per-slot or runner limit is lower. Reject before allocation when declared bounds already exceed a limit, and enforce streamed read-time bounds; changes to these limits require a reviewed policy/runner change and matching boundary tests. +- Rollback trigger: a claim attached to the wrong SHA, a false complete claim, subject isolation/credential exposure, cleanup failure, unavailable PR event, or a ruleset-induced block of otherwise qualifying PRs. For gate correctness or availability failures without suspected isolation or credential exposure, the repository administrator removes only the new exact check from the active ruleset to restore pre-gate merge eligibility for in-flight PRs after GitHub applies the ruleset; disable the workflow if continued execution is unsafe. For suspected isolation or credential exposure, follow the immediate contain/cancel sequence below before the ruleset change. Confirm existing checks still govern, document affected PRs/runs, fix root cause, rerun the full same-repository/docs/failure/fork/base-advance pilot, and re-enable the required check only after observed head association and freshness pass. +- Treat the office-hours 1–2 human-week / 1–2 agent-day effort line as a provisional comparison among approaches, not a delivery commitment. Re-estimate after the policy/producer inventory, with separate contract/CLI, host/isolation, release, live-pilot, and administrator-activation milestones; the latter two depend on GitHub event policy and administrator availability. +- For suspected subject isolation or credential exposure, disable/contain the new workflow so no new subject runs start, cancel active runs, then have the administrator remove the exact required check from the ruleset to restore prior merge behavior. For other gate correctness/availability failures, remove the required check promptly and disable the workflow if continued execution is unsafe. Record affected runs and preserve existing checks. Re-enable only after a root-cause fix, a trigger-specific regression proof (including envelope, resource, release, or cleanup branch as applicable), the full same-repository/docs/failure/fork/base-advance live pilot, and administrator verification of head association and strict freshness. +- Map every rollback trigger to re-enable proof: wrong-SHA attachment requires a controlled head/base update and current-head check-association assertion; false-complete claim requires injected missing obligation/failed assertion plus a nonzero gate assertion; isolation or credential exposure requires a hostile subject probe for mount, token, socket and network denial plus cancellation proof; cleanup failure requires supervisor kill/timeout injection and incomplete claim; unavailable PR event requires a live event-policy and check-attachment pilot; ruleset blocking a qualifying PR requires a live docs-only and code PR that pass the exact check under strict freshness. Release-related triggers additionally require retag/rebuilt-artifact regression. Record links to each proof in the rollout log before administrator re-enables the check. +- Treat changes to the base-owned workflow, policy, runner, envelope verifier, and host registrations as control-plane changes. The current trusted controller must classify these paths conservatively, require the old policy's obligations, and validate the proposed policy as data against old-versus-new selection fixtures for docs/code/rename/deletion/resource/release and unrecognized paths. A shadow run of the proposed controller/host in an unprivileged, non-claiming envelope must pass before merging; the proposed files cannot be trusted by their own PR run. Require explicit maintainer review of any reduced obligation or changed trust capability, a post-merge smoke run before continued enforcement, and a regression where deletion/weakening of a rule cannot let its own PR pass under the old gate. +- Use `ReleaseTaggedProjectionResolver`'s validated tagged projection and V2 evidence bundle as the sole source of the release preparation base. Verify the bundle's subject digest covers the V2 preparation-base commit, the V2 release manifest `PreparationBaseCommit` agrees, the annotated tag's `AppSurface-Release-Evidence-Subject-Sha256` trailer matches that digest, and the protected release invocation validates version/tag/base-branch reachability. Bind the validated bundle digest, tag object ID, peeled commit and preparation-base commit into the evidence plan. Reject a raw or alternate-ancestor field even if it is a valid Git ancestor; test forged prepared evidence, mismatched manifest source, and mismatched tag trailer. +- In the policy/registration matrix, name each existing workflow obligation's canonical command or implementation, whether EvidenceHost calls that exact seam, which old job remains necessary after activation, and expected steady-state ownership. During the pilot compare duplicate result and runtime; do not remove an existing required job until equivalent branch/failure behavior is proven and a separate migration is reviewed. +- Keep fork `ObservationOnly` and same-repository promotion as the approved gate behavior. The pilot records the number of fork PRs, maintainer promotion steps and elapsed turnaround, and the runbook documents the exact SHA promotion path. A base-owned external check publisher is a future separate design if that measured cost justifies it; it cannot silently upgrade the observation claim in #777. + + + +### CEO Step 0 and decision ledger + +Mode: SELECTIVE EXPANSION, set by autoplan. The user selected option B, the complete AppSurface gate, in office hours. The scope challenge found no beneficial new capability within a one-day agent blast radius: the most important work is closing correctness holes in that approved scope. Generic reusable workflow, self-hosted runners, and automatic publication stay out of scope. The plan is already large; splitting into milestone proof points reduces risk without cutting the accepted outcome. + +Real problem: AppSurface has planning and manifest contracts but no live required check proving policy-selected evidence for exact revisions. A green example without a required check solves only a proxy. Do nothing leaves CI decisions in YAML and the trust claim unproven. + +Existing leverage: `EvidencePlanner` and contracts handle policy/profile selection and manifest identity; `EvidenceHostBootstrap` handles explicit registrations; the extracted coverage core is reusable; `ReleaseTaggedProjectionResolver` already validates annotated tags and V2 preparation-base ancestry; release-publish and package-gate workflows define candidate assertions. No new general scheduler is warranted. + +12-month path: local planner and ad hoc CI -> one versioned, revision-bound AppSurface runner with a required check -> copied, documented adopter pattern once this reference has shown real failure modes. This plan creates that path but does not promise compatibility to external consumers yet. + +Complexity check: the baseline spans contracts, CLI, host, policy, runner, workflows, tests and docs, well over eight files. The minimum correct path is still one canonical plan/verifier/renderer and explicit host registrations. Separate controller, untrusted subject and supervisor are necessary at the trust boundary; no additional service or generic plugin registry is proposed. + +Selective-expansion scan: CLI quickstart, sample diagnostics, copyable policy matrix, one-command local rehearsal, summary links, and troubleshooting examples were considered. Only the policy matrix, clear diagnostics and rehearsal guidance already follow from the approved API and adoption requirements; the other polish is deferred until the first pilot shows the actual friction. Platform potential is the versioned evidence identity and reference workflow, not a new public workflow interface. + +| ID and owner | Contract and evidence | Current | Proposed | Status | Exact authority and scope | +|---|---|---|---|---|---| +| C1 CEO | AppSurface-only required EvidenceHost gate; approved office-hours design and #777 | Complete option B | Generic reusable interface | declined | User chose B over C in office hours; preserve B. | +| C2 CEO | Release base must be deterministic; office-hours R2-1, V2 `ContentSourceCommit` | unspecified base | use canonical V2 preparation base | approved | Correctness detail within approved release binding; autoplan P2/P6. | +| C3 CEO | Tag must remain bound at verdict/publication; R2-2 | capture only | final and pre-publish remote ref checks | approved | Correctness detail within approved release eligibility; autoplan P2/P6. | +| C4 CEO | Subject artifact transfer is a trust boundary; R2-3 | copy declared scratch output | descriptor-relative no-follow bounded copy | approved | Security repair within approved isolation; autoplan P2/P6. | +| C5 CEO | Stable required check must be proven live; approved design | pilot then ruleset | retain with explicit rollback owner | approved | Operational detail of already approved rollout; autoplan P6. | + +### CEO scope summary + +10x ambition: a maintainer can see *why* a policy selected a profile, whether every obligation closed, and which exact change was tested, in one bounded verdict. The delight scan found no new feature that improves that proof more than closing the three recorded correctness gaps. + +Accepted scope: approved design plus C2-C5. Deferred: generic reusable workflow, self-hosted runner, automatic publication. Reviewer concerns are R2-1/R2-2/R2-3, now addressed as explicit implementation obligations, pending independent spec verification. + +### CEO review: temporal and strategic result + +The six-month regret would be a required check whose name is stable but whose evidence describes a different revision or a merely self-consistent manifest. The defense is the immutable base/head/source-diff identity, a fresh pre-verdict GitHub read, and live required-check association proof. In a future reusable-workflow phase, the AppSurface policy and host registrations should be replaceable without changing canonical plan identity. No current market comparison changes issue #777's concrete local goal; the risky alternative is shipping a demonstration that cannot block a bad merge. + +**NOT in scope.** A cross-repository reusable workflow, new scheduler, self-hosted runner, external resource reaper, merge-queue support before adoption, automatic publication, and deployment attestation are excluded. They would add contract and operational surface before the AppSurface reference is proven. Existing CI jobs remain independent; their conclusions cannot impersonate EvidenceHost producers. + +**What already exists.** `EvidencePlanner` provides policy selection and normalized path digestion; `EvidenceContracts` holds claim, producer, resource, artifact, plan, and manifest types; `EvidenceHostBootstrap` and Aspire adapters supply explicit host composition; `CoverageExecutionBoundary` is the coverage reuse seam; `ReleaseTaggedProjectionResolver` validates annotated tags and V2 preparation-base ancestry; `release-publish.yml`, `package-gate.yml`, and `release-contract.yml` provide assertion candidates and release context. The new work extends these surfaces rather than rebuilding their logic. + +#### 1. Architecture + +```text +PR event / protected release event + -> trusted base-owned controller -> verified revision pair + source diff + -> policy planner -> immutable plan -> explicit EvidenceHost registrations + -> isolated subject + disposable resources -> bounded artifact extractor + -> manifest verifier + fresh event/tag read -> one verdict renderer -> CI check + external supervisor -> cleanup attestation --^ +``` + +Four paths share that state machine: trusted PR `TargetedComplete`, docs-only PR `NoEvidenceRequired`, untrusted fork `ObservationOnly` with failed required gate, and protected release `ReleaseComplete` with tag and artifact rechecks. Missing event/revision/policy data fails before planning; an empty diff is allowed only when policy explicitly emits `NoEvidenceRequired` for a valid event and revision pair. Producer, resource, artifact, verifier, API, or cleanup failure leads to a bounded incomplete/invalid result and nonzero gate. The only legal progression is `Captured -> Planned -> Running -> CleanupVerified -> ManifestVerified -> FreshnessVerified -> EligibleVerdict`; any failure enters `Failed`, and a stale head/tag cannot transition back to eligible. Re-run from fresh capture. The principal coupling is the versioned plan identity shared by CLI, host, verifier and renderer; that is intentional. At 10x PR volume, disposable container startup and coverage dominate; at 100x, GitHub-hosted runner capacity and API rate limits dominate. No database, cache, or long-lived service is added. Rollback is removal of the required-check ruleset entry by the administrator, then disabling the workflow, while existing build/test checks remain active. + +#### 2. Error & Rescue Registry + +| Method/codepath | Failure / exception class | Rescue action | User sees | +|---|---|---|---| +| Capture revision / Git diff | missing object, malformed SHA, nonzero Git, oversized diff; validation/IO/process failure | fail closed; bounded diagnostic, never invent a manifest | `revision-invalid` / `diff-unavailable` and failed check | +| Policy parse / plan | malformed policy, unmapped path, hash mismatch; parse/contract failure | reject input or conservative policy rule; no silent fallback to docs-only | `policy-invalid` / `plan-mismatch` | +| Host registration / resource readiness | missing producer, startup timeout, unavailable dependency | mark unavailable/incomplete, run supervisor cleanup | named missing obligation and failed check | +| Subject execution | timeout, cancellation, assertion failure, invalid producer output | terminate subject, collect bounded diagnostics, cleanup | stable producer code and failed check | +| Artifact extraction | traversal, symlink, special file, mutation, size/count/time breach | reject artifact, stop extraction, cleanup | `artifact-invalid` and failed check | +| Manifest verification | digest/claim/envelope mismatch | reject claim; no alternate pass source | `manifest-invalid` and failed check | +| Freshness API / release ref read | timeout, 403/404, moved head/base/tag | bounded retry only for transient transport/rate limit, then fail closed; never reuse stale observation | `revision-stale` or `freshness-unavailable` | +| Cleanup supervisor | process loss, timeout, failed deletion | fail claim and invoke CI `always()` cleanup; local VM destruction is the final boundary | `cleanup-incomplete` and failed check | +| Summary/artifact upload | presentation IO/network error | preserve already computed failed verdict; upload cannot upgrade it | diagnostic in job log, gate status unchanged | + +Catch only specific expected process, IO, cancellation, contract and API failures. At every rescue, log run ID, stage, bounded IDs/digests and diagnostic code without raw subject output. Retry only transient API calls with bounded backoff; an invalid plan, unsafe artifact, failed assertion or stale revision is never retried into success. + +#### 3. Security and trust + +Threats are high-impact: untrusted head code escaping the subject container, reading runner credentials, reaching the host gateway, or tricking trusted extraction through a symlink. The base-owned workflow, pinned actions, minimal permissions, no subject token/socket/home, rootless pinned container, isolated network, envelope verification, and descriptor-relative no-follow copy are mandatory. PR title, path and head content are data, never shell or workflow instructions. A fork's observation cannot be promoted by label or manual dispatch. Log only bounded paths and diagnostics; secret canaries belong in tests. GitHub documents that `pull_request_target` uses a trusted base workflow but head checkout/execution is dangerous, so pilot its event/check association and enforce the container boundary before trusting it. No new secret is required. + +#### 4. Data flow and ordering + +```text +event identity -> full-SHA validation -> fetched Git objects -> fixed-options diff + -> source digest + policy digest -> canonical plan -> host result + -> no-follow copied artifacts -> manifest verification -> fresh API/ref read + -> eligible claim -> one bounded terminal/summary/JSON rendering +``` + +Nil/empty/wrong-type event fields, missing objects, invalid UTF-8 or overlong paths, policy conflicts and oversized streams fail at their first validator. Duplicate artifact names, partial writes and read-time mutation fail extraction. The shared invariant is: a successful claim names the exact currently eligible PR base/head or protected tag object and the exact copied artifact bytes. Test both orders of a head update versus final PR read, tag move versus verdict, tag move versus publisher consumption, artifact mutation versus hashing, and supervisor termination versus cleanup status. A fresh consumer must re-read identity; a prior successful manifest is not a reusable authorization token. The same PR event retried under identical inputs yields the same plan digest; a new run ID affects provenance only, not plan identity. + +#### 5. Code quality + +One canonical plan serializer/digest and one verifier should serve `explain`, `run`, and `verify`; no duplicated YAML eligibility rule or separate summary verdict path. Keep host registrations explicit and producer implementations cohesive. Avoid a generic plugin registry, reflection-driven policy binding, broad catch-all exception handling, and complex workflow shell interpolation. Favor typed diagnostics, narrow process wrappers and test seams exposed through internal APIs. + +#### 6. Test diagram + +| Boundary | Positive proof | Failure / edge proof | +|---|---|---| +| Revision and policy plan | same explain/run digest for fixed pair; docs-only and code profiles | changed head/base/source bytes/policy, rename/delete/mixed/unmapped/empty input | +| Host and manifest | selected resource/producer/assertion closes and complete claim | missing registration, unavailable resource, failed assertion, absent artifact, timeout/cancel | +| Isolation and extraction | declared regular artifact copied, hash matches | token/socket/network denial, traversal, symlink/special file, oversize, mutation race | +| Release | canonical V2 base, annotated tag, matching package digest | invalid/missing/non-ancestor/alternate base, retag at two windows, rebuilt artifact | +| Verdict and rollout | one renderer agrees across terminal/summary/JSON; live head-attached check | secret canary, oversized malicious path, fork fails gate, base advance blocks, wrong event/check association | +| Cleanup | normal and forced host-process kill complete within in-VM deadline | supervisor failure/time-out denies complete claim; VM loss issues no success | + +Unit tests should dominate plan parsing, digest, state transition, verifier, renderer and extraction; narrower integration tests cover host/resources, OCI boundary and cleanup; a few live PR pilots cover GitHub event and ruleset semantics. The 2am confidence test is a real code PR with one failed required producer that cannot merge. Hostile QA moves the head/tag after execution and swaps a symlink during extraction. Chaos kills EvidenceHost while the supervisor reaps resources. External GitHub timing is tested by controlled seams locally and observed in the pilot, not asserted through a flaky wall-clock test. + +#### 7. Performance + +Slow paths are coverage/test execution, disposable resource readiness and container startup, not plan hashing. Diff and artifacts require explicit byte/count/time limits and streamed processing; memory must not scale with raw logs or full artifact bodies. No ORM, database index, connection pool, or cache is in scope. Cache only immutable trusted-tool builds keyed by base commit and policy/tool version if a measured pilot warrants it; never cache a complete claim across revision or tag freshness boundaries. CI timeouts should exceed the host deadline plus cleanup and rendering, while bounding total job runtime. + +#### 8. Observability + +Log stage entry/exit, run ID, base/head or tag object short IDs, profile, obligation IDs, claim kind, diagnostic code and cleanup outcome. Never log raw subject stdout, secret values or arbitrary artifact contents. Machine JSON and GitHub summary share the verified verdict so a failed job can be reconstructed from retained bounded metadata. Track gate outcomes by profile and failure code, stale-revision frequency, resource readiness/cleanup duration, and summary truncation. The maintainer runbook maps codes to re-run, fix producer, promote fork commit, or disable required check; no dashboard service is needed for the first reference. + +#### 9. Rollout and rollback + +There is no database migration. First land versioned contracts and migration docs, then host/policy with all selected producers, then a non-required workflow, then pilot same-repo code/docs/failure/fork/base-advance cases. Only a repository administrator can activate the exact check in the ruleset after verifying source/check association and strict freshness. In the first five minutes, inspect one active PR's check name, attached SHA, claim and summary; within the first hour, confirm a base advance and failed/fork PR remain blocked. If wrong-head attachment, unavailable event, unexpected block or unsafe resource behavior occurs, remove the required-check entry immediately, disable the new workflow, and retain existing checks. The release path remains non-mutating and cannot publish merely because it produced evidence. + +#### 10. Long-term trajectory + +Reversibility is 4/5: versioned contracts need compatibility care, but the gate can be disabled without migrating data. The lasting debt is maintaining policy-to-registration parity and an OCI isolation runtime; the matrix, diagnostics and tests make that visible. External adopters may later copy the reference, but a reusable public workflow should wait for a second actual consumer. A new engineer should find the policy matrix, one local rehearsal, the versioned contract reference, and a runbook from the EvidenceHost start page. No accepted cherry-pick creates a new service or public API beyond the already planned contract revision. + +### CEO completion summary + +| Area | Result | Remaining proof | +|---|---|---| +| Premise / scope | AppSurface gate solves the named pain; option B retained | live pilot | +| Architecture / threat | explicit trusted/subject boundary; three prior concerns converted to requirements | OCI enforcement and extraction tests | +| Error / data | fail-closed state machine and rescue registry | implementation and race tests | +| Tests / performance | branch and failure coverage planned; bounded streams | profile inventory and runtime measurements | +| Rollout / trajectory | non-required pilot then admin ruleset; reversible | event/check association and strict freshness | + +### CEO independent spec review history + +First `combo/sub` spec review: 8/10, NOT PASS. It found (1) rollback triggers/actions and re-enable conditions underspecified, (2) extraction bounds lacked concrete values, and (3) the office-hours effort comparison lacked a workstream breakdown. The accepted CEO block now names each trigger and manual rollback, 64/256 MiB/512 MiB/120-second limits, and milestone-based re-estimation. The CEO scope summary and implementation input were refreshed for a second review. + +Second `combo/sub` spec review: 8/10, NOT PASS. It confirmed the numeric limits and provisional milestone estimate, but found that suspected isolation or credential exposure must stop/cancel unsafe runs before administrator ruleset removal, and that re-enabling must prove the triggering failure is fixed. The recorded requirements now distinguish unsafe-run containment from ordinary gate rollback and require a trigger-specific regression plus the full live pilot. A third review checked the corrected inputs and scored 8/10, leaving an auditable trigger-to-proof mapping gap. The mapping is now recorded as an accepted requirement, unconfirmed by another spec reviewer because the loop is capped at three launches. + +### Failure Modes Registry + +| Failure mode | Detection | Required result | Recovery owner | +|---|---|---|---| +| Wrong or stale PR revision | independent Git diff and final GitHub API read | failed check, no eligible claim | controller author | +| Policy/host drift | matrix and registration validation | invalid/incomplete manifest | policy/host maintainer | +| Producer/resource timeout | typed outcome and deadline | failed check and cleanup | producer owner | +| Isolation envelope mismatch | trusted pre-provision verifier | no subject execution/complete claim | runner maintainer | +| Unsafe artifact | descriptor-relative type/path/size/hash validation | reject artifact and complete claim | extractor maintainer | +| Retag or rebuilt release output | remote tag and artifact digest recheck | no `ReleaseComplete`/publication authorization | release maintainer | +| Cleanup failure | independent supervisor attestation | incomplete claim and failed check | CI maintainer | +| GitHub event/check misassociation | real PR pilot with head SHA and base advance | stop rollout before required ruleset | repository administrator | + +### Async order proof to implement + +```text +Controller/host Shared PR/tag identity GitHub/publisher +capture base/head/tag ---------> S0 +execute producers S0 head or tag moves -> S1 +verify manifest S0 +fresh-read ----------------------> S1 reject stale S0 + +Alternative order: move -> S1 before capture; capture S1, execute, then +fresh-read S1 may pass only if the manifest and every digest bind to S1. +Publisher repeats remote tag read immediately before consumption; a move +after verdict but before publication rejects the old claim. +``` + +The controlled regression pauses at final read and pre-publication consumption and releases a competing head/tag update in both orders. Cleanup attestation is a prerequisite for `ManifestVerified`; a supervisor failure before or after host completion cannot be masked by a prior producer success. + +### Decision Audit Trail + +| # | Phase | Decision | Classification | Principle | Rationale | Rejected | +|---|---|---|---|---|---|---| +| 1 | CEO | Retain complete AppSurface-only gate | prior user decision | P6 | Office-hours option B explicitly selected for #777 | narrow demo and generic reusable workflow | +| 2 | CEO | Use V2 preparation-base commit for release selection | auto-decided correction | P2/P6 | Existing release evidence gives a deterministic source and resolves R2-1 | arbitrary base ref or preceding tag heuristic | +| 3 | CEO | Recheck remote tag at verdict and publication | auto-decided correction | P2/P6 | Prevents a captured claim authorizing a moved tag | initial capture only | +| 4 | CEO | Descriptor-relative bounded artifact extraction | auto-decided safety repair | P2/P6 | Closes the subject-to-trusted copy boundary | ordinary file copy/tar | +| 5 | CEO | Fixed extraction limits and trigger-based rollback | auto-decided operational detail | P2/P6 | Makes the trust and rollout contracts testable | undocumented runtime defaults | +| 6 | CEO | Preserve provisional estimate and re-estimate after inventory | auto-decided clarification | P6 | Event feasibility and producer inventory are unknown | treating office-hours comparison as schedule commitment | +| 7 | CEO | Stop/cancel unsafe runs and map every rollback trigger to proof | auto-decided safety repair | P2/P6 | Third spec review required auditable re-enable evidence | generic re-pilot alone | + +### CEO voice reconciliation + +The native `combo/sub` reviewer completed against `INPUT: ceo 3100f9d5ae3d8808d9f68414c91ca49ff84f58b7886682e99b2ca6c63e28ef40` and raised four issues. Its two high findings, control-plane self-change validation and release baseline authority, are accepted as correctness obligations in the CEO block. Its medium duplicate-CI concern is accepted as a matrix and pilot comparison, without removing established checks prematurely. Its medium fork-cost concern is accepted as measurement and runbook detail; the user-selected observation-only fork gate remains unchanged. The Claude Code outside lane was unavailable at preflight, so no cross-provider consensus or User Challenge is claimed. + +| CEO dimension | Native voice | Outside voice | Consensus | +|---|---|---|---| +| Premises valid | conditional: release authority and control-plane lifecycle | unavailable | N/A | +| Right problem | yes: live required AppSurface gate | unavailable | N/A | +| Scope calibration | yes, with duplicate-CI and fork-cost measurement | unavailable | N/A | +| Alternatives explored | fork publisher worth later study | unavailable | N/A | +| Market risk | low for local gate | unavailable | N/A | +| Six-month trajectory | conditional on lifecycle and steady-state ownership | unavailable | N/A | + +The native review did not call for changing the user's chosen AppSurface-only scope or fork policy. No taste decision needs an interim question. The 0H CEO scope document matches the accepted obligations and was auto-approved for continuation under Autoplan's intermediate-decision rule; this is not implementation approval. + +### DX Step 0: developer and clock + +Primary product type: CLI-led developer tool with a GitHub Actions reference and a versioned .NET evidence contract. Primary developer: an AppSurface maintainer who has the repository and normal .NET toolchain, is adding or reviewing a PR, and needs to know whether the selected evidence will satisfy the required check. An external adopter is a later audience for the copyable guide, not the first-run clock. Mode: DX POLISH, selected by Autoplan for an enhancement to an existing tool. + +The current [EvidenceHost start page](../../start-here/evidencehost.md) gives a three-command sample (`init`, `doctor`, `explain`) and a visible plan. The [CLI package guide](../../Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md) documents `run` and `verify`; the [cookbook](../../guides/evidencehost-cookbook.md) covers docs-only, coverage, resource-backed and release examples. None currently gives a revision-bound AppSurface CI gate rehearsal because that workflow and those flags do not exist yet. Current time from checkout to a *revision-bound, gate-shaped* first result is therefore unavailable, not an observed 5-minute success. The local sample's `--path` result is a different endpoint. + +First-person developer perspective (inferred from inspected docs, not an observed user test): “I open the EvidenceHost page and quickly understand why `NoEvidenceRequired` differs from incomplete evidence. I can run the sample commands and see a profile and obligations. When I try to reproduce a failing PR check, the examples switch to `--path` or an arbitrary patch file. I cannot yet tell which base/head pair the CI gate used, where its checked-in policy lives, or whether my local result can satisfy the gate. I need one documented rehearsal from a real PR's two SHAs to the same plan digest, plus a diagnostic that tells me whether a failure is policy selection, missing producer, stale revision, unsafe artifact, or GitHub check wiring. I also need to know that a fork observation will stay red and how to promote its exact commit.” + +Clock: from an AppSurface maintainer's normal checkout and installed .NET/AppSurface CLI to a verified `explain` result for an actual base/head pair, including locating the guide, selecting a fixture pair, and reading the rationale. Current duration: unmeasured, estimated 8–12 minutes because the revision flags and gate guide are absent. Target: competitive 2–5 minutes, to be measured in a fresh maintainer rehearsal after implementation. This target does not claim a cold toolchain install, producer execution, or a live PR completes within five minutes. The useful “magical moment” is `explain` showing exact revisions, policy rule, profile, obligations, and one plan digest that `run` and `verify` reproduce. Delivery vehicle: the existing CLI plus one copyable AppSurface gate rehearsal in the start page, using the checked-in policy and two full SHAs; no hosted playground or new API. + +Comparable DX patterns are [Conftest's direct `test` command and explicit policy default](https://www.conftest.dev/options/), [Conftest's CI/JSON output choices](https://www.conftest.dev/output/), and [GitHub's required-check troubleshooting guidance](https://docs.github.com/en/pull-requests/how-tos/merge-and-close-pull-requests/troubleshooting-required-status-checks). These are interface patterns, not equivalent measured onboarding times; AppSurface's revision-bound evidence and required-check journey is longer. No peer timing is asserted. + +| Journey stage | Maintainer action | Evidenced or predicted friction | Planned disposition | +|---|---|---|---| +| Discover | Follow README link to EvidenceHost | Start page exists; CI reference not yet linked | Add AppSurface gate entry point | +| Evaluate | Read claim table and sample plan | Existing sample is local path mode | Label local vs gate mode clearly | +| Install | Use normal AppSurface CLI and .NET toolchain | Existing CLI install guide; cold timing unknown | Reuse existing instructions and state prerequisites | +| Hello world | Run `explain` for real base/head pair | Revision flags not yet implemented | Copyable rehearsal with expected summary | +| Integrate | Use checked-in policy and host matrix | Policy/registration matrix is planned | Link exact file and selected profile | +| Debug | Read code, summary, manifest | Existing diagnostics only cover v1 local flow | Problem + cause + fix + canonical doc link | +| CI adopt | Compare live PR check to local digest | Event/check association is unproven | Pilot checklist and exact SHA comparison | +| Upgrade | Move from v1 local to versioned gate contract | New schema/migration required | Version matrix and migration steps | +| Maintain | Change policy/control plane or rollback | Self-change and ruleset hazards | Shadow proof, runbook and rollback trigger map | + +First-time rehearsal roleplay, predicted rather than measured: T+0 opens the README EvidenceHost link; T+0:30 runs sample `init`/`doctor`; T+1 sees the local path-mode plan; T+2 tries to map it to a live PR but the current CLI has no authoritative revision flags; T+3 reads the cookbook and still lacks a gate-shaped command; T+5 must ask a maintainer for the PR's base/head and workflow details. The plan should remove that gap with a single end-to-end example, not with a new CLI mode that silently upgrades local output to a trusted claim. + + +- Put a revision-bound AppSurface gate quickstart on the [EvidenceHost start page](../../start-here/evidencehost.md), linked from the repository and CLI entry points. It must use a checked-in policy, one maintained fixture with two full commit IDs and exact diff bytes, and copyable `appsurface evidence explain` commands with expected profile, rationale, obligations, source-diff digest and plan digest. State prerequisites and distinguish the local `--path` sample from gate-eligible evidence. The chosen first-result clock runs from a normal checkout with the CLI installed to that verified explanation; target 2–5 minutes, measured in a fresh maintainer rehearsal. Report full producer/CI runtime separately. +- Define the gate input contract for `explain`, `run`, and `verify` in the CLI and contract references: both full `--base-revision` and `--head-revision` plus `--diff-file` are required together for a revision-bound PR candidate; missing/mixed/abbreviated inputs, absent Git objects, or bytes that fail independent diff regeneration are errors. A local path/diff plan remains usable but cannot claim gate eligibility. Document how the trusted controller supplies its immutable snapshot, how the host executes selected resource-backed producers, and which fields and plan digest the three commands must agree on. Show real command/output templates for a docs-only and a code fixture, with no implication that local `explain` alone can satisfy GitHub's required check. +- Give every gate diagnostic a stable code and a bounded human message with the observed identifier, what failed, likely cause, next action and a nearby link to its canonical reference or troubleshooting section. Demonstrate at least stale base/head, source-diff or plan mismatch, missing producer/resource, unsafe artifact, isolation-envelope failure, cleanup failure, and moved release tag. Keep terminal, summary and machine JSON codes consistent while never printing raw subject output or credentials. Test that the guidance is accurate for those injected branches and that long/malicious values remain bounded. +- Add one tested end-to-end AppSurface adoption walkthrough in the [cookbook](../../guides/evidencehost-cookbook.md): policy rule and explicit registration, local explain, host run, manifest verify, expected claim/verdict, then live check and strict-freshness pilot. Name which code is the reusable contract/CLI and which is AppSurface's reference runner. Include the exact-SHA same-repository promotion procedure for a fork and the fact that its original observation remains ineligible. Link the policy/producer matrix and the operator rollback guide. +- Publish a versioned v1-local to revision-bound gate migration table covering schema compatibility, plan/manifest identity changes, CLI input rules, and what old consumers must change or can keep. Separate consumer-tailorable policy/profile/registration/diagnostic display choices from fixed trust invariants: independent Git diff verification, base-owned authority, complete obligations, isolation, bounded extraction, cleanup attestation, and fresh PR/tag checks. Test the documented fixture and examples against the built CLI and host before enabling the required check. +- Measure and record the selected 2–5 minute first-result journey with a fresh maintainer starting at the documented start page; include discovery, commands, errors and reading the useful explanation. Separately record local full profile execution time, live PR gate latency, fork-promotion effort, and duplicate existing-CI time during the pilot. Treat these as rollout observations, not new telemetry infrastructure or an automatic release gate. + + +### DX pass review and scorecard + +These scores assess the *current plan before* and *planned experience after* the accepted follow-through. They do not assert an implemented or measured result. Mode remains DX POLISH; the approved AppSurface gate and existing CLI are the delivery vehicle. + +| Pass | Before → planned | Evidence, exact follow-through and residual proof | +|---|---:|---| +| 1. Getting started | 4 → 8 | [Start page](../../start-here/evidencehost.md) has a three-command local sample but no real revision-bound gate path. Add the checked-in fixture and three-step rehearsal: locate base/head and policy; run `explain` with immutable diff; read profile/rationale/obligations/digest. Target 2–5 minutes from normal checkout and installed CLI; fresh-user timing remains unmeasured. Cold install and full CI are separate clocks. | +| 2. CLI and API | 6 → 8 | The approved `--base-revision`, `--head-revision`, `--diff-file` interface needs a complete/invalid input matrix and same plan identity across `explain`, `run`, `verify`. Keep path mode local and non-eligible. The host, not a fake local CLI success, supplies resource-backed execution. Fixture tests must prove full-SHA and diff semantics. | +| 3. Errors and debugging | 5 → 8 | Existing local diagnostics do not cover all new gate failures. Stable codes plus problem/cause/action/link are required; test unsafe values and consistency across outputs. A failed claim must remain failed even if summary upload fails. | +| 4. Documentation | 6 → 8 | Existing start page, CLI reference and cookbook are useful but distributed. Add one start-here link chain, copyable expected output, tested adoption walkthrough, policy matrix and operator guide. Keep API reference and runnable tutorial distinct and cross-linked. | +| 5. Upgrade and migration | 5 → 8 | Versioned revision-bound fields change plan/manifest identity. Publish compatibility matrix and examples for v1 local consumers; test old local behavior remains local and never inherits gate eligibility. No automatic codemod is justified for this additive reference. | +| 6. Environment and tooling | 6 → 8 | The planned reference fits .NET and GitHub Actions but host/resource and OCI availability need honest prerequisites and a local rehearsal. Retain noninteractive failure exits and immutable snapshots. Cross-platform claims require actual proof; GitHub-hosted Linux is the supported gate runner. | +| 7. Ecosystem and adoption | 5 → 7 | The first adopter is AppSurface; a copyable policy/host walkthrough is useful. External reusable workflow, public plugin ecosystem, support channel and hosted playground are outside #777. A second adopter would justify revisiting them. | +| 8. Measurement | 3 → 7 | Current first-result time is unmeasured. Time a fresh maintainer's full approved clock, record errors and completion, and separately log full gate, pilot and fork cost. This is a bounded rollout record, not ongoing telemetry or a new process. | + +Pass 1 gold-standard lesson is a single golden path and immediate meaningful output; no hosted playground is justified by the accepted scope. Pass 2 favors one guessable command grammar and consistent identity, without adding a generic endpoint. Pass 3 uses a structured code/message/help/link pattern. Pass 4 requires docs to ship with the contract. Pass 5 treats schema migration as a first-class task. Pass 6 emphasizes short local feedback; Pass 7 is intentionally limited to this repository's reference; Pass 8 measures the chosen first-result clock rather than a warmed command timer. No Hall of Fame example changes the approved behavior. + +#### Diagnostic trace for three concrete failure paths + +| Trigger | Current developer experience | Required developer experience | +|---|---|---| +| PR base or head changed after execution | The planned CLI has no revision inputs today, so it cannot explain a stale gate run. | `revision-stale`: show bounded captured/current short IDs, explain that the PR moved, tell the maintainer to update/rerun for the new pair, link the revision-input and strict-freshness guide; nonzero gate. | +| Captured diff differs from regenerated Git diff | Today's path/patch sample can explain a plan without authoritative base/head objects. | `diff-unavailable` or `plan-mismatch`: identify the expected/actual digest or missing object, reject the claim, advise fetching exact commits or recapturing the immutable snapshot, link the contract reference. | +| Subject declares a symlink/oversized artifact or cleanup fails | Neither branch is exercised by the current local sample, so the maintainer has no existing gate-specific explanation. | `artifact-invalid` names the declared slot and violated bound, or `cleanup-incomplete` names the failed stage; both point to the operator guide, preserve bounded data, and fail the gate. | + +The operator guide also covers envelope denial, missing registration/resource, failed assertion, unavailable GitHub freshness read, and moved release tag. Verbose debug may add bounded controller stage IDs but must not reveal raw subject logs, secrets or untrusted file contents. Exceptions and stack traces belong in trusted diagnostic artifacts only when safe; the required-check summary stays actionable and bounded. + +#### DX implementation and measurement checklist + +- [ ] A maintainer can follow the canonical start page from a normal checkout and reach a real revision-bound `explain` result in the accepted 2–5 minute target; capture observed timing and errors, not an estimate. +- [ ] CLI help and references specify required flag combinations, defaults, invalid cases, claim eligibility, schema versions, and the host-versus-CLI execution boundary; fixture commands and expected output pass against the built tool. +- [ ] The cookbook runs one complete policy/registration/host/manifest/verify example, links the policy matrix, and distinguishes AppSurface-owned reference files from package APIs. +- [ ] Every injected diagnostic branch gives code, problem, likely cause, corrective step and canonical link in terminal, summary and JSON without leaking unsafe output. +- [ ] The v1-local migration and compatibility matrix is accurate; old path mode cannot be mistaken for a gate claim. +- [ ] Pilot records full profile latency, duplicate-CI cost, fork promotion effort, and current-head/check association separately from first-result time; no unsupported platform or cross-platform claim appears in docs. + +#### DX prior learning, trend and decision audit + +Prior learning applied: `pr-evidence-required-check-freshness` (confidence 9/10, 2026-10-01) confirms that manual dispatch cannot satisfy the PR gate and that strict base freshness needs a live pilot. `appsurface-docs-source-file-links` (confidence 10/10, 2026-09-11) means docs should link workflow/source files through stable source URLs where the strict docs exporter does not emit those files. Previous AppSurface DX reviews have covered other products, with reported before scores from 5 to 8 and planned scores from 7 to 9.3; they are not a measured trend for this new gate. Current #777 DX score average is 5.0 before and 7.8 planned, with first-result time still unmeasured. + +| # | Decision | Classification | Authority and effect | +|---|---|---|---| +| 8 | Use existing CLI and checked-in fixture as the first-result vehicle | auto-decided within DX POLISH | Preserves approved revision-bound CLI and AppSurface-only scope; no hosted playground. | +| 9 | Keep local path mode ineligible and require the complete revision input set for a gate candidate | accepted-contract clarification | The approved design already distinguishes local planning from externally verified gate claims; prevents a misleading local green result. | +| 10 | Treat 2–5 minutes as a measured rehearsal target, with full CI timed separately | auto-decided measurement detail | Preserves the target's start and endpoint without claiming an observed result or adding telemetry infrastructure. | + +The native `combo/sub` reviewer completed against `INPUT: dx 60b157bb30d944971b115b35ffafebf1e80e1a145cb14f5b9a1e3457ebdcc3a1` and found four medium gaps: missing smallest tested local fixture, underspecified CLI gate input mode, diagnostics lacking actionable causes and links, and no complete adoption walkthrough. Each is accepted above. It also asked to separate adjustable consumer choices from fixed trust invariants; that is included in the migration/adoption reference. No critical DX blocker was reported. The Claude Code outside lane was unavailable at preflight; native review supplies no cross-provider consensus, so consensus is N/A. + +| DX voice dimension | Native `combo/sub` | Claude Code | Consensus | +|---|---|---|---| +| Getting started under five minutes | Conditional on tested fixture and measured clock | unavailable | N/A | +| CLI naming and input grammar | Needs explicit gate input matrix | unavailable | N/A | +| Error messages actionable | Needs cause/fix/link catalog | unavailable | N/A | +| Docs findable and complete | Needs end-to-end adoption path | unavailable | N/A | +| Upgrade path safe | No native objection; parent requires v1 compatibility matrix | unavailable | N/A | +| Environment friction | No native objection; parent retains supported GitHub-hosted Linux prerequisite | unavailable | N/A | + +## Implementation Tasks + +Synthesized from DX findings; each task is part of the approved AppSurface gate, not a separate product expansion. + +- [ ] **T1 (P1, human: ~4h / agent: ~1h)** — CLI and contracts — Define the complete revision-input, eligibility and identity contract for `explain`, `run` and `verify`. + - Surfaced by: Pass 2 and native DX finding 2; revision flags are planned but gate-mode combinations and the host boundary are not yet specified. + - Files: `Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs`, Evidence contracts/planner and their README files. + - Verify: CLI contract tests for valid full-SHA pairs and invalid/mixed/abbreviated/diff-mismatch inputs; explain/run/verify share plan digest. +- [ ] **T2 (P1, human: ~3h / agent: ~45min)** — Getting started — Check in a real immutable fixture and copyable three-step gate rehearsal with expected output. + - Surfaced by: Pass 1 and native DX finding 1; the present start page only reaches a local `--path` result. + - Files: `start-here/evidencehost.md`, checked-in AppSurface fixture/policy, CLI reference. + - Verify: run documented commands from a normal checkout; time a fresh maintainer from start page to revision-bound explanation. +- [ ] **T3 (P1, human: ~4h / agent: ~1h)** — Diagnostics — Make new gate failures actionable with stable codes, causes, fixes and canonical links. + - Surfaced by: Pass 3 and native DX finding 3; stale revisions, unsafe extraction and cleanup currently lack gate-specific guidance. + - Files: CLI/runner/verifier diagnostics, EvidenceHost troubleshooting reference, renderer tests. + - Verify: inject stale revision, mismatched diff, missing registration, unsafe artifact, envelope failure, cleanup failure and moved tag; compare terminal/summary/JSON codes and bound hostile values. +- [ ] **T4 (P1, human: ~4h / agent: ~1h)** — Adoption — Publish and execute the full AppSurface policy/registration/host/manifest/verify walkthrough. + - Surfaced by: Pass 4 and native DX finding 4; current cookbook lacks a live gate-shaped end-to-end path. + - Files: `guides/evidencehost-cookbook.md`, `start-here/evidencehost.md`, policy matrix and operator runbook. + - Verify: run the example end to end and pilot current-head check, docs/code, failure and exact-SHA fork promotion. +- [ ] **T5 (P2, human: ~2h / agent: ~30min)** — Migration and measurement — Document v1-local compatibility, fixed trust invariants and separate first-result/full-gate timing. + - Surfaced by: Passes 5 and 8; schema identity changes and the 2–5 minute target need an accurate migration path and actual clock. + - Files: Evidence contracts README, CLI README, start page and pilot log. + - Verify: old local examples remain ineligible; fresh maintainer timing uses the full approved start/end state and pilot log records distinct full-run/fork/duplicate-CI costs. + + +- Preserve the complete AppSurface-only gate and non-mutating release reference, but place the base-owned controller/verifier and untrusted subject execution on separate ephemeral GitHub-hosted job VMs. The subject job has `permissions: {}`, no secrets or OIDC permission, no persisted checkout credential, and receives only the exact captured subject tree and bounded plan data; it never receives the trusted policy/runner as writable input. A private same-workflow artifact handoff carries bounded result bytes, not a generic cross-job aggregation API. The verifier treats every subject result and artifact as untrusted, independently recreates the plan from the base-owned policy and exact Git objects, validates run/job provenance, complete obligations, artifact hashes and cleanup, then performs fresh PR-head/base checks before its stable required-check verdict. No subject job or artifact can directly set that verdict. Pilot actual current-head association and event-policy availability before enforcement. Keep the OCI boundary inside the unprivileged subject VM and hostile-probe it; an inability to enforce it prevents a complete claim. +- Specify one versioned, byte-exact Git change protocol for the gate. Fetch and resolve full commit object IDs into a trusted bare/object-only checkout; invoke Git with argument arrays, pinned runner Git version, neutral trusted configuration, disabled external diff/textconv/color and fixed rename/submodule/binary options. Retain a bounded exact source diff for its digest, and derive selection paths separately from a NUL-delimited `git diff --name-status -z` representation of the same objects. Parse statuses and both rename/copy paths, including mode-only, symlink, binary and submodule changes; reject malformed/truncated/invalid-UTF-8/unrepresentable records rather than selecting an empty profile. Independently regenerate both representations before verdict. Enforce an initial 20 MiB source-diff cap, 10,000 changed records and 4 KiB path-byte cap, or revise these only through a reviewed policy/runner limit change. Test unusual names, zero diff, mixed changes, renames, deletions, type/mode-only and submodule records, oversized input and object/ref races. +- Do not let the v1 `EvidencePlanner` mixed-profile fallback erase a resource or producer obligation. For every trusted PR policy, validate that its conservative profile contains every producer, resource, assertion, artifact and obligation required by each targeted profile it may replace; an incompatible policy is invalid before any run. Test docs+code, docs+resource, resource+code, rename across classes, unknown path and control-plane changes for superset closure. Give legitimate release-preparation PRs a targeted PR profile while the protected release invocation selects its non-mutating release profile from its validated preparation-base/tag diff. If one policy cannot express both contexts without letting an event choose a profile in YAML, use a base-owned, versioned PR/release policy pair selected only by validated event kind; each policy still resolves its candidate profile from its exact diff and both digests enter the plan. An event/profile mismatch always fails. +- Treat the current self-consistency-only `EvidenceManifestBuilder.Verify` and CLI `verify` as necessary but insufficient for a CI authorization. Add a trusted gate verifier that checks the base-owned policy digest, independently regenerated Git diff and status set, immutable plan identity, subject-job provenance, execution envelope and external fresh GitHub/tag identity. Legacy v1 local claims retain documented compatibility but never authorize the new required check merely because their manifest says `PullRequestGate`. Test a fully recomputed forged plan/manifest, wrong policy source, wrong subject job, moved base/head/tag and a valid local-only manifest that the external gate rejects. +- Reuse `ReleaseTaggedProjectionResolver` as the sole release-evidence authority without copying its parser into the new host. Because it is currently internal to a non-packable release executable, expose a narrow, versioned, read-only machine result from the existing `inspect` path containing the validated V2 preparation base, evidence bundle digest, tag object ID and peeled commit, or extract that exact validation seam into a private shared assembly used by both callers. Prove identical success/failure behavior in the release tool and EvidenceHost. A release claim remains non-mutating; any future publisher that consumes it must verify tag immutability for the publication lifetime and use only artifacts bound to the captured object and digests. Without that protection, the claim cannot authorize publication. Test a tag move after the last pre-publication read as well as the two earlier race windows. +- Make dependency supply part of the subject envelope: use a pinned, base-owned SDK/OCI image and reviewed immutable package cache or controlled allowlisted mirror, with locked dependency integrity checks. Restore and all head-controlled build hooks run only inside the unprivileged subject boundary; cache misses, lock mismatches or mirror failure yield unavailable/incomplete evidence, never trusted-host restore or silent network expansion. Pilot a cold-cache run and a dependency-changing PR, and record the image/cache refresh path in the policy matrix. +- Give each policy-selected profile a checked-in, measurable maximum: capture/planning, resource readiness, producer execution, API retry, cleanup and total workflow deadlines. The total job deadline must leave room for the independent 10-minute cleanup and final verification; reject a policy whose declared worst-case work exceeds it. Cancel stale same-PR runs on a new head while allowing their supervisor cleanup to finish; do not cancel another PR's run or mark a cancelled run complete. Test overlapping pushes, a push during cleanup, unavailable/rate-limited GitHub API, each cancellation phase and a stuck producer. Set final numeric budgets after the producer inventory and before any required-check activation, using observed pilot duration rather than an arbitrary promise. +- Keep shadow control-plane validation entirely base-owned: the old trusted controller supplies the harness, path classifier, fixtures and expected outcomes. Subject changes to policy, workflow, runner, host registrations or test fixtures are data to that harness, never authority. Test deleted/weakened rules, edited/removed fixtures and an unrecognized control-plane path; each remains subject to the old obligations. New controller code runs only in an unprivileged non-claiming shadow and becomes authoritative after merge plus smoke proof. +- Preserve the already approved descriptor-relative extraction boundary, but do not route untrusted scratch paths through the current `EvidenceArtifactWriter`'s path-based write or `ReadAllBytes` verification. Stream no-follow copies into a private trusted root, hash bytes as copied, reject mutation and enforce both per-slot/per-producer v1 limits and the runner's 64-file/256 MiB per-file/512 MiB total/120-second caps. Extend the writer/verifier through a narrow streaming seam if necessary; document the lower applicable limit and test 256 MiB memory behavior without allocating entire artifacts. + + +### Eng Step 0: scope challenge grounded in current code + +The reviewed target is the approved #777 implementation plan. The work touches at least the Evidence contracts, planner, CLI, Aspire host, private coverage core, release tool, tests, workflows, policy and documentation: more than eight files and at least the controller/verifier, subject runner and cleanup supervisor as distinct components. Scope is **accepted as-is** under the Autoplan no-reduction rule. The smaller arrangement keeps the complete behavior but uses one private base-owned controller/verifier implementation, one unprivileged subject job and one cleanup supervisor; no general scheduler, persistence layer or public workflow framework is added. This is a structural safety correction, not a feature cut. Re-estimate the provisional timeline after the producer inventory, now including the private cross-job handoff and live event pilot. + +What already exists: [`EvidencePlanner`](../../Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs) validates a policy and chooses a profile; [`EvidenceManifestBuilder`](../../Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs) closes typed obligations and verifies self-consistency; [`EvidenceHostBootstrap`](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/EvidenceHostBootstrap.cs) executes explicit registrations and lifecycle cleanup; the [coverage execution seam](../../Evidence/ForgeTrust.AppSurface.Evidence.Coverage/CoverageExecutionBoundary.cs) is reusable; the [release inspect tool](../../tools/ForgeTrust.AppSurface.Release/README.md) already validates tag-bound V2 preparation evidence. The existing [build workflow](https://github.com/forge-trust/AppSurface/blob/main/.github/workflows/build.yml) and [release workflows](https://github.com/forge-trust/AppSurface/tree/main/.github/workflows) supply candidate assertions, not EvidenceHost producer results. The new work is trustworthy capture, isolation, extraction, external verification and live check wiring, not replacement of the typed core. + +Current-code findings and dispositions: + +| ID | Severity / confidence | Evidence | Consequence and accepted remedy | +|---|---|---|---| +| E1 | P1 / 9 | `EvidencePlanner.cs:49-52` uses `distinctProfiles.Length != 1` to select only `ConservativeProfileId`. | A docs+resource or resource+code change can drop obligations if the fallback is weaker. Validate conservative-profile superset or reject policy; test every mixed class. | +| E2 | P1 / 9 | `EvidencePlanner.cs:426-445` adds paths only from `---`/`+++` headers, apart from `rename from/to`. | Binary, mode-only, symlink or submodule changes can be absent from selection. Gate path inventory comes from NUL-delimited Git status records, with source diff separately bound. | +| E3 | P1 / 9 | `EvidenceCliWorkflow.cs:208` re-resolves `plan.PolicySnapshot` and `EvidenceContracts.cs:936-964` verifies internal digests; neither authenticates the GitHub event or base-owned policy source. | A self-consistent local manifest is not a required-check authorization. Add an external trusted verifier and negative forged/legacy tests. | +| E4 | P1 / 9 | `ReleaseTaggedProjectionResolver.cs:13,54` is internal and `ForgeTrust.AppSurface.Release.csproj:4,8` is a non-packable executable. | A new host cannot simply call the existing authority. Expose a read-only machine result or move the exact validator to a private shared seam; test parity. | +| E5 | P1 / 9 | `EvidenceContracts.cs:500,534` uses `WriteAllBytesAsync` and `ReadAllBytesAsync`; these are appropriate to current trusted bounded producer data, but not to the new 256 MiB untrusted scratch transfer. | Stream through no-follow descriptors and private trusted storage; retain lower per-slot/v1 limits and test memory as well as path races. | +| E6 | P1 / 8 | The approved plan places subject OCI execution on the `pull_request_target` controller VM; [GitHub's security guide](https://docs.github.com/en/actions/reference/security/securely-using-pull_request_target) says the event has elevated base trust and warns against fetching then executing untrusted PR code. | Separate subject and controller job VMs, remove subject job permissions/secrets/OIDC, treat handoff as untrusted, and retain OCI hostile probes. | +| E7 | P1 / 7 | The plan denies subject egress yet does not specify a package restore source for a clean runner. | Use locked packages from a pinned base-owned image/cache or controlled mirror, with restore only inside the subject boundary; prove cold cache and dependency PR behavior. | +| E8 | P2 / 7 | The plan has extraction/cleanup limits but leaves total run and GitHub API budgets unspecified; the current host executes resource and producer declarations sequentially (`EvidenceHostBootstrap.cs:338-387`). | Derive numeric policy and job budgets from inventory before enforcement; cancel stale same-PR runs and test overload/timeout branches. | +| E9 | P2 / 8 | The proposed control-plane shadow test does not explicitly own its fixtures at the base revision. | Old trusted harness and expected cases must be base-owned; subject fixture edits cannot approve their own policy weakening. | +| E10 | P1 / 7 | Tag rereads at verdict and pre-publication still leave a mutable-ref window after the last read. | A non-mutating claim is safe only for its captured identity; any publication consumer requires tag immutability for its use window and object/digest-bound artifacts. | + +No current implementation bug is claimed for #777's absent runner. E1-E5 quote existing code that the proposed gate must extend or avoid; E6-E10 identify plan risks, with observed platform guidance or explicit design text. The native review supplied E6-E10 and the broader form of E2. Its P1 issues are represented as mandatory pre-enforcement requirements, not dismissed because the current prototype works locally. Prior learning `appsurface-patch-gate-committed-source` (confidence 10/10, 2026-09-10) applies to final coverage proof: commit new changed code and tests before relying on `coverage-solution.sh` patch metrics. + +### Eng Section 1: architecture and data flow + +```text +PR event -> base-owned controller job VM -> full-SHA Git objects + | -> source-diff bytes + NUL status inventory + | -> checked-in PR policy + immutable plan + | | + +-- bounded snapshot artifact ----------+--> unprivileged subject job VM + -> OCI subject + declared resources + -> typed producer results + scratch + -> no-follow bounded extraction + -> independent cleanup supervisor + +<-- untrusted bounded results/artifacts --+ + -> base-owned verifier job VM -> rederive plan/diff/status/policy + -> verify provenance/manifest/artifacts/cleanup + -> fresh PR base/head API read + -> single renderer -> stable required check + +protected tag -> existing release inspect authority -> V2 preparation base + -> release policy + same subject/verify boundaries where applicable + -> final tag-object check -> non-mutating ReleaseComplete +``` + +The three-job private handoff is the important trust line: subject content can supply test data and artifacts but never the policy, expected selection fixture, job authority or final verdict. The verifier recomputes the plan instead of trusting a subject-supplied digest. The new runner should name its state transitions and one failure sink; every exception or cancellation lands in a bounded failed/incomplete verdict after cleanup. A live pilot is still needed because event policy and required-check association are GitHub behavior, not properties unit tests can establish. At 10x PR volume, container/resource startup and duplicate existing CI dominate; per-PR concurrency and stale-run cancellation bound work without a cache of complete claims. + +The PR/release profile conflict is explicit: a release-preparation PR must be able to pass a targeted PR gate, while its eventual protected tag must run release obligations. A base-owned PR/release policy pair is permitted only if a single policy cannot express both without letting YAML choose an event privilege. In either form, the validated event selects the policy scope and the exact diff selects the candidate profile. Plan identity binds that policy and revisions; no event can reinterpret a targeted claim as release complete. + +### Eng Section 2: code quality and error handling + +Keep one canonical planner/digest, one manifest verifier and one renderer. The public v1 `EvidenceManifestBuilder.Verify` has an explicit self-consistency contract; strengthen the external gate at a trusted boundary rather than silently redefining v1. The new Git status parser and source-diff capture may share a fixed Git invocation helper because they have the same revisions, configuration and error policy; do not extract a generic Git framework. Preserve `EvidenceCliWorkflow` local usage and publish a versioned gate contract. Reuse the release inspect authority through a narrow read-only result rather than duplicating V2 trailer parsing. Keep subject result diagnostics typed and bounded; do not catch an arbitrary failure and then emit `TargetedComplete` from a partially populated result. + +No new external package is required to implement the parsing, hashing, deadlines or renderer. Standard Git, .NET streams, `TimeProvider`/cancellation and existing xUnit infrastructure are the first reuse choices. The separate VM handoff uses the platform's existing job/artifact capability; it is private to this AppSurface workflow, not a public aggregation format. If the platform cannot deliver a provenance-safe handoff with the chosen event, rollout stops before the ruleset change; no `workflow_dispatch` success is substituted. + +### Eng Section 3: codepath and user-flow test diagram + +Current positive coverage exists for local docs/coverage selection, rename parsing, manifest self-consistency, host resource/producer timeouts and local cleanup in `EvidencePlannerTests.cs` and `EvidenceHostBootstrapTests.cs`. These do not exercise the proposed GitHub gate. `ReleaseToolTests.cs` covers tagged V2 validation, but not the new host/release handoff. The project uses xUnit and `dotnet test`; no LLM/prompt change or eval suite is in scope. + +```text +CODE PATHS MAINTAINER / CI FLOWS +Git capture Start page -> revision-bound explain + [GAP] full SHA/object fetch [GAP] fixture command + expected digest + [GAP] source diff exact bytes / 20 MiB cap [GAP] invalid or missing SHA guidance + [GAP] NUL status / rename / type / binary [GAP] local v1 result stays non-authoritative + [GAP] mismatch / malformed / empty -> fail PR gate +Policy resolution [GAP →E2E] docs-only explicit pass + [★★ TESTED] docs path -> no-evidence [GAP →E2E] code/resource complete pass + [★★ TESTED] unknown path -> conservative [GAP →E2E] failed obligation blocks merge + [GAP] mixed profile superset / reject [GAP →E2E] fork observation and promotion + [GAP] control-plane old-policy fixture [GAP →E2E] base advance and wrong-head block +Host / subject Protected release + [★★★ TESTED] local readiness/timeout/cleanup [GAP →E2E] V2 base/tag/package proof + [GAP] no-token separate VM / OCI denial [GAP] retag at each publication window + [GAP] cold-cache/missing dependency Operator + [GAP] no-follow extraction / 64,256,512,120 [GAP] cancellation, cleanup and rollback + [GAP] forced host kill / supervisor [GAP] actionable bounded diagnostics +Verification / output + [★★ TESTED] local self-consistency + [GAP] base-owned policy / job provenance / freshness + [GAP] one verdict across terminal/summary/JSON +``` + +Each `[GAP]` is a proposed codepath or flow, not an assertion about a shipped feature. The [test plan artifact](/Users/andrew/.gstack/projects/forge-trust-AppSurface/andrew-main-eng-review-test-plan-20260930-234800.md) gives each critical path and edge case an observable invariant, credible regression, reason existing coverage misses it, and the required test boundary. Add rows to current table-driven planner/host/release tests where they fit; create new runner/extractor/verifier tests at their actual boundaries, without reflection or test-only production hooks. No test is retired. Run focused xUnit suites for changed packages, hostile OCI integration on supported Linux, a live PR pilot for GitHub semantics, formatting and `./scripts/coverage-solution.sh` when practical. Live remote behavior remains a rollout dependency, not a simulated unit-test pass. + +### Eng Section 4: performance and operations + +There is no database query path or N+1 issue. The expensive stages are checkout/capture, locked restore, disposable resource readiness, test/coverage execution and artifact transfer. The 20 MiB source cap bounds in-memory diff handling; status records and artifact reads must be streamed or explicitly bounded. Avoid loading a 256 MiB artifact twice when hashing and verifying. Set the total deadline from the policy's worst-case sequential resource/producer durations plus cleanup and API/render reserve, then prove a normal full profile fits; the required check must fail closed rather than run indefinitely. Cache only immutable trusted image/package inputs keyed to lockfiles and base-owned tooling, never a manifest, complete claim or freshness result. Per-PR concurrency cancels stale work while the supervisor still cleans it up; unrelated PRs retain capacity. Log stage duration and failure code so the pilot can distinguish this gate's added cost from duplicate existing jobs. + +### Eng failure modes registry + +| Path | Realistic failure | Planned handling and proof | Critical gap after amendment? | +|---|---|---|---| +| Git capture/selection | Binary or mode-only change omitted, object missing, oversized diff | NUL status parser plus independent regeneration; malformed input fails with diagnostic and unit fixture | No | +| Policy/host | Mixed profile drops resource assertion or registration absent | Superset validation and negative matrix tests; incomplete/invalid manifest | No | +| Subject job/dependencies | Container escape attempt, cold cache or missing locked package | Separate unprivileged VM, OCI hostile probe, locked restore and fail-closed diagnostics | No; live isolation proof required | +| Artifact transfer | Symlink/race/special file or size overflow | Descriptor-relative no-follow stream copy with boundary/race tests; no complete claim | No | +| Freshness/provenance | Wrong job, moved head/base or GitHub 403/timeout | Base-owned independent verifier and bounded retry; failed check | No; live check association required | +| Release | Invalid V2 base, moved tag after last read, rebuilt package | Existing inspect authority, immutable publication precondition, retag and digest tests | No; external tag-rule proof required for publication use | +| Cleanup/concurrency | Host killed, stale run cancelled while cleanup active | Independent supervisor attestation, per-PR cancellation, kill/overlap tests | No | +| Control-plane PR | Head edits a rule and its expected fixture | Old base-owned harness/fixtures plus shadow proof and post-merge smoke | No | + +No failure is allowed to become a silent successful claim. Two platform behaviors remain measured dependencies: actual PR check association/event policy, and any future publication tag immutability. The new check stays non-required until the live pilot proves the former. This plan does not authorize a publisher from `ReleaseComplete` alone. + +### Eng workstreams and boundaries + +| Step | Modules touched | Depends on | +|---|---|---| +| A. Contract, Git identity and policy selection | Evidence Contracts, Planner, CLI | policy/producer inventory | +| B. Release inspect machine seam | Release tool and contracts | validated V2 authority already present | +| C. Host, isolation and streaming extraction | Evidence Aspire/Coverage, new AppSurface runner | A, producer inventory | +| D. Trusted controller/verifier and workflow jobs | new runner, GitHub workflows | A, B, C | +| E. Documentation and focused tests | start-here, guides, package docs, tests | alongside A-D, finalized after interfaces | +| F. Live pilot and ruleset activation | GitHub workflow/ruleset | A-E, repository administrator | + +Launch A and B in separate worktrees because their authored modules are disjoint. Integrate both, then C; D follows the runner boundary. Documentation/tests travel with each interface rather than waiting entirely until E. F is sequential and cannot be simulated. Shared new runner and workflow files are one lane to avoid ownership conflicts. No separate service or state store is needed. + +### Eng not in scope and deferred work + +Generic reusable workflow, self-hosted runner support, merge-queue event support before adoption, external check publisher for fork PRs, automatic package/release publication, deployment attestation and a hosted evidence dashboard remain outside #777. They add new trust or compatibility surfaces without helping AppSurface prove its first required gate. The private subject/verifier job handoff is part of this gate, not a generic aggregation API. These deferrals are recorded in `TODOS.md` with adoption or measurement triggers. Existing build/test checks remain until separate equivalence proof supports migration. + +### Eng decision audit and independent voice + +| # | Decision | Classification | Principle | Reason and rejected alternative | +|---|---|---|---|---| +| 11 | Separate privileged verifier and unprivileged subject VMs | safety correction within approved gate | P2/P5 | GitHub identifies `pull_request_target` head-code execution as elevated-risk; retain OCI but remove controller credentials from the subject VM. Rejected same privileged VM as the default. | +| 12 | Derive gate paths from NUL-delimited Git status, source bytes separately | verified correctness repair | P2/P5 | Existing unified-diff reader omits non-text header cases; rejected trusting the text parser for a gate. | +| 13 | Validate mixed-profile conservative superset | verified correctness repair | P2/P6 | Existing fallback replaces multiple profiles; rejected a weaker fallback that silently drops obligations. | +| 14 | Keep v1 digest verification, add external authority check | compatibility-preserving correction | P2/P5 | Existing verifier explicitly authenticates no source; rejected treating a local manifest as PR authorization. | +| 15 | Reuse release inspect authority and require immutable publication use | safety correction | P2/P5 | Internal executable seam needs a narrow bridge; rejected duplicate V2 parser or mutable-tag check/use gap. | +| 16 | Locked dependency supply, bounded deadlines and base-owned shadow fixtures | feasibility/operational correction | P2/P6 | Gives the complete profile a reproducible, bounded run; rejected trusted-host restore and subject-controlled expected fixtures. | + +The native `combo/sub` reviewer completed against `INPUT: eng 237a6770dc6da73691a9d243b6723d311d45e013ad4c48e404a4dddc484671de` with six findings: four P1 (same-VM privilege, Git selection completeness, tag use race, dependency restore) and two P2 (run budgets/concurrency, shadow fixture ownership). They are reconciled above. The Claude Code outside lane was unavailable at preflight; no cross-provider agreement is claimed. + +| Eng voice dimension | Native `combo/sub` | Claude Code | Consensus | +|---|---|---|---| +| Architecture sound | Conditional on VM separation and release seam | unavailable | N/A | +| Test coverage sufficient | Requires unusual Git, retag and hostile isolation branches | unavailable | N/A | +| Performance addressed | Needs whole-run and concurrency bounds | unavailable | N/A | +| Security threats covered | Same-VM and shadow-fixture risks require correction | unavailable | N/A | +| Error paths handled | Restore/cache and API failures need explicit outcomes | unavailable | N/A | +| Deployment risk manageable | Pilot before ruleset; tag immutability before publication use | unavailable | N/A | + +### Eng completion summary + +| Review area | Result | +|---|---| +| Scope challenge | Accepted as-is; safer three-job arrangement retains complete #777 outcome | +| Architecture | Four issue groups resolved into explicit trust, profile and release requirements | +| Code quality | Three seam issues mapped to reuse or narrow extension, no generic framework | +| Test review | Diagram and QA artifact complete; all proposed gate paths remain implementation gaps with named regression proofs | +| Performance | One bounded-runtime issue group, numeric profile/job budgets required before enforcement | +| Failure modes | Zero silent-success gaps after accepted requirements; live event and isolation proofs still pending | +| Parallelization | A/B parallel; C then D; live F last | +| Unresolved engineering decisions | None; administrator ruleset activation requires the completed pilot | +| Outside voice | Claude Code unavailable; native `combo/sub` completed, consensus N/A | + +Approval readiness for the *plan review*: PASS for decisions 11-16 under Autoplan's correctness/safety rules and the user's approved complete-gate scope. This does not claim an implemented gate or authorize a ruleset change before its pilot. + +## Implementation Tasks + +These engineering tasks derive from E1-E10 and the test diagram; effort assumes existing .NET/xUnit and GitHub Actions patterns are reused. Estimates exclude live-pilot waiting and administrator availability. + +- [ ] **T1 (P1, human: ~2 days / agent: ~5h)** — Git identity — Implement full-SHA capture, exact source-diff and NUL status inventory with bounded malformed-input handling. + - Surfaced by: E2 and native Git-selection finding; the current unified-diff parser omits non-text changes. + - Files: Evidence planner/CLI and new trusted runner; contract/CLI references. + - Verify: table-driven Git fixtures for binary, mode-only, symlink, submodule, rename/copy, deletion, invalid filename, empty and oversized diffs; repeat independently at verdict. +- [ ] **T2 (P1, human: ~1 day / agent: ~3h)** — Policy — Enforce mixed-profile superset and PR/release policy-context compatibility. + - Surfaced by: E1; the v1 planner replaces multiple selected profiles with one conservative profile. + - Files: Evidence policy/planner contracts and AppSurface checked-in policy/matrix. + - Verify: docs+resource, resource+code, release-preparation PR, protected release, rename/control-plane and missing-registration fixtures. +- [ ] **T3 (P1, human: ~3 days / agent: ~1 day)** — Isolation — Build separate credentialless subject job, private bounded handoff and trusted verifier job. + - Surfaced by: E3/E6 and native same-VM finding; local manifest digests do not authenticate source or job. + - Files: AppSurface runner and GitHub workflow, Evidence host integration. + - Verify: hostile OCI/credential/socket/network probe, forged manifest/wrong-job rejection, same-repo/fork/failed producer live pilots and head-association proof. +- [ ] **T4 (P1, human: ~2 days / agent: ~5h)** — Host and artifacts — Stream no-follow extraction with typed producer/resource and independent cleanup results. + - Surfaced by: E5 and existing path-based `ReadAllBytes` verification. + - Files: Evidence contracts/Aspire host and AppSurface runner. + - Verify: traversal, symlink, special file, hardlink ambiguity, collisions, mutation, every size/count/time cap and forced host kill; no complete claim on cleanup failure. +- [ ] **T5 (P1, human: ~1 day / agent: ~3h)** — Release — Bridge existing inspect authority to EvidenceHost and bind immutable tag/artifact use. + - Surfaced by: E4/E10 and native tag check/use finding. + - Files: Release tool/contract and AppSurface host release producer. + - Verify: tool/host parity; forged V2 base/trailer, retag at all windows, rebuilt/missing package and publication-ineligible mutable tag. +- [ ] **T6 (P1, human: ~1 day / agent: ~3h)** — Reproducibility — Supply locked dependencies inside the subject boundary and bound every phase/job. + - Surfaced by: E7/E8 and native restore/load findings. + - Files: pinned subject image/cache or mirror config, AppSurface policy/matrix and workflow. + - Verify: cold cache, cache/lock mismatch, mirror unavailable, dependency PR, cancellation at each phase, overlapping pushes and API timeout; record numeric budgets before enforcement. +- [ ] **T7 (P1, human: ~1 day / agent: ~3h)** — Control plane — Make old controller/fixtures authoritative for self-change PRs, with non-claiming shadow and post-merge smoke. + - Surfaced by: E9 and native shadow-fixture finding. + - Files: base-owned policy/runner tests and workflow. + - Verify: delete/weaken rule, change/remove expected fixture, unrecognized control-plane path, then live shadow/smoke proof. +- [ ] **T8 (P1, human: ~2 days plus pilot/admin wait / agent: ~4h plus wait)** — Rollout — Run the complete pilot and activate the exact required check only after observed proof. + - Surfaced by: E6/E8, original #777 finish line and GitHub event/check uncertainty. + - Files: GitHub workflow/ruleset runbook and pilot log. + - Verify: current-head association, strict base-advance freshness, docs/code/resource/failure/fork cases, release non-mutation, rollback trigger map, existing checks and `./scripts/coverage-solution.sh` when practical. + +## GSTACK REVIEW REPORT + +| Review | Trigger | Why | Runs | Status | Findings | +|---|---|---|---:|---|---| +| CEO Review | `/plan-ceo-review` via Autoplan | Scope and strategy | 19 including this review | ISSUES MAPPED | Complete AppSurface scope retained; one third-pass spec-review mapping was resolved by parent without a fourth reviewer. | +| Outside Review | Claude Code via Autoplan | Independent second opinion | 2 historical; current unavailable | UNAVAILABLE | CLI not installed at preflight; no cross-provider consensus is claimed for #777. | +| Eng Review | `/plan-eng-review` via Autoplan | Architecture and tests, required | 21 including this review | ISSUES MAPPED | 10 findings mapped to accepted requirements; zero silent-success critical gaps after amendment; live pilot remains. | +| Design Review | `/plan-design-review` | UI/UX gaps | 2 historical; skipped for #777 | SKIPPED | No UI scope in the #777 gate. | +| DX Review | `/plan-devex-review` via Autoplan | Developer experience gaps | 19 including this review | ISSUES MAPPED | Planned 5.0/10 → 7.8/10; first-result time unmeasured, target 2–5 minutes. | + +**OUTSIDE COVERAGE:** Claude Code was unavailable for CEO, DX and Eng phases. Native `combo/sub` reviews completed with 4, 4 and 6 issues respectively. Their findings were reconciled, but native review does not supply independent outside-provider coverage. + +**VERDICT:** APPROVED by the user at the final Autoplan gate on 2026-10-01 after CEO, DX and Eng review. The new required check must not be activated until the implementation, hostile isolation tests, live head/freshness pilot and administrator verification pass. Eng implementation review is required before ship because this plan review mapped issues rather than certifying code. + +NO UNRESOLVED DECISIONS From 2cca334af64a41a7fb0054dd5a481b182f500ac4 Mon Sep 17 00:00:00 2001 From: Andrew Krock Date: Thu, 1 Oct 2026 06:37:43 -0400 Subject: [PATCH 002/123] feat(evidence): add fail-closed CI evidence gate pilot --- .appsurface/evidence/evidence.policy.json | 525 ++++++++ .gitattributes | 2 + .github/workflows/evidence-gate-shadow.yml | 99 ++ .github/workflows/evidence-gate.yml | 201 +++ .../EvidenceHostBootstrapTests.cs | 303 +++++ .../AppSurfaceEvidencePolicyTests.cs | 383 ++++++ .../EvidenceGitChangeCaptureTests.cs | 304 +++++ .../EvidenceNoFollowArtifactExtractorTests.cs | 320 +++++ .../EvidencePlannerTests.cs | 314 +++++ .../EvidencePullRequestGateVerifierTests.cs | 518 ++++++++ .../EvidenceCommands.cs | 43 +- Cli/ForgeTrust.AppSurface.Cli/README.md | 2 + .../EvidenceCliWorkflow.cs | 125 +- .../README.md | 6 +- .../EvidenceContracts.cs | 278 +++- .../EvidenceNoFollowArtifactExtractor.cs | 724 +++++++++++ .../README.md | 31 + .../EvidenceGitChangeCapture.cs | 424 +++++++ .../EvidencePlanner.cs | 260 ++++ .../EvidencePullRequestGateVerifier.cs | 1128 +++++++++++++++++ .../EvidenceRevisionPlanBuilder.cs | 120 ++ .../README.md | 56 +- ForgeTrust.AppSurface.slnx | 2 + ...AppSurfaceDocsWayfindingPlaywrightTests.cs | 23 +- .../release-preference-dark-1440x1000.png | Bin 452890 -> 456106 bytes .../release-preference-light-1440x1000.png | Bin 504682 -> 507815 bytes .../release-system-dark-1440x1000.png | Bin 452897 -> 456107 bytes .../release-system-light-1440x1000.png | Bin 504721 -> 507829 bytes .../release-desktop-1440x1000.png | Bin 565525 -> 570580 bytes docs/evidence-gate-diagnostics.md | 84 ++ docs/evidence-gate-policy-matrix.md | 20 + docs/evidence-gate-rollout.md | 48 + docs/fixtures/issue-777-docs-only/README.md | 34 + .../fixtures/issue-777-docs-only/fixture.json | 8 + docs/fixtures/issue-777-docs-only/policy.json | 1 + .../issue-777-docs-only/repository.bundle | Bin 0 -> 828 bytes docs/fixtures/issue-777-docs-only/source.diff | 9 + .../DurablePostgreSqlLocalProofScriptTests.cs | 12 +- guides/evidencehost-cookbook.md | 15 + scripts/evidence-gate-controller.py | 926 ++++++++++++++ scripts/evidence-gate-subject-entrypoint.py | 809 ++++++++++++ scripts/evidence-gate-subject.py | 904 +++++++++++++ .../tests/test_evidence_gate_controller.py | 662 ++++++++++ scripts/tests/test_evidence_gate_fixture.py | 78 ++ scripts/tests/test_evidence_gate_subject.py | 448 +++++++ .../test_evidence_gate_subject_entrypoint.py | 439 +++++++ start-here/evidencehost.md | 4 + .../EvidenceGateResultRendererTests.cs | 81 ++ .../EvidenceGateVerifierTests.cs | 328 +++++ .../EvidenceHostRunnerTests.cs | 351 +++++ ...Trust.AppSurface.EvidenceGate.Tests.csproj | 33 + ...ubActionsEvidenceAuthorityProviderTests.cs | 129 ++ .../packages.lock.json | 767 +++++++++++ .../EvidenceGateResultRenderer.cs | 129 ++ .../EvidenceGateVerifier.cs | 233 ++++ .../EvidenceHostRunner.cs | 435 +++++++ .../ForgeTrust.AppSurface.EvidenceGate.csproj | 21 + .../GitHubActionsEvidenceAuthorityProvider.cs | 317 +++++ .../Program.cs | 168 +++ .../README.md | 51 + .../packages.lock.json | 655 ++++++++++ .../ReleaseToolTests.cs | 320 ++++- tools/ForgeTrust.AppSurface.Release/README.md | 29 +- .../ReleaseCommands.cs | 27 +- .../ReleaseEvidence.cs | 5 +- .../ReleaseInspectMachineResult.cs | 136 ++ .../ReleaseTaggedProjectionResolver.cs | 219 +++- 67 files changed, 15069 insertions(+), 57 deletions(-) create mode 100644 .appsurface/evidence/evidence.policy.json create mode 100644 .github/workflows/evidence-gate-shadow.yml create mode 100644 .github/workflows/evidence-gate.yml create mode 100644 Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs create mode 100644 Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceGitChangeCaptureTests.cs create mode 100644 Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceNoFollowArtifactExtractorTests.cs create mode 100644 Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePullRequestGateVerifierTests.cs create mode 100644 Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceNoFollowArtifactExtractor.cs create mode 100644 Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceGitChangeCapture.cs create mode 100644 Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePullRequestGateVerifier.cs create mode 100644 Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceRevisionPlanBuilder.cs create mode 100644 docs/evidence-gate-diagnostics.md create mode 100644 docs/evidence-gate-policy-matrix.md create mode 100644 docs/evidence-gate-rollout.md create mode 100644 docs/fixtures/issue-777-docs-only/README.md create mode 100644 docs/fixtures/issue-777-docs-only/fixture.json create mode 100644 docs/fixtures/issue-777-docs-only/policy.json create mode 100644 docs/fixtures/issue-777-docs-only/repository.bundle create mode 100644 docs/fixtures/issue-777-docs-only/source.diff create mode 100644 scripts/evidence-gate-controller.py create mode 100644 scripts/evidence-gate-subject-entrypoint.py create mode 100644 scripts/evidence-gate-subject.py create mode 100644 scripts/tests/test_evidence_gate_controller.py create mode 100644 scripts/tests/test_evidence_gate_fixture.py create mode 100644 scripts/tests/test_evidence_gate_subject.py create mode 100644 scripts/tests/test_evidence_gate_subject_entrypoint.py create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate.Tests/EvidenceGateResultRendererTests.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate.Tests/EvidenceGateVerifierTests.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate.Tests/EvidenceHostRunnerTests.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate.Tests/ForgeTrust.AppSurface.EvidenceGate.Tests.csproj create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate.Tests/GitHubActionsEvidenceAuthorityProviderTests.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate.Tests/packages.lock.json create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/EvidenceGateResultRenderer.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/EvidenceGateVerifier.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/EvidenceHostRunner.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/ForgeTrust.AppSurface.EvidenceGate.csproj create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/GitHubActionsEvidenceAuthorityProvider.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/Program.cs create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/README.md create mode 100644 tools/ForgeTrust.AppSurface.EvidenceGate/packages.lock.json create mode 100644 tools/ForgeTrust.AppSurface.Release/ReleaseInspectMachineResult.cs diff --git a/.appsurface/evidence/evidence.policy.json b/.appsurface/evidence/evidence.policy.json new file mode 100644 index 000000000..5a868076c --- /dev/null +++ b/.appsurface/evidence/evidence.policy.json @@ -0,0 +1,525 @@ +{ + "id": "appsurface-pr-evidence", + "version": "1", + "conservativeProfileId": "pr-conservative", + "profiles": [ + { + "id": "documentation-only", + "scope": "Targeted", + "resources": [], + "producers": [], + "obligations": [] + }, + { + "id": "code-coverage", + "scope": "Targeted", + "resources": [], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + } + ] + }, + { + "id": "postgresql-integration", + "scope": "Targeted", + "resources": [ + { "id": "postgresql-16-5", "readiness": "aspire_health", "deadlineSeconds": 180, "requires": [] }, + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "postgresql-contract", + "kind": "postgresql-integration", + "version": "1.0.0", + "requiredResources": ["postgresql-16-5"], + "assertionIds": ["appsurface/durable/postgresql-16.5-assertions@1"], + "artifactSlots": [ + { "logicalName": "scenario-results", "relativeRoot": "postgresql/scenarios", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "run-metadata", "relativeRoot": "postgresql/run", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 900 + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "postgresql-integration-contract", + "riskClass": "resource-backed-integration", + "rationale": "Durable PostgreSQL changes require real assertions against a disposable PostgreSQL 16.5 service.", + "requiredProducerIds": ["postgresql-contract"], + "requiredAssertionId": "appsurface/durable/postgresql-16.5-assertions@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + } + ] + }, + { + "id": "keycloak-theme-integration", + "scope": "Targeted", + "resources": [ + { "id": "keycloak-pinned-image", "readiness": "aspire_health", "deadlineSeconds": 240, "requires": [] }, + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "keycloak-theme-contract", + "kind": "keycloak-theme-integration", + "version": "1.0.0", + "requiredResources": ["keycloak-pinned-image"], + "assertionIds": ["appsurface/keycloak/served-theme-assets@1"], + "artifactSlots": [ + { "logicalName": "theme-proof", "relativeRoot": "keycloak/theme", "mediaType": "application/json", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "theme-summary", "relativeRoot": "keycloak/summary", "mediaType": "text/markdown", "required": true, "maximumBytes": 524288 }, + { "logicalName": "runtime-metadata", "relativeRoot": "keycloak/runtime", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 600 + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "keycloak-theme-rendering", + "riskClass": "resource-backed-integration", + "rationale": "Keycloak theme changes require a disposable pinned service and proof that the expected stylesheet is served.", + "requiredProducerIds": ["keycloak-theme-contract"], + "requiredAssertionId": "appsurface/keycloak/served-theme-assets@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + } + ] + }, + { + "id": "package-release-preparation", + "scope": "Targeted", + "resources": [ + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + }, + { + "id": "release-preparation-contract", + "kind": "release-preparation-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": ["appsurface/release/preparation-base-and-artifacts-verified@1"], + "artifactSlots": [ + { "logicalName": "preparation-projection", "relativeRoot": "release/preparation", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "prepared-artifact-digests", "relativeRoot": "release/digests", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 } + ], + "timeoutSeconds": 900 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + }, + { + "id": "release-preparation-evidence", + "riskClass": "release-preparation", + "rationale": "Release-preparation changes require the validated V2 preparation base and digest-bound non-mutating evidence.", + "requiredProducerIds": ["release-preparation-contract"], + "requiredAssertionId": "appsurface/release/preparation-base-and-artifacts-verified@1" + } + ] + }, + { + "id": "pr-conservative", + "scope": "Targeted", + "resources": [ + { "id": "postgresql-16-5", "readiness": "aspire_health", "deadlineSeconds": 180, "requires": [] }, + { "id": "keycloak-pinned-image", "readiness": "aspire_health", "deadlineSeconds": 240, "requires": [] }, + { "id": "locked-package-inputs", "readiness": "completion", "deadlineSeconds": 300, "requires": [] } + ], + "producers": [ + { + "id": "coverage", + "kind": "coverage", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/coverage/overall-and-patch-thresholds@1"], + "artifactSlots": [ + { "logicalName": "cobertura", "relativeRoot": "coverage/cobertura", "mediaType": "application/xml", "required": true, "maximumBytes": 20971520 }, + { "logicalName": "gate-report", "relativeRoot": "coverage/report", "mediaType": "text/markdown", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "diagnostics", "relativeRoot": "coverage/diagnostics", "mediaType": "application/json", "required": false, "maximumBytes": 4194304 } + ], + "timeoutSeconds": 1200, + "coverageGate": { + "minLinePercent": 95, + "minBranchPercent": 85, + "minPatchLinePercent": 95, + "minPatchBranchPercent": 85, + "patchLineMode": "codecov", + "tolerancePercent": 0.5 + } + }, + { + "id": "control-plane-validation", + "kind": "control-plane-validation", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/control-plane/base-owned-validation@1"], + "artifactSlots": [ + { "logicalName": "validation-report", "relativeRoot": "control-plane/report", "mediaType": "application/json", "required": true, "maximumBytes": 1048576 } + ], + "timeoutSeconds": 300 + }, + { + "id": "postgresql-contract", + "kind": "postgresql-integration", + "version": "1.0.0", + "requiredResources": ["postgresql-16-5"], + "assertionIds": ["appsurface/durable/postgresql-16.5-assertions@1"], + "artifactSlots": [ + { "logicalName": "scenario-results", "relativeRoot": "postgresql/scenarios", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "run-metadata", "relativeRoot": "postgresql/run", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 900 + }, + { + "id": "keycloak-theme-contract", + "kind": "keycloak-theme-integration", + "version": "1.0.0", + "requiredResources": ["keycloak-pinned-image"], + "assertionIds": ["appsurface/keycloak/served-theme-assets@1"], + "artifactSlots": [ + { "logicalName": "theme-proof", "relativeRoot": "keycloak/theme", "mediaType": "application/json", "required": true, "maximumBytes": 1048576 }, + { "logicalName": "theme-summary", "relativeRoot": "keycloak/summary", "mediaType": "text/markdown", "required": true, "maximumBytes": 524288 }, + { "logicalName": "runtime-metadata", "relativeRoot": "keycloak/runtime", "mediaType": "application/json", "required": true, "maximumBytes": 262144 } + ], + "timeoutSeconds": 600 + }, + { + "id": "package-contract", + "kind": "package-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": [ + "appsurface/package/locked-restore-build@1", + "appsurface/package/artifact-manifest-and-digests@1" + ], + "artifactSlots": [ + { "logicalName": "package-manifest", "relativeRoot": "packages/manifest", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "validation-report", "relativeRoot": "packages/validation", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-digest-index", "relativeRoot": "packages/digests", "mediaType": "application/json", "required": true, "maximumBytes": 4194304 }, + { "logicalName": "nupkg-bundle", "relativeRoot": "packages/nupkg", "mediaType": "application/zip", "required": true, "maximumBytes": 268435456 } + ], + "timeoutSeconds": 1800 + }, + { + "id": "release-preparation-contract", + "kind": "release-preparation-contract", + "version": "1.0.0", + "requiredResources": ["locked-package-inputs"], + "assertionIds": ["appsurface/release/preparation-base-and-artifacts-verified@1"], + "artifactSlots": [ + { "logicalName": "preparation-projection", "relativeRoot": "release/preparation", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "prepared-artifact-digests", "relativeRoot": "release/digests", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 } + ], + "timeoutSeconds": 900 + } + ], + "obligations": [ + { + "id": "behavioral-coverage", + "riskClass": "behavioral-code", + "rationale": "Changed executable code must meet the AppSurface overall and patch coverage thresholds.", + "requiredProducerIds": ["coverage"], + "requiredAssertionId": "appsurface/coverage/overall-and-patch-thresholds@1" + }, + { + "id": "control-plane-integrity", + "riskClass": "trusted-control-plane", + "rationale": "Workflow, policy, runner, host, and gate implementation changes require base-owned validation and cannot waive evidence.", + "requiredProducerIds": ["control-plane-validation"], + "requiredAssertionId": "appsurface/control-plane/base-owned-validation@1" + }, + { + "id": "postgresql-integration-contract", + "riskClass": "resource-backed-integration", + "rationale": "Durable PostgreSQL changes require real assertions against a disposable PostgreSQL 16.5 service.", + "requiredProducerIds": ["postgresql-contract"], + "requiredAssertionId": "appsurface/durable/postgresql-16.5-assertions@1" + }, + { + "id": "keycloak-theme-rendering", + "riskClass": "resource-backed-integration", + "rationale": "Keycloak theme changes require a disposable pinned service and proof that the expected stylesheet is served.", + "requiredProducerIds": ["keycloak-theme-contract"], + "requiredAssertionId": "appsurface/keycloak/served-theme-assets@1" + }, + { + "id": "package-locked-build-and-artifacts", + "riskClass": "package-artifacts", + "rationale": "Package changes require locked restore and build, contract validation, a package manifest, and exact package digests.", + "requiredProducerIds": ["package-contract"], + "requiredAssertionId": "appsurface/package/locked-restore-build@1" + }, + { + "id": "release-preparation-evidence", + "riskClass": "release-preparation", + "rationale": "Release-preparation changes require the validated V2 preparation base and digest-bound non-mutating evidence.", + "requiredProducerIds": ["release-preparation-contract"], + "requiredAssertionId": "appsurface/release/preparation-base-and-artifacts-verified@1" + } + ] + }, + { + "id": "protected-release", + "scope": "Release", + "resources": [], + "producers": [ + { + "id": "release-inspection", + "kind": "release-inspection", + "version": "1.0.0", + "requiredResources": [], + "assertionIds": ["appsurface/release/protected-tag-and-preparation-base@1"], + "artifactSlots": [ + { "logicalName": "release-projection", "relativeRoot": "release/projection", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 }, + { "logicalName": "release-digest-index", "relativeRoot": "release/digests", "mediaType": "application/json", "required": true, "maximumBytes": 2097152 } + ], + "timeoutSeconds": 600 + } + ], + "obligations": [ + { + "id": "protected-release-subject", + "riskClass": "protected-release", + "rationale": "Only a protected release invocation may attest the tag object, peeled commit, validated preparation base, and exact package digests without publishing.", + "requiredProducerIds": ["release-inspection"], + "requiredAssertionId": "appsurface/release/protected-tag-and-preparation-base@1" + } + ] + } + ], + "rules": [ + { "id": "documentation-reference", "pattern": "docs/*.md", "profileId": "documentation-only" }, + { "id": "documentation-guides", "pattern": "guides/*.md", "profileId": "documentation-only" }, + { "id": "documentation-start-here", "pattern": "start-here/*.md", "profileId": "documentation-only" }, + { "id": "documentation-root-readme", "pattern": "README.md", "profileId": "documentation-only" }, + { "id": "documentation-contributor-guide", "pattern": "CONTRIBUTING.md", "profileId": "documentation-only" }, + { "id": "control-github", "pattern": ".github/**", "profileId": "pr-conservative" }, + { "id": "control-policy", "pattern": ".appsurface/**", "profileId": "pr-conservative" }, + { "id": "control-design-documents", "pattern": "docs/designs/**", "profileId": "pr-conservative" }, + { "id": "control-issue-plans", "pattern": "docs/plans/**", "profileId": "pr-conservative" }, + { "id": "control-policy-matrix", "pattern": "docs/evidence-gate-policy-matrix.md", "profileId": "pr-conservative" }, + { "id": "control-rollout-guide", "pattern": "docs/evidence-gate-rollout.md", "profileId": "pr-conservative" }, + { "id": "control-diagnostics-guide", "pattern": "docs/evidence-gate-diagnostics.md", "profileId": "pr-conservative" }, + { "id": "control-scripts", "pattern": "scripts/**", "profileId": "pr-conservative" }, + { "id": "control-agent-guidance", "pattern": "AGENTS.md", "profileId": "pr-conservative" }, + { "id": "control-nested-agent-guidance", "pattern": "**/AGENTS.md", "profileId": "pr-conservative" }, + { "id": "control-evidence-implementation", "pattern": "Evidence/**", "profileId": "pr-conservative" }, + { "id": "control-evidence-cli", "pattern": "Cli/ForgeTrust.AppSurface.Cli/**", "profileId": "pr-conservative" }, + { "id": "control-evidence-cli-tests", "pattern": "Cli/ForgeTrust.AppSurface.Cli.Tests/**", "profileId": "pr-conservative" }, + { "id": "coverage-csharp", "pattern": "**/*.cs", "profileId": "code-coverage" }, + { "id": "package-project-files", "pattern": "**/*.csproj", "profileId": "package-release-preparation" }, + { "id": "unknown-typescript", "pattern": "**/*.ts", "profileId": "pr-conservative" }, + { "id": "unknown-tsx", "pattern": "**/*.tsx", "profileId": "pr-conservative" }, + { "id": "unknown-javascript", "pattern": "**/*.js", "profileId": "pr-conservative" }, + { "id": "unknown-css", "pattern": "**/*.css", "profileId": "pr-conservative" }, + { "id": "unknown-scss", "pattern": "**/*.scss", "profileId": "pr-conservative" }, + { "id": "unknown-razor", "pattern": "**/*.razor", "profileId": "pr-conservative" }, + { "id": "unknown-sql", "pattern": "**/*.sql", "profileId": "pr-conservative" }, + { "id": "integration-durable-postgresql", "pattern": "Durable/**", "profileId": "postgresql-integration" }, + { "id": "integration-durable-package-projects", "pattern": "Durable/**/*.csproj", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-durable-package-locks", "pattern": "Durable/**/packages.lock.json", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-durable-postgresql-example", "pattern": "examples/durable-postgresql/**", "profileId": "postgresql-integration" }, + { "id": "integration-keycloak-theme", "pattern": "Web/ForgeTrust.AppSurface.Web.Tailwind/**", "profileId": "keycloak-theme-integration" }, + { "id": "integration-keycloak-theme-package-projects", "pattern": "Web/ForgeTrust.AppSurface.Web.Tailwind/**/*.csproj", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-theme-package-locks", "pattern": "Web/ForgeTrust.AppSurface.Web.Tailwind/**/packages.lock.json", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-library", "pattern": "Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**", "profileId": "keycloak-theme-integration" }, + { "id": "integration-keycloak-library-package-projects", "pattern": "Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**/*.csproj", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-library-package-locks", "pattern": "Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/**/packages.lock.json", "profileId": "pr-conservative", "precedence": 1 }, + { "id": "integration-keycloak-apphost", "pattern": "examples/auth-aspire-keycloak-apphost/**", "profileId": "keycloak-theme-integration" }, + { "id": "integration-keycloak-examples", "pattern": "examples/auth-aspire-keycloak-*/**", "profileId": "keycloak-theme-integration" }, + { "id": "packages-index", "pattern": "packages/**", "profileId": "package-release-preparation" }, + { "id": "packages-tool", "pattern": "tools/ForgeTrust.AppSurface.PackageIndex/**", "profileId": "package-release-preparation" }, + { "id": "packages-lockfiles", "pattern": "**/packages.lock.json", "profileId": "package-release-preparation" }, + { "id": "packages-msbuild-files", "pattern": "**/*.props", "profileId": "package-release-preparation" }, + { "id": "packages-msbuild-targets", "pattern": "**/*.targets", "profileId": "package-release-preparation" }, + { "id": "packages-pnpm-lockfile", "pattern": "**/pnpm-lock.yaml", "profileId": "package-release-preparation" }, + { "id": "packages-dotnet-build-config", "pattern": "Directory.Build.*", "profileId": "package-release-preparation" }, + { "id": "packages-directory-package-config", "pattern": "Directory.Packages.props", "profileId": "package-release-preparation" }, + { "id": "packages-sdk-config", "pattern": "global.json", "profileId": "package-release-preparation" }, + { "id": "packages-nuget-config", "pattern": "NuGet.config", "profileId": "package-release-preparation" }, + { "id": "packages-gate-config", "pattern": "NuGet.package-gate.config", "profileId": "package-release-preparation" }, + { "id": "release-preparation-tool", "pattern": "tools/ForgeTrust.AppSurface.Release/**", "profileId": "package-release-preparation" }, + { "id": "release-preparation-documents", "pattern": "releases/**", "profileId": "package-release-preparation" }, + { "id": "release-preparation-version", "pattern": "VERSION", "profileId": "package-release-preparation" }, + { "id": "release-preparation-changelog", "pattern": "CHANGELOG.md", "profileId": "package-release-preparation" } + ] +} diff --git a/.gitattributes b/.gitattributes index dd0138b23..840794d54 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,3 @@ Web/ForgeTrust.AppSurface.Web.Tailwind/tailwind.release.json text eol=lf +# A captured Git diff marks an unchanged empty line with one leading context space. +docs/fixtures/issue-777-docs-only/source.diff -whitespace diff --git a/.github/workflows/evidence-gate-shadow.yml b/.github/workflows/evidence-gate-shadow.yml new file mode 100644 index 000000000..e7f4366de --- /dev/null +++ b/.github/workflows/evidence-gate-shadow.yml @@ -0,0 +1,99 @@ +name: evidence-gate-shadow.yml + +on: + pull_request: + branches: [main] + types: [opened, synchronize, reopened, ready_for_review, edited] + push: + branches: [main] + paths: + - .appsurface/** + - Evidence/** + - tools/ForgeTrust.AppSurface.EvidenceGate/** + - tools/ForgeTrust.AppSurface.EvidenceGate.Tests/** + - tools/ForgeTrust.AppSurface.Release/** + - .github/workflows/evidence-gate*.yml + - scripts/evidence-gate-* + +permissions: + contents: read + +concurrency: + group: evidence-gate-shadow-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + non-claiming-contract-check: + name: Evidence gate shadow (non-claiming) + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - name: Checkout candidate code for non-claiming validation + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Setup .NET SDK + uses: actions/setup-dotnet@a98b56852c35b8e3190ac28c8c2271da59106c68 # v6.0.0 + with: + dotnet-version: 10.0.x + - name: Restore focused evidence tests with lock files + run: | + dotnet restore Cli/ForgeTrust.AppSurface.Cli.Tests/ForgeTrust.AppSurface.Cli.Tests.csproj --locked-mode + dotnet restore tools/ForgeTrust.AppSurface.EvidenceGate.Tests/ForgeTrust.AppSurface.EvidenceGate.Tests.csproj --locked-mode + dotnet restore tools/ForgeTrust.AppSurface.Release.Tests/ForgeTrust.AppSurface.Release.Tests.csproj --locked-mode + - name: Validate policy, revision, verifier, and extraction contracts + run: >- + dotnet test Cli/ForgeTrust.AppSurface.Cli.Tests/ForgeTrust.AppSurface.Cli.Tests.csproj + --no-restore + --filter "FullyQualifiedName~Evidence|FullyQualifiedName~AppSurfaceEvidencePolicyTests" + - name: Validate first-party host behavior + run: dotnet test tools/ForgeTrust.AppSurface.EvidenceGate.Tests/ForgeTrust.AppSurface.EvidenceGate.Tests.csproj --no-restore + - name: Validate non-mutating release inspection + run: >- + dotnet test tools/ForgeTrust.AppSurface.Release.Tests/ForgeTrust.AppSurface.Release.Tests.csproj + --no-restore + --filter "FullyQualifiedName~Release" + - name: Validate controller capture and credentialless subject isolation + run: python3 -m unittest discover -s scripts/tests -p 'test_evidence_gate_*.py' + - name: Rehearse exact docs-only plan, host, and local verification + shell: bash + run: | + set -euo pipefail + fixture_dir="$(mktemp -d)" + git clone --quiet docs/fixtures/issue-777-docs-only/repository.bundle "$fixture_dir/repository" + base_revision="$(python3 -c 'import json; print(json.load(open("docs/fixtures/issue-777-docs-only/fixture.json"))["baseRevision"])')" + head_revision="$(python3 -c 'import json; print(json.load(open("docs/fixtures/issue-777-docs-only/fixture.json"))["headRevision"])')" + policy=docs/fixtures/issue-777-docs-only/policy.json + dotnet run --project Cli/ForgeTrust.AppSurface.Cli --no-restore -- evidence explain \ + --policy "$policy" --repository "$fixture_dir/repository" \ + --base-revision "$base_revision" --head-revision "$head_revision" \ + --diff-file docs/fixtures/issue-777-docs-only/source.diff --gate-mode \ + --output "$fixture_dir/explain" + dotnet run --project tools/ForgeTrust.AppSurface.EvidenceGate --no-restore -- run \ + --plan "$fixture_dir/explain/evidence-plan.json" --policy "$policy" \ + --repository "$fixture_dir/repository" --output-dir "$fixture_dir/host" + dotnet run --project Cli/ForgeTrust.AppSurface.Cli --no-restore -- evidence verify \ + "$fixture_dir/host/evidence-manifest.json" \ + --plan "$fixture_dir/host/evidence-plan.json" --policy "$policy" \ + --repository "$fixture_dir/repository" + python3 - "$fixture_dir" <<'PY' + import json + from pathlib import Path + import sys + root = Path(sys.argv[1]) + explained = json.loads((root / "explain/evidence-plan.json").read_text()) + hosted = json.loads((root / "host/evidence-plan.json").read_text()) + manifest = json.loads((root / "host/evidence-manifest.json").read_text()) + assert explained["PlanDigest"] == hosted["PlanDigest"] + assert hosted["Profile"]["Id"] == "documentation-only" + assert manifest["ClaimKind"] == "NoEvidenceRequired" + assert manifest["Eligibility"] == "PullRequestGate" + PY + - name: Explain shadow status + if: ${{ always() }} + run: | + { + echo '## AppSurface evidence gate shadow' + echo '' + echo 'This branch-owned check validates implementation contracts only. It is not the base-owned verifier, does not issue an EvidenceHost claim, and must not be configured as the required evidence check.' + } >> "$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/evidence-gate.yml b/.github/workflows/evidence-gate.yml new file mode 100644 index 000000000..eedd10ff9 --- /dev/null +++ b/.github/workflows/evidence-gate.yml @@ -0,0 +1,201 @@ +name: Evidence gate pilot (non-claiming) + +on: + pull_request_target: + branches: + - main + types: + - opened + - synchronize + - reopened + - ready_for_review + - edited + +permissions: {} + +concurrency: + group: evidence-gate-pilot-${{ github.event.pull_request.number || github.run_id }} + cancel-in-progress: true + +jobs: + controller-capture: + name: Evidence gate controller capture (non-claiming) + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + steps: + - name: Checkout the workflow's trusted base revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.workflow_sha }} + path: trusted + persist-credentials: false + fetch-depth: 1 + + - name: Capture the exact pull-request revision pair + shell: bash + env: + GITHUB_TOKEN: ${{ github.token }} + run: | + set -euo pipefail + capture_directory="$RUNNER_TEMP/evidence-gate-capture" + handoff_directory="$RUNNER_TEMP/evidence-gate-handoff" + + python3 "$GITHUB_WORKSPACE/trusted/scripts/evidence-gate-controller.py" \ + --event "$GITHUB_EVENT_PATH" \ + --output "$capture_directory" \ + --target-branch main + + install -d -m 700 "$handoff_directory" + if [[ -f "$capture_directory/source.diff" && ! -L "$capture_directory/source.diff" \ + && -f "$capture_directory/pull-request-run-identity.json" \ + && ! -L "$capture_directory/pull-request-run-identity.json" ]]; then + install -m 600 "$capture_directory/source.diff" "$handoff_directory/source.diff" + install -m 600 "$capture_directory/pull-request-run-identity.json" \ + "$handoff_directory/pull-request-run-identity.json" + elif [[ -f "$capture_directory/observation.json" && ! -L "$capture_directory/observation.json" ]]; then + install -m 600 "$capture_directory/observation.json" "$handoff_directory/observation.json" + else + echo 'The controller did not produce one recognized bounded handoff.' >&2 + exit 1 + fi + + python3 - "$handoff_directory" <<'PY' + import os + from pathlib import Path + import stat + import sys + + root = Path(sys.argv[1]) + entries = list(root.iterdir()) + names = {entry.name for entry in entries} + valid = ( + names == {"source.diff", "pull-request-run-identity.json"} + or names == {"observation.json"} + ) + if not valid or len(entries) != len(names): + raise SystemExit("The controller handoff file set is invalid.") + total = 0 + for entry in entries: + metadata = entry.lstat() + if not stat.S_ISREG(metadata.st_mode): + raise SystemExit("The controller handoff contains a non-regular file.") + total += metadata.st_size + if total > 20 * 1024 * 1024 + 64 * 1024: + raise SystemExit("The controller handoff exceeds its byte limit.") + PY + + - name: Upload the bounded same-run handoff + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-controller-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-handoff/* + if-no-files-found: error + retention-days: 1 + compression-level: 0 + include-hidden-files: false + + credentialless-subject: + name: Evidence gate subject (credentialless, non-claiming) + needs: controller-capture + if: ${{ needs.controller-capture.result == 'success' }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: {} + steps: + - name: Download this run's controller handoff + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: evidence-gate-controller-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-controller-handoff + + - name: Validate the bounded handoff without executing pull-request content + shell: bash + run: | + set -euo pipefail + python3 - "$RUNNER_TEMP/evidence-gate-controller-handoff" <<'PY' + from pathlib import Path + import stat + import sys + + root = Path(sys.argv[1]) + entries = list(root.iterdir()) + names = {entry.name for entry in entries} + if not ( + names == {"source.diff", "pull-request-run-identity.json"} + or names == {"observation.json"} + ) or len(entries) != len(names): + raise SystemExit("The downloaded controller handoff file set is invalid.") + total = 0 + for entry in entries: + metadata = entry.lstat() + if not stat.S_ISREG(metadata.st_mode): + raise SystemExit("The downloaded handoff contains a non-regular file.") + total += metadata.st_size + if total > 20 * 1024 * 1024 + 64 * 1024: + raise SystemExit("The downloaded controller handoff exceeds its byte limit.") + PY + printf '%s\n' '{"claimEligible":false,"execution":"not-run","schemaVersion":1}' \ + > "$RUNNER_TEMP/evidence-gate-subject-result.json" + + - name: Upload the fixed non-claiming subject result + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: evidence-gate-subject-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-subject-result.json + if-no-files-found: error + retention-days: 1 + compression-level: 0 + include-hidden-files: false + + trusted-verifier: + name: Evidence gate verifier (non-claiming; intentionally fails closed) + needs: + - controller-capture + - credentialless-subject + if: ${{ always() }} + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Checkout the workflow's trusted base revision + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.workflow_sha }} + path: trusted + persist-credentials: false + fetch-depth: 1 + + - name: Download same-run handoffs when both producer jobs succeeded + if: ${{ needs.controller-capture.result == 'success' && needs.credentialless-subject.result == 'success' }} + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + pattern: evidence-gate-*-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/evidence-gate-verifier-inputs + merge-multiple: false + + - name: Report the unavailable authorization seams and fail closed + if: ${{ always() }} + shell: bash + env: + CONTROLLER_RESULT: ${{ needs.controller-capture.result }} + SUBJECT_RESULT: ${{ needs.credentialless-subject.result }} + run: | + { + echo '## AppSurface evidence gate pilot' + echo '' + echo 'This base-owned verifier scaffold is deliberately non-claiming and must not be made required.' + echo '' + printf '%s\n' "- Controller capture job: $CONTROLLER_RESULT" + printf '%s\n' "- Credentialless subject job: $SUBJECT_RESULT" + echo '- Subject execution: not run; no reviewed subject image or producer handoff is configured.' + echo '- Checkout/isolation attestation: unavailable; workflow/job metadata does not attest the consumed checkout.' + echo '- Trusted gate verdict: unavailable; host registrations and complete producer verification are not established.' + } >> "$GITHUB_STEP_SUMMARY" + echo 'ASEGH003: Non-claiming pilot scaffold. Subject execution and trusted checkout/isolation attestation are not implemented.' + exit 1 diff --git a/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs b/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs index 7c41e4015..878a10b3d 100644 --- a/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs +++ b/Aspire/ForgeTrust.AppSurface.Aspire.Tests/EvidenceHostBootstrapTests.cs @@ -419,6 +419,309 @@ [new EvidenceArtifactSlot("report", "coverage", "text/plain", Required: true, Ma } } + [Fact] + public async Task ArtifactWriter_StreamWriteShouldHashAndVerifyWithoutTakingStreamOwnership() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-stream-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 512 * 1024); + var contents = Enumerable.Range(0, 200_000).Select(static value => (byte)(value % 251)).ToArray(); + await using var source = new NonSeekableReadStream(contents); + + var artifact = await writer.WriteAsync("report", "coverage/report.bin", source, contents.LongLength); + + Assert.Equal(contents.LongLength, artifact.LengthBytes); + Assert.Equal(EvidenceDigest.Sha256(contents), artifact.Sha256); + Assert.Equal(contents, await File.ReadAllBytesAsync(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + Assert.True(source.CanRead); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldHandleTheV1MaximumWithBoundedReads() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-maximum-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, EvidenceArtifactWriter.MaximumTotalArtifactBytes); + await using var source = new GeneratedReadStream(EvidenceArtifactWriter.MaximumTotalArtifactBytes); + + var artifact = await writer.WriteAsync( + "report", + "coverage/report.bin", + source, + EvidenceArtifactWriter.MaximumTotalArtifactBytes); + + Assert.Equal(EvidenceArtifactWriter.MaximumTotalArtifactBytes, artifact.LengthBytes); + Assert.Equal(EvidenceArtifactWriter.MaximumTotalArtifactBytes, source.BytesRead); + Assert.InRange(source.MaximumRequestedReadSize, 1, 81_920); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldRejectSlotAndProducerLimitsBeforeReading() + { + var slotWriter = CreateArtifactWriter(TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-slot-{Guid.NewGuid():N}"), maximumBytes: 4); + await using var slotSource = new MemoryStream("12345"u8.ToArray(), writable: false); + + await Assert.ThrowsAsync(async () => await slotWriter.WriteAsync("report", "coverage/report.bin", slotSource, 5)); + Assert.Equal(0, slotSource.Position); + + var producerWriter = CreateArtifactWriter( + TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-producer-{Guid.NewGuid():N}"), + maximumBytes: EvidenceArtifactWriter.MaximumTotalArtifactBytes + 1); + await using var producerSource = new MemoryStream(); + + await Assert.ThrowsAsync(async () => await producerWriter.WriteAsync( + "report", + "coverage/report.bin", + producerSource, + EvidenceArtifactWriter.MaximumTotalArtifactBytes + 1)); + Assert.Equal(0, producerSource.Position); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldEnforceTheProducerLimitAcrossConcurrentSlots() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-total-{Guid.NewGuid():N}"); + var producer = new EvidenceProducerDeclaration( + "coverage", + "coverage", + "1.0.0", + [], + [], + [ + new EvidenceArtifactSlot("report", "coverage", "application/octet-stream", Required: false, MaximumBytes: EvidenceArtifactWriter.MaximumTotalArtifactBytes), + new EvidenceArtifactSlot("summary", "coverage", "application/octet-stream", Required: false, MaximumBytes: EvidenceArtifactWriter.MaximumTotalArtifactBytes), + ], + 30); + var writer = new EvidenceArtifactWriter(producer, artifactDirectory); + using var cancellation = new CancellationTokenSource(); + await using var firstSource = new BlockingAfterFirstReadStream("partial"u8.ToArray()); + var firstWrite = writer.WriteAsync( + "report", + "coverage/report.bin", + firstSource, + EvidenceArtifactWriter.MaximumTotalArtifactBytes, + cancellation.Token).AsTask(); + await firstSource.FirstReadCompleted.Task; + await using var secondSource = new MemoryStream("x"u8.ToArray(), writable: false); + + await Assert.ThrowsAsync(async () => await writer.WriteAsync("summary", "coverage/summary.bin", secondSource, 1)); + Assert.Equal(0, secondSource.Position); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => firstWrite); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldRejectShortAndLongStreamsAndReleaseReservations() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-length-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 16); + await using var shortSource = new MemoryStream("short"u8.ToArray(), writable: false); + + await Assert.ThrowsAsync(async () => await writer.WriteAsync("report", "coverage/report.bin", shortSource, 6)); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + + await using var longSource = new MemoryStream("long"u8.ToArray(), writable: false); + await Assert.ThrowsAsync(async () => await writer.WriteAsync("report", "coverage/report.bin", longSource, 3)); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + + await using var validSource = new MemoryStream("valid"u8.ToArray(), writable: false); + var artifact = await writer.WriteAsync("report", "coverage/report.bin", validSource, 5); + Assert.Equal(5, artifact.LengthBytes); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamVerificationShouldDetectTampering() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-tamper-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 16); + await using var source = new MemoryStream("original"u8.ToArray(), writable: false); + await writer.WriteAsync("report", "coverage/report.bin", source, source.Length); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + await Assert.ThrowsAnyAsync(() => writer.VerifyWrittenArtifactsAsync(cancellation.Token)); + + await File.WriteAllTextAsync(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"), "tampered"); + + Assert.False(await writer.VerifyWrittenArtifactsAsync()); + await File.WriteAllTextAsync(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"), "tampered-size"); + Assert.False(await writer.VerifyWrittenArtifactsAsync()); + Directory.Delete(artifactDirectory, recursive: true); + } + + [Fact] + public async Task ArtifactWriter_StreamWriteShouldCleanUpAndReleaseReservationWhenCancelledMidCopy() + { + var artifactDirectory = TestPathUtils.PathUnder(Path.GetTempPath(), $"appsurface-evidence-cancel-{Guid.NewGuid():N}"); + var writer = CreateArtifactWriter(artifactDirectory, maximumBytes: 16); + using var cancellation = new CancellationTokenSource(); + await using var source = new BlockingAfterFirstReadStream("partial"u8.ToArray()); + + var write = writer.WriteAsync("report", "coverage/report.bin", source, 16, cancellation.Token).AsTask(); + await source.FirstReadCompleted.Task; + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => write); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(TestPathUtils.PathUnder(artifactDirectory, "coverage", "report.bin"))); + Assert.Empty(Directory.EnumerateFiles(artifactDirectory, "*", SearchOption.AllDirectories)); + + await using var validSource = new MemoryStream("valid"u8.ToArray(), writable: false); + Assert.Equal(5, (await writer.WriteAsync("report", "coverage/report.bin", validSource, 5)).LengthBytes); + Directory.Delete(artifactDirectory, recursive: true); + } + + private static EvidenceArtifactWriter CreateArtifactWriter(string artifactDirectory, long maximumBytes) => new( + new EvidenceProducerDeclaration( + "coverage", + "coverage", + "1.0.0", + [], + [], + [new EvidenceArtifactSlot("report", "coverage", "application/octet-stream", Required: false, MaximumBytes: maximumBytes)], + 30), + artifactDirectory); + + private sealed class NonSeekableReadStream(byte[] contents) : Stream + { + private int _position; + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) + { + var bytesToCopy = Math.Min(Math.Min(count, 4_096), contents.Length - _position); + contents.AsSpan(_position, bytesToCopy).CopyTo(buffer.AsSpan(offset, bytesToCopy)); + _position += bytesToCopy; + return bytesToCopy; + } + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var bytesToCopy = Math.Min(Math.Min(buffer.Length, 4_096), contents.Length - _position); + contents.AsMemory(_position, bytesToCopy).CopyTo(buffer); + _position += bytesToCopy; + return ValueTask.FromResult(bytesToCopy); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + private sealed class GeneratedReadStream(long length) : Stream + { + private long _position; + + public long BytesRead => _position; + + public int MaximumRequestedReadSize { get; private set; } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + MaximumRequestedReadSize = Math.Max(MaximumRequestedReadSize, buffer.Length); + var bytesToRead = (int)Math.Min(buffer.Length, length - _position); + buffer.Span[..bytesToRead].Clear(); + _position += bytesToRead; + return ValueTask.FromResult(bytesToRead); + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + + private sealed class BlockingAfterFirstReadStream(byte[] firstChunk) : Stream + { + private bool _firstRead = true; + + public TaskCompletionSource FirstReadCompleted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => throw new NotSupportedException(); + + public override long Position + { + get => throw new NotSupportedException(); + set => throw new NotSupportedException(); + } + + public override void Flush() => throw new NotSupportedException(); + + public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + if (_firstRead) + { + _firstRead = false; + var bytesToCopy = Math.Min(buffer.Length, firstChunk.Length); + firstChunk.AsMemory(0, bytesToCopy).CopyTo(buffer); + FirstReadCompleted.TrySetResult(); + return bytesToCopy; + } + + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + return 0; + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + } + [Fact] public async Task RunAsync_ShouldProtectLifecycleBoundsSharedDependenciesAndCallerCancelledProducers() { diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs new file mode 100644 index 000000000..ffc38aeac --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs @@ -0,0 +1,383 @@ +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; +using ForgeTrust.AppSurface.Testing; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class AppSurfaceEvidencePolicyTests +{ + private const string PolicyRelativePath = ".appsurface/evidence/evidence.policy.json"; + private static readonly EvidencePolicy Policy = LoadPolicy(); + private static readonly EvidencePlanner Planner = new(); + + [Theory] + [InlineData("docs/overview.md")] + [InlineData("guides/evidencehost-cookbook.md")] + [InlineData("start-here/evidencehost.md")] + [InlineData("README.md")] + [InlineData("CONTRIBUTING.md")] + public void ReviewedNarrativeDocumentation_ShouldProduceExplicitNoEvidenceClaim(string path) + { + // These paths contain human-facing reference and onboarding content only. The separately tested + // workflow, policy, design, script, and gate-implementation paths retain evidence obligations. + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + Assert.Equal("documentation-only", plan.Profile.Id); + Assert.Equal(EvidenceProfileScope.Targeted, plan.Profile.Scope); + Assert.Empty(plan.Profile.Resources); + Assert.Empty(plan.Profile.Producers); + Assert.Empty(plan.Profile.Obligations); + + var manifest = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceClaimKind.NoEvidenceRequired, manifest.ClaimKind); + Assert.Equal(EvidenceClaimEligibility.PullRequestGate, manifest.Eligibility); + } + + [Theory] + [InlineData("docs/designs/new-design.md")] + [InlineData("docs/plans/new-plan.md")] + [InlineData("docs/evidence-gate-rollout.md")] + [InlineData("guides/nested/behavior-contract.md")] + public void DesignPlanRolloutAndNestedDocumentation_ShouldRemainFailClosed(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "control-plane-integrity"); + } + + [Fact] + public void ExecutableCode_ShouldSelectBoundedCoverageObligation() + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath("examples/web-app/ExampleModule.cs")]); + + Assert.Equal("code-coverage", plan.Profile.Id); + var coverage = Assert.Single(plan.Profile.Producers); + Assert.Equal("coverage", coverage.Id); + Assert.Equal(1200, coverage.TimeoutSeconds); + Assert.Equal( + new EvidenceCoverageGateRequirements(95, 85, 95, 85, "codecov", 0.5m), + coverage.CoverageGate); + Assert.All(coverage.ArtifactSlots, slot => Assert.InRange(slot.MaximumBytes, 1, 20_971_520)); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "behavioral-coverage"); + + var unregistered = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, unregistered.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, unregistered.ClaimKind); + } + + [Theory] + [InlineData("Durable/ForgeTrust.AppSurface.Durable.PostgreSql/Store.cs", "postgresql-integration", "postgresql-contract")] + [InlineData("examples/auth-aspire-keycloak-apphost/Program.cs", "keycloak-theme-integration", "keycloak-theme-contract")] + [InlineData("packages/package-index.yml", "package-release-preparation", "package-contract")] + [InlineData("src/Example/Example.csproj", "package-release-preparation", "package-contract")] + [InlineData("tools/ForgeTrust.AppSurface.Release/ReleaseCommands.cs", "package-release-preparation", "release-preparation-contract")] + public void ResourceAndPackagePaths_ShouldKeepTheirRequiredProducers(string path, string profileId, string producerId) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + Assert.Equal(profileId, plan.Profile.Id); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == producerId); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + if (profileId != "postgresql-integration" && profileId != "keycloak-theme-integration") + { + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "package-contract"); + } + Assert.NotEmpty(plan.Profile.Obligations); + Assert.All(plan.Profile.Producers, producer => Assert.InRange(producer.TimeoutSeconds, 1, 1800)); + Assert.All(plan.Profile.Resources, resource => Assert.InRange(resource.DeadlineSeconds, 1, 300)); + + // Policy selection is not producer registration or a successful execution. With no host results, + // every behavior-bearing profile must stay incomplete and ineligible. + var missing = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, missing.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, missing.ClaimKind); + } + + [Fact] + public void MixedDocumentationAndCode_ShouldUseTheConservativeUnion() + { + var plan = Planner.ResolveForGate( + Policy, + [ + new NormalizedDiffPath("guides/evidencehost-cookbook.md"), + new NormalizedDiffPath("examples/web-app/ExampleModule.cs"), + ]); + + AssertConservativeUnion(plan); + Assert.Contains("documentation-guides", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains("coverage-csharp", plan.MatchedRuleIds, StringComparer.Ordinal); + } + + [Fact] + public void RenameAcrossDocumentationAndResourcePaths_ShouldEvaluateBothNames() + { + var renamed = new NormalizedDiffPath( + "guides/evidencehost-cookbook.md", + "renamed", + "Durable/verify-postgresql.sh"); + var plan = Planner.ResolveForGate(Policy, [renamed]); + + AssertConservativeUnion(plan); + Assert.Contains("documentation-guides", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains("integration-durable-postgresql", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Equal("Durable/verify-postgresql.sh", Assert.Single(plan.ChangedPaths).PreviousPath); + } + + [Fact] + public void DeletedCodePath_ShouldStillRequireCoverage() + { + var plan = Planner.ResolveForGate( + Policy, + [new NormalizedDiffPath("examples/web-app/ExampleModule.cs", "deleted")]); + + Assert.Equal("code-coverage", plan.Profile.Id); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "behavioral-coverage"); + Assert.Equal("deleted", Assert.Single(plan.ChangedPaths).Kind); + } + + [Theory] + [InlineData("Durable/ForgeTrust.AppSurface.Durable.PostgreSql/ForgeTrust.AppSurface.Durable.PostgreSql.csproj")] + [InlineData("Web/ForgeTrust.AppSurface.Web.Tailwind/ForgeTrust.AppSurface.Web.Tailwind.csproj")] + [InlineData("Auth/ForgeTrust.AppSurface.Auth.Aspire.Keycloak/ForgeTrust.AppSurface.Auth.Aspire.Keycloak.csproj")] + public void ResourceProjectFiles_ShouldRetainPackageAndIntegrationObligations(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "package-locked-build-and-artifacts"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "postgresql-integration-contract"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "keycloak-theme-rendering"); + } + + [Theory] + [InlineData("src/client/app.ts")] + [InlineData("src/client/app.tsx")] + [InlineData("src/client/app.js")] + [InlineData("src/client/app.css")] + [InlineData("src/client/theme.scss")] + [InlineData("Web/Pages/Index.razor")] + [InlineData("data/migrations/0001_contract.sql")] + public void NonDotNetBehavior_ShouldRemainFailClosedUntilAProducerCanProveIt(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + var manifest = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, manifest.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, manifest.ClaimKind); + } + + [Fact] + public void DurableSql_ShouldRequireResourceBackedDatabaseEvidence() + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath("Durable/Migrations/0001_contract.sql")]); + + Assert.Equal("postgresql-integration", plan.Profile.Id); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "postgresql-contract"); + var manifest = EvidenceManifestBuilder.Build(plan, []); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, manifest.ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, manifest.ClaimKind); + } + + [Theory] + [InlineData(".github/workflows/build.yml")] + [InlineData(".appsurface/evidence/evidence.policy.json")] + [InlineData("docs/designs/issue-777-policy-driven-ci-evidence-gate.md")] + [InlineData("docs/plans/issue-777-policy-driven-ci-evidence-gate-implementation.md")] + [InlineData("docs/evidence-gate-policy-matrix.md")] + [InlineData("docs/evidence-gate-rollout.md")] + [InlineData("docs/evidence-gate-diagnostics.md")] + [InlineData("scripts/coverage-solution.sh")] + [InlineData("Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs")] + [InlineData("Cli/ForgeTrust.AppSurface.Cli.Tests/AppSurfaceEvidencePolicyTests.cs")] + public void ControlPlanePaths_ShouldNeverUseNoEvidenceProfile(string path) + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath(path)]); + + AssertConservativeUnion(plan); + Assert.NotEqual("documentation-only", plan.Profile.Id); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "control-plane-integrity"); + } + + [Fact] + public void UnclassifiedRepositoryPath_ShouldUseConservativeFallback() + { + var plan = Planner.ResolveForGate(Policy, [new NormalizedDiffPath("new-area/unrecognized-input.bin")]); + + AssertConservativeUnion(plan); + Assert.Contains("conservative:pr-conservative", plan.MatchedRuleIds, StringComparer.Ordinal); + } + + [Fact] + public void ConservativeProfile_ShouldPreserveEveryTargetedPrRequirement() + { + EvidencePlanner.ValidateGatePolicy(Policy); + + var conservative = GetProfile("pr-conservative"); + Assert.Equal(EvidenceProfileScope.Targeted, conservative.Scope); + Assert.Equal(conservative.Producers.Count, conservative.Producers.Select(producer => producer.Id).Distinct(StringComparer.Ordinal).Count()); + Assert.Equal(conservative.Obligations.Count, conservative.Obligations.Select(obligation => obligation.Id).Distinct(StringComparer.Ordinal).Count()); + Assert.Equal(conservative.Resources.Count, conservative.Resources.Select(resource => resource.Id).Distinct(StringComparer.Ordinal).Count()); + + var profilesById = Policy.Profiles.ToDictionary(profile => profile.Id, StringComparer.Ordinal); + foreach (var targeted in Policy.Rules.Select(rule => profilesById[rule.ProfileId]).DistinctBy(profile => profile.Id)) + { + Assert.All(targeted.Resources, required => AssertResourceIncluded(required, conservative.Resources)); + Assert.All(targeted.Producers, required => AssertProducerIncluded(required, conservative.Producers)); + Assert.All(targeted.Obligations, required => AssertObligationIncluded(required, conservative.Obligations)); + } + + var weakenedProfiles = Policy.Profiles + .Select(profile => profile.Id == conservative.Id + ? profile with + { + Producers = profile.Producers + .Select(producer => producer.Id == "package-contract" + ? producer with { TimeoutSeconds = producer.TimeoutSeconds + 1 } + : producer) + .ToArray(), + } + : profile) + .ToArray(); + var weakened = Policy with { Profiles = weakenedProfiles }; + var error = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(weakened)); + + Assert.Equal("ASEVD129", error.Code); + Assert.Contains("package-contract", error.Message, StringComparison.Ordinal); + + var weakenedReleaseProfile = Policy.Profiles + .Select(profile => profile.Id == conservative.Id + ? profile with + { + Producers = profile.Producers + .Select(producer => producer.Id == "release-preparation-contract" + ? producer with { TimeoutSeconds = producer.TimeoutSeconds + 1 } + : producer) + .ToArray(), + } + : profile) + .ToArray(); + var missingReleaseProducer = Policy with + { + Profiles = weakenedReleaseProfile, + }; + var releaseError = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(missingReleaseProducer)); + Assert.Equal("ASEVD129", releaseError.Code); + Assert.Contains("release-preparation-contract", releaseError.Message, StringComparison.Ordinal); + } + + [Fact] + public void ProtectedReleaseProfile_ShouldNotBeSelectableByAnyPrRule() + { + var release = GetProfile("protected-release"); + Assert.Equal(EvidenceProfileScope.Release, release.Scope); + Assert.NotEmpty(release.Obligations); + Assert.All(Policy.Rules, rule => Assert.Equal(EvidenceProfileScope.Targeted, GetProfile(rule.ProfileId).Scope)); + + var invalidRules = Policy.Rules + .Append(new EvidencePolicyRule("invalid-pr-release-selection", "release/**", release.Id)) + .ToArray(); + var invalidPrPolicy = Policy with { Rules = invalidRules }; + var error = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(invalidPrPolicy)); + + Assert.Equal("ASEVD129", error.Code); + Assert.Contains("non-targeted", error.Message, StringComparison.OrdinalIgnoreCase); + } + + private static void AssertConservativeUnion(EvidencePlan plan) + { + Assert.Equal("pr-conservative", plan.Profile.Id); + Assert.Equal(EvidenceProfileScope.Targeted, plan.Profile.Scope); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "postgresql-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "keycloak-theme-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "package-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "release-preparation-contract"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "control-plane-validation"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "release-preparation-evidence"); + Assert.Contains(plan.Profile.Obligations, obligation => obligation.Id == "control-plane-integrity"); + Assert.Equal(EvidenceExecutionVerdict.Incomplete, EvidenceManifestBuilder.Build(plan, []).ExecutionVerdict); + Assert.Equal(EvidenceClaimKind.None, EvidenceManifestBuilder.Build(plan, []).ClaimKind); + } + + private static EvidenceProfile GetProfile(string id) => + Policy.Profiles.Single(profile => string.Equals(profile.Id, id, StringComparison.Ordinal)); + + private static void AssertResourceIncluded( + EvidenceResourceDeclaration required, + IReadOnlyList declarations) + { + var actual = Assert.Single(declarations, declaration => declaration.Id == required.Id); + Assert.Equal(required.Readiness, actual.Readiness); + Assert.True(actual.DeadlineSeconds <= required.DeadlineSeconds); + Assert.All(required.Requires, dependency => Assert.Contains(dependency, actual.Requires, StringComparer.Ordinal)); + } + + private static void AssertProducerIncluded( + EvidenceProducerDeclaration required, + IReadOnlyList declarations) + { + var actual = Assert.Single(declarations, declaration => declaration.Id == required.Id); + Assert.Equal(required.Kind, actual.Kind); + Assert.Equal(required.Version, actual.Version); + Assert.True(actual.TimeoutSeconds <= required.TimeoutSeconds); + AssertCoverageGateIncluded(required.CoverageGate, actual.CoverageGate); + Assert.All(required.RequiredResources, resource => Assert.Contains(resource, actual.RequiredResources, StringComparer.Ordinal)); + Assert.All(required.AssertionIds, assertion => Assert.Contains(assertion, actual.AssertionIds, StringComparer.Ordinal)); + + foreach (var slot in required.ArtifactSlots) + { + var actualSlot = Assert.Single(actual.ArtifactSlots, candidate => candidate.LogicalName == slot.LogicalName); + Assert.Equal(slot.RelativeRoot, actualSlot.RelativeRoot); + Assert.Equal(slot.MediaType, actualSlot.MediaType); + Assert.True(!slot.Required || actualSlot.Required); + Assert.True(actualSlot.MaximumBytes <= slot.MaximumBytes); + } + } + + private static void AssertObligationIncluded(EvidenceObligation required, IReadOnlyList declarations) + { + var actual = Assert.Single(declarations, declaration => declaration.Id == required.Id); + Assert.Equal(required.RiskClass, actual.RiskClass); + Assert.Equal(required.Rationale, actual.Rationale); + Assert.Equal(required.RequiredAssertionId, actual.RequiredAssertionId); + Assert.All(required.RequiredProducerIds, producer => Assert.Contains(producer, actual.RequiredProducerIds, StringComparer.Ordinal)); + } + + private static void AssertCoverageGateIncluded( + EvidenceCoverageGateRequirements? required, + EvidenceCoverageGateRequirements? actual) + { + if (required is null) + { + return; + } + + Assert.NotNull(actual); + Assert.True(actual.MinLinePercent >= required.MinLinePercent); + Assert.True(actual.MinBranchPercent >= required.MinBranchPercent); + Assert.True(required.MinPatchLinePercent is null || actual.MinPatchLinePercent >= required.MinPatchLinePercent); + Assert.True(required.MinPatchBranchPercent is null || actual.MinPatchBranchPercent >= required.MinPatchBranchPercent); + Assert.Equal(required.PatchLineMode, actual.PatchLineMode, ignoreCase: true); + Assert.True(actual.TolerancePercent <= required.TolerancePercent); + } + + private static EvidencePolicy LoadPolicy() + { + var current = new DirectoryInfo(AppContext.BaseDirectory); + while (current is not null) + { + var candidate = TestPathUtils.PathUnder(current.FullName, PolicyRelativePath); + if (File.Exists(candidate)) + { + return EvidenceCanonicalJson.Deserialize(File.ReadAllBytes(candidate)); + } + + current = current.Parent; + } + + throw new DirectoryNotFoundException($"Could not find the checked-in {PolicyRelativePath} file from the test assembly directory."); + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceGitChangeCaptureTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceGitChangeCaptureTests.cs new file mode 100644 index 000000000..3b2e87a6d --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceGitChangeCaptureTests.cs @@ -0,0 +1,304 @@ +using System.Diagnostics; +using System.Text; +using ForgeTrust.AppSurface.Evidence.Cli; +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class EvidenceGitChangeCaptureTests +{ + [Fact] + public void ParseNameStatus_ShouldIncludeNonTextChangesAndBothRenamePaths() + { + var bytes = Encoding.UTF8.GetBytes("A\0src/new.cs\0M\0images/logo.bin\0T\0links/current\0R100\0src/old.cs\0src/moved.cs\0C75\0src/base.cs\0src/copied.cs\0D\0src/gone.cs\0"); + + var paths = EvidenceGitChangeCapture.ParseNameStatus(bytes); + + Assert.Collection( + paths, + path => Assert.Equal(("src/new.cs", "added", (string?)null), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("images/logo.bin", "modified", (string?)null), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("links/current", "typechanged", (string?)null), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("src/moved.cs", "renamed", "src/old.cs"), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("src/copied.cs", "copied", "src/base.cs"), (path.Path, path.Kind, path.PreviousPath)), + path => Assert.Equal(("src/gone.cs", "deleted", (string?)null), (path.Path, path.Kind, path.PreviousPath))); + } + + [Theory] + [InlineData("A\0src/file.cs")] + [InlineData("U\0src/file.cs\0")] + [InlineData("R1000\0src/old.cs\0src/new.cs\0")] + [InlineData("R101\0src/old.cs\0src/new.cs\0")] + [InlineData("R50\0src/old.cs\0")] + [InlineData("A\0../outside\0")] + [InlineData("A\0src//file.cs\0")] + [InlineData("A\0src\\file.cs\0")] + [InlineData("A\0src/file\n.cs\0")] + [InlineData("A\0src/file\t.cs\0")] + [InlineData("A\0src/file.cs\0A\0src/file.cs\0")] + public void ParseNameStatus_ShouldRejectMalformedOrUnsafeRecords(string output) + { + var exception = Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(Encoding.UTF8.GetBytes(output))); + + Assert.Equal("ASEVD135", exception.Code); + } + + [Fact] + public void ParseNameStatus_ShouldRejectInvalidUtf8AndOversizedPath() + { + var invalidUtf8 = new byte[] { (byte)'A', 0, 0xff, 0 }; + var longPath = Encoding.UTF8.GetBytes($"A\0{new string('x', EvidenceGitChangeCapture.MaximumPathBytes + 1)}\0"); + + Assert.Equal("ASEVD135", Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(invalidUtf8)).Code); + Assert.Equal("ASEVD135", Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(longPath)).Code); + } + + [Fact] + public void ParseNameStatus_ShouldBoundRecordCount() + { + var builder = new StringBuilder(); + for (var index = 0; index <= EvidenceGitChangeCapture.MaximumChangedRecords; index++) + { + builder.Append("A\0src/file").Append(index).Append(".cs\0"); + } + + var exception = Assert.Throws( + () => EvidenceGitChangeCapture.ParseNameStatus(Encoding.UTF8.GetBytes(builder.ToString()))); + + Assert.Equal("ASEVD134", exception.Code); + } + + [Fact] + public async Task CaptureAndVerify_ShouldBindExactCommitsAndIncludeBinaryPath() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "code.cs"), "before\n"); + repository.Run("add", "code.cs"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + + File.WriteAllText(Path.Join(repository.Path, "code.cs"), "after\n"); + File.WriteAllBytes(Path.Join(repository.Path, "blob.bin"), [0, 1, 2, 255, 0, 254]); + repository.Run("add", "code.cs", "blob.bin"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(Path.Join(repository.Path, "unrelated.txt"), "later\n"); + repository.Run("add", "unrelated.txt"); + repository.Commit("ambient-head-moved"); + repository.Run("config", "diff.external", "false"); + + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + await EvidenceGitChangeCapture.VerifyAsync(repository.Path, snapshot); + + Assert.Equal(baseRevision, snapshot.BaseRevision); + Assert.Equal(headRevision, snapshot.HeadRevision); + Assert.Equal(64, snapshot.SourceDiffDigest.Length); + Assert.Equal(64, snapshot.NameStatusDigest.Length); + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "blob.bin" && path.Kind == "added"); + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "code.cs" && path.Kind == "modified"); + Assert.DoesNotContain(snapshot.ChangedPaths, path => path.Path == "unrelated.txt"); + Assert.Contains("diff --git", Encoding.UTF8.GetString(snapshot.SourceDiff.Span), StringComparison.Ordinal); + } + + [Fact] + public async Task Capture_ShouldSelectRenameModeSymlinkAndSubmoduleWithoutTextHunks() + { + using var repository = new GitFixture(); + File.WriteAllText(Path.Join(repository.Path, "mode.sh"), "#!/bin/sh\n"); + File.WriteAllText(Path.Join(repository.Path, "old.txt"), "unchanged\n"); + repository.Run("add", "mode.sh", "old.txt"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + + repository.Run("mv", "old.txt", "moved.txt"); + repository.Run("update-index", "--chmod=+x", "mode.sh"); + if (!OperatingSystem.IsWindows()) + { + File.CreateSymbolicLink(Path.Join(repository.Path, "linked"), "moved.txt"); + repository.Run("add", "linked"); + } + repository.Run("update-index", "--add", "--cacheinfo", $"160000,{baseRevision},submodule"); + repository.Commit("nontext"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "moved.txt" && path.PreviousPath == "old.txt" && path.Kind == "renamed"); + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "mode.sh" && path.Kind == "modified"); + if (!OperatingSystem.IsWindows()) + { + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "linked" && path.Kind == "added"); + } + Assert.Contains(snapshot.ChangedPaths, path => path.Path == "submodule" && path.Kind == "added"); + } + + [Theory] + [InlineData("main")] + [InlineData("abc123")] + [InlineData("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")] + public async Task Capture_ShouldRejectRefsAndNonCanonicalObjectIds(string revision) + { + using var repository = new GitFixture(); + + var exception = await Assert.ThrowsAsync( + () => EvidenceGitChangeCapture.CaptureAsync(repository.Path, revision, revision)); + + Assert.Equal("ASEVD130", exception.Code); + } + + [Fact] + public async Task Capture_ShouldRejectMissingCommitObject() + { + using var repository = new GitFixture(); + var missingRevision = new string('a', 40); + + var exception = await Assert.ThrowsAsync( + () => EvidenceGitChangeCapture.CaptureAsync(repository.Path, missingRevision, missingRevision)); + + Assert.Equal("ASEVD136", exception.Code); + } + + [Fact] + public async Task RevisionBoundCli_ShouldRecreateV2IdentityAndRejectTamperedDiffOrPolicy() + { + using var repository = new GitFixture(); + Directory.CreateDirectory(Path.Join(repository.Path, "docs")); + var documentPath = Path.Join(repository.Path, "docs", "readme.md"); + File.WriteAllText(documentPath, "before\n"); + repository.Run("add", "docs/readme.md"); + repository.Commit("base"); + var baseRevision = repository.Run("rev-parse", "HEAD").Trim(); + File.WriteAllText(documentPath, "after\n"); + repository.Run("add", "docs/readme.md"); + repository.Commit("head"); + var headRevision = repository.Run("rev-parse", "HEAD").Trim(); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repository.Path, baseRevision, headRevision); + var diffPath = Path.Join(repository.Path, "change.diff"); + await File.WriteAllBytesAsync(diffPath, snapshot.SourceDiff.ToArray()); + var policyPath = Path.Join(repository.Path, "policy.json"); + var policy = CreateGatePolicy(); + await File.WriteAllBytesAsync(policyPath, EvidenceCanonicalJson.Serialize(policy)); + var workflow = new EvidenceCliWorkflow(new EvidencePlanner()); + var request = new EvidencePlanningRequest(policyPath, [], diffPath, baseRevision, headRevision, repository.Path, GateMode: true); + + var first = await workflow.ExplainAsync(request, CancellationToken.None); + var second = await workflow.ExplainAsync(request, CancellationToken.None); + Assert.Equal(first.PlanDigest, second.PlanDigest); + Assert.Equal("2.0", first.ContractVersion); + Assert.Equal(snapshot.SourceDiffDigest, first.SourceDiffDigest); + Assert.Equal(snapshot.NameStatusDigest, first.NameStatusDigest); + var manifest = EvidenceManifestBuilder.Build(first, []); + Assert.True(EvidenceManifestBuilder.Verify(first, manifest)); + Assert.Equal(baseRevision, manifest.BaseRevision); + Assert.Equal(headRevision, manifest.HeadRevision); + + var capturedIdentity = new EvidencePullRequestRunIdentity(123, 123, 777, "main", 456, 1); + var identifiedPlan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(new EvidencePlanner(), policy, snapshot, capturedIdentity); + var identifiedManifest = EvidenceManifestBuilder.Build(identifiedPlan, []); + Assert.Equal(capturedIdentity, identifiedManifest.PullRequestRunIdentity); + await EvidenceRevisionPlanBuilder.VerifyAsync(new EvidencePlanner(), policy, repository.Path, identifiedPlan, expectedRunIdentity: capturedIdentity); + Assert.Equal("ASEVD139", (await Assert.ThrowsAsync(() => + EvidenceRevisionPlanBuilder.VerifyAsync(new EvidencePlanner(), policy, repository.Path, identifiedPlan, + expectedRunIdentity: capturedIdentity with { WorkflowRunAttempt = 2 }))).Code); + var identityPath = Path.Join(repository.Path, "pr-run-identity.json"); + await File.WriteAllBytesAsync(identityPath, EvidenceCanonicalJson.Serialize(capturedIdentity)); + var cliIdentified = await workflow.ExplainAsync(request with { PullRequestRunIdentityFile = identityPath }, CancellationToken.None); + Assert.Equal(identifiedPlan.PlanDigest, cliIdentified.PlanDigest); + + var output = Path.Join(repository.Path, "output"); + await workflow.WritePlanAsync(first, output, CancellationToken.None); + await workflow.WriteManifestAsync(manifest, output, CancellationToken.None); + var planPath = Path.Join(output, "evidence-plan.json"); + var manifestPath = Path.Join(output, "evidence-manifest.json"); + await workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None, policyPath, repository.Path); + Assert.Contains("ASEVD232", (await Assert.ThrowsAsync( + () => workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None))).Message, StringComparison.Ordinal); + + await File.AppendAllTextAsync(manifestPath, "\n"); + Assert.Contains("ASEVD209", (await Assert.ThrowsAsync( + () => workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None, policyPath, repository.Path))).Message, StringComparison.Ordinal); + await workflow.WriteManifestAsync(manifest, output, CancellationToken.None); + + File.AppendAllText(diffPath, "tampered"); + Assert.Contains("ASEVD231", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(request, CancellationToken.None))).Message, StringComparison.Ordinal); + + await File.WriteAllBytesAsync(policyPath, EvidenceCanonicalJson.Serialize(policy with { Id = "substituted" })); + Assert.Equal("ASEVD139", (await Assert.ThrowsAsync( + () => EvidenceRevisionPlanBuilder.VerifyAsync(new EvidencePlanner(), policy with { Id = "substituted" }, repository.Path, first))).Code); + Assert.Contains("ASEVD203", (await Assert.ThrowsAsync( + () => workflow.VerifyAsync(planPath, manifestPath, CancellationToken.None, policyPath, repository.Path))).Message, StringComparison.Ordinal); + } + + [Fact] + public async Task RevisionBoundCli_ShouldRejectPartialAndPathOnlyGateInputs() + { + using var repository = new GitFixture(); + var policyPath = Path.Join(repository.Path, "policy.json"); + await File.WriteAllBytesAsync(policyPath, EvidenceCanonicalJson.Serialize(CreateGatePolicy())); + var workflow = new EvidenceCliWorkflow(new EvidencePlanner()); + + var partial = new EvidencePlanningRequest(policyPath, [], null, BaseRevision: new string('a', 40)); + Assert.Contains("ASEVD230", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(partial, CancellationToken.None))).Message, StringComparison.Ordinal); + var pathOnly = new EvidencePlanningRequest(policyPath, ["docs/readme.md"], null, GateMode: true); + Assert.Contains("ASEVD230", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(pathOnly, CancellationToken.None))).Message, StringComparison.Ordinal); + Assert.Contains("ASEVD233", (await Assert.ThrowsAsync( + () => workflow.ExplainAsync(pathOnly with { GateMode = false, PullRequestRunIdentityFile = "identity.json" }, CancellationToken.None))).Message, StringComparison.Ordinal); + } + + private static EvidencePolicy CreateGatePolicy() + { + var all = new EvidenceProfile( + "all", EvidenceProfileScope.Targeted, [], + [new EvidenceProducerDeclaration("build", "build", "1", [], ["build/pass"], [], 60)], + [new EvidenceObligation("build", "code", "Code requires a build.", ["build"], "build/pass")]); + var docs = new EvidenceProfile("docs", EvidenceProfileScope.Targeted, [], [], []); + return new EvidencePolicy("gate", "1", "all", [all, docs], [new EvidencePolicyRule("docs", "docs/**", "docs")]); + } + + private sealed class GitFixture : IDisposable + { + public GitFixture() + { + Path = System.IO.Path.Join(System.IO.Path.GetTempPath(), $"appsurface-evidence-git-{Guid.NewGuid():N}"); + Directory.CreateDirectory(Path); + Run("init", "-q"); + } + + public string Path { get; } + + public void Commit(string message) => Run( + "-c", "user.name=AppSurface Test", "-c", "user.email=appsurface@example.invalid", + "commit", "-qm", message); + + public string Run(params string[] arguments) + { + var start = new ProcessStartInfo("git") + { + WorkingDirectory = Path, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEnd(); + var error = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Assert.True(process.ExitCode == 0, $"git {string.Join(' ', arguments)} failed: {error}"); + return output; + } + + public void Dispose() => Directory.Delete(Path, recursive: true); + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceNoFollowArtifactExtractorTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceNoFollowArtifactExtractorTests.cs new file mode 100644 index 000000000..941ff9adc --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidenceNoFollowArtifactExtractorTests.cs @@ -0,0 +1,320 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using ForgeTrust.AppSurface.Evidence.Contracts; +using Microsoft.Win32.SafeHandles; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class EvidenceNoFollowArtifactExtractorTests +{ + [Fact] + public async Task ExtractAsync_ShouldStreamRegularFileIntoItsDeclaredArtifactSlot() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var expected = new byte[] { 0, 1, 2, 0xff, 0x80 }; + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "report.bin"), expected); + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + + var results = await EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/report.bin", "reports/report.bin")]); + + var result = Assert.Single(results); + Assert.Equal("report", result.LogicalName); + Assert.Equal(expected.LongLength, result.LengthBytes); + Assert.Equal(Convert.ToHexString(SHA256.HashData(expected)).ToLowerInvariant(), result.Sha256); + Assert.Equal(expected, await File.ReadAllBytesAsync(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + Assert.True(await writer.VerifyWrittenArtifactsAsync()); + } + + [Theory] + [InlineData("../outside")] + [InlineData("subject/../outside")] + [InlineData("subject/./report.bin")] + [InlineData("/etc/passwd")] + [InlineData("//outside")] + [InlineData("subject//report.bin")] + [InlineData("subject\\report.bin")] + [InlineData("./report.bin")] + public async Task ExtractAsync_ShouldRejectNonCanonicalOrTraversingSourcePaths(string sourcePath) + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + var exception = await Assert.ThrowsAsync(() => + EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [new EvidenceNoFollowArtifact("report", sourcePath, "reports/report.bin")])); + Assert.NotNull(exception.ParamName); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectDuplicateLogicalSourceAndDestinationEntriesBeforeOpeningRoot() + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + var writer = CreateWriter(Path.GetTempPath()); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [ + new EvidenceNoFollowArtifact("report", "subject/one.bin", "reports/one.bin"), + new EvidenceNoFollowArtifact("report", "subject/two.bin", "reports/two.bin"), + ])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [ + new EvidenceNoFollowArtifact("first", "subject/one.bin", "reports/one.bin"), + new EvidenceNoFollowArtifact("second", "subject/one.bin", "reports/two.bin"), + ])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + writer, + [ + new EvidenceNoFollowArtifact("first", "subject/one.bin", "reports/same.bin"), + new EvidenceNoFollowArtifact("second", "subject/two.bin", "reports/same.bin"), + ])); + } + + [Fact] + public async Task ExtractAsync_ShouldEnforceFileCountAndCallerLimitCeilings() + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + var tooManyFiles = Enumerable.Range(0, EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount + 1) + .Select(index => new EvidenceNoFollowArtifact($"artifact-{index}", $"subject/{index}.bin", $"reports/{index}.bin")) + .ToArray(); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + tooManyFiles)); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [], + new EvidenceNoFollowArtifactExtractionLimits { MaximumTotalBytes = EvidenceArtifactWriter.MaximumTotalArtifactBytes + 1 })); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [], + new EvidenceNoFollowArtifactExtractionLimits { MaximumDuration = TimeSpan.FromMinutes(3) })); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectSymlinksAndFilesOutsideTheScratchRoot() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + Directory.CreateDirectory(Path.Join(temp.OutsideRoot, "private")); + var outsideFile = Path.Join(temp.OutsideRoot, "private", "secret.bin"); + await File.WriteAllTextAsync(outsideFile, "outside"); + File.CreateSymbolicLink(Path.Join(temp.ScratchRoot, "subject", "linked.bin"), outsideFile); + Directory.CreateSymbolicLink(Path.Join(temp.ScratchRoot, "linked-directory"), Path.Join(temp.OutsideRoot, "private")); + using var root = OpenTrustedRoot(temp.ScratchRoot); + + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/linked.bin", "reports/report.bin")])); + await Assert.ThrowsAnyAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "linked-directory/secret.bin", "reports/report.bin")])); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectHardlinksDirectoriesAndAggregateByteOverflow() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + await File.WriteAllTextAsync(Path.Join(temp.ScratchRoot, "subject", "one.bin"), "hard-linked"); + if (Link( + Path.Join(temp.ScratchRoot, "subject", "one.bin"), + Path.Join(temp.ScratchRoot, "subject", "second-name.bin")) != 0) + { + throw new IOException($"Could not create the Linux hard-link fixture (errno {Marshal.GetLastPInvokeError()})."); + } + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject", "directory")); + using var root = OpenTrustedRoot(temp.ScratchRoot); + + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/one.bin", "reports/report.bin")])); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/directory", "reports/report.bin")])); + + File.Delete(Path.Join(temp.ScratchRoot, "subject", "second-name.bin")); + await File.WriteAllBytesAsync(Path.Join(temp.ScratchRoot, "subject", "small.bin"), [1, 2, 3]); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + CreateWriter(temp.ArtifactRoot), + [new EvidenceNoFollowArtifact("report", "subject/small.bin", "reports/report.bin")], + new EvidenceNoFollowArtifactExtractionLimits { MaximumTotalBytes = 2 })); + } + + [Fact] + public async Task ExtractAsync_ShouldRejectContentChangedDuringStreamingBeforePromotion() + { + if (!OperatingSystem.IsLinux()) + { + await AssertUnsupportedPlatformFailsClosedAsync(); + return; + } + + using var temp = new TemporaryDirectory(); + Directory.CreateDirectory(temp.ScratchRoot); + Directory.CreateDirectory(temp.ArtifactRoot); + Directory.CreateDirectory(Path.Join(temp.ScratchRoot, "subject")); + var sourcePath = Path.Join(temp.ScratchRoot, "subject", "large.bin"); + await using (var created = new FileStream(sourcePath, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite)) + { + created.SetLength(64L * 1024 * 1024); + } + + using var root = OpenTrustedRoot(temp.ScratchRoot); + var writer = CreateWriter(temp.ArtifactRoot); + var extraction = EvidenceNoFollowArtifactExtractor.ExtractAsync( + root, + writer, + [new EvidenceNoFollowArtifact("report", "subject/large.bin", "reports/report.bin")]); + + var changed = false; + await using (var mutator = new FileStream(sourcePath, FileMode.Open, FileAccess.Write, FileShare.ReadWrite)) + { + while (!extraction.IsCompleted && !changed) + { + mutator.Position = 0; + await mutator.WriteAsync(new byte[] { 0xff }); + await mutator.FlushAsync(); + changed = true; + } + } + + if (!changed) + { + await extraction; + return; + } + + await Assert.ThrowsAsync(() => extraction); + Assert.Empty(writer.WrittenArtifacts); + Assert.False(File.Exists(Path.Join(temp.ArtifactRoot, "reports", "report.bin"))); + } + + [Fact] + public async Task ExtractAsync_OnUnsupportedPlatform_ShouldFailClosed() + { + if (OperatingSystem.IsLinux()) + { + return; + } + + await AssertUnsupportedPlatformFailsClosedAsync(); + } + + private static async Task AssertUnsupportedPlatformFailsClosedAsync() + { + using var invalidRoot = new SafeFileHandle(IntPtr.Zero, ownsHandle: false); + await Assert.ThrowsAsync(() => EvidenceNoFollowArtifactExtractor.ExtractAsync( + invalidRoot, + CreateWriter(Path.GetTempPath()), + [])); + } + + private static EvidenceArtifactWriter CreateWriter(string artifactRoot) + { + var producer = new EvidenceProducerDeclaration( + "extractor-test", + "test", + "1.0.0", + [], + [], + [new EvidenceArtifactSlot("report", "reports", "application/octet-stream", Required: false, EvidenceArtifactWriter.MaximumTotalArtifactBytes)], + TimeoutSeconds: 120); + return new EvidenceArtifactWriter(producer, artifactRoot); + } + + private static SafeFileHandle OpenTrustedRoot(string path) + { + // The test controls this fixture path; the extractor itself verifies the opened handle is a directory. + var descriptor = Open(path, flags: 0); + if (descriptor < 0) + { + throw new IOException($"Could not open the Linux scratch root (errno {Marshal.GetLastPInvokeError()})."); + } + + return new SafeFileHandle(new IntPtr(descriptor), ownsHandle: true); + } + + [DllImport("libc", EntryPoint = "open", SetLastError = true)] + private static extern int Open([MarshalAs(UnmanagedType.LPUTF8Str)] string path, int flags); + + [DllImport("libc", EntryPoint = "link", SetLastError = true)] + private static extern int Link( + [MarshalAs(UnmanagedType.LPUTF8Str)] string existingPath, + [MarshalAs(UnmanagedType.LPUTF8Str)] string newPath); + + private sealed class TemporaryDirectory : IDisposable + { + private readonly string _path = Path.Join(Path.GetTempPath(), "evidence-nofollow-" + Guid.NewGuid().ToString("N")); + + public string ScratchRoot => Path.Join(_path, "scratch"); + + public string ArtifactRoot => Path.Join(_path, "artifacts"); + + public string OutsideRoot => Path.Join(_path, "outside"); + + public TemporaryDirectory() + { + Directory.CreateDirectory(_path); + } + + public void Dispose() + { + try + { + Directory.Delete(_path, recursive: true); + } + catch (IOException) + { + // Preserve the test result if the operating system still has a transient handle open. + } + catch (UnauthorizedAccessException) + { + // Preserve the test result if the operating system still has a transient handle open. + } + } + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs index 32d4eff50..8809dc79a 100644 --- a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePlannerTests.cs @@ -95,6 +95,274 @@ public void Resolve_ShouldRejectEmptyConservativeProfile() Assert.Contains("ASEVD105", exception.Message, StringComparison.Ordinal); } + [Fact] + public void ResolveForGate_ShouldUseConservativeProfileForDocumentationAndCodeDiff() + { + var documentation = CreateNoEvidenceProfile(); + var code = CreateCoverageProfile(EvidenceProfileScope.Targeted) with { Id = "code" }; + var policy = CreateGatePolicy(code with { Id = "conservative" }, documentation, code); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [GatePath(0, "readme.md"), GatePath(1, "Feature.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains("conservative:conservative", plan.MatchedRuleIds, StringComparer.Ordinal); + } + + [Fact] + public void ValidateGatePolicy_ShouldKeepLegacyLocalV1ValidationAndSelectionCompatible() + { + var targetedResourceProfile = CreateRequirementProfile("integration"); + var conservative = CreateCoverageProfile(EvidenceProfileScope.Targeted) with { Id = "conservative" }; + var policy = CreateGatePolicy(conservative, targetedResourceProfile); + + EvidencePlanner.ValidatePolicy(policy); + var localPlan = new EvidencePlanner().Resolve(policy, [GatePath(0, "integration.cs"), new NormalizedDiffPath("unmapped/file.cs")]); + + Assert.Equal("conservative", localPlan.Profile.Id); + AssertGatePolicyFailure(policy, "resource 'database'"); + } + + [Fact] + public void ResolveForGate_ShouldPreserveResourceAndCodeRequirementsInMixedProfile() + { + var integration = CreateRequirementProfile("integration"); + var code = CreateCoverageProfile(EvidenceProfileScope.Targeted) with { Id = "code" }; + var conservative = MergeProfiles("conservative", integration, code); + var policy = CreateGatePolicy(conservative, integration, code); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [GatePath(0, "database-tests.cs"), GatePath(1, "Feature.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains(plan.Profile.Resources, resource => resource.Id == "database"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "integration-tests"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + } + + [Fact] + public void ResolveForGate_ShouldPreserveResourceRequirementsInDocumentationAndResourceDiff() + { + var documentation = CreateNoEvidenceProfile(); + var integration = CreateRequirementProfile("integration"); + var conservative = MergeProfiles("conservative", integration); + var policy = CreateGatePolicy(conservative, documentation, integration); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [GatePath(0, "guide.md"), GatePath(1, "database-tests.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains(plan.Profile.Resources, resource => resource.Id == "database"); + Assert.Contains(plan.Profile.Producers, producer => producer.RequiredResources.Contains("database", StringComparer.Ordinal)); + } + + [Fact] + public void ResolveForGate_ShouldPreserveControlPlaneRequirementsWhenRenameCrossesProfileRules() + { + var documentation = CreateNoEvidenceProfile(); + var controlPlane = CreateRequirementProfile("control-plane"); + var conservative = MergeProfiles("conservative", controlPlane); + var policy = CreateGatePolicy(conservative, documentation, controlPlane); + + var plan = new EvidencePlanner().ResolveForGate( + policy, + [new NormalizedDiffPath("gate/0/evidence-guide.md", "renamed", "gate/1/evidence.policy.json")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains("target-0", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains("target-1", plan.MatchedRuleIds, StringComparer.Ordinal); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "integration-tests"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingProducer() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = CreateCoverageProfile(EvidenceProfileScope.Targeted) with + { + Id = "conservative", + Resources = targeted.Resources, + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "producer 'integration-tests'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingResource() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Resources = [], + Producers = [targeted.Producers[0] with { RequiredResources = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "resource 'database'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingAssertion() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = [targeted.Producers[0] with { AssertionIds = ["integration/ready@2"] }], + Obligations = [targeted.Obligations[0] with { RequiredAssertionId = "integration/ready@2" }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "assertion 'integration/passed@1'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingArtifactSlot() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = [targeted.Producers[0] with { ArtifactSlots = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "artifact slot 'integration-tests/report'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectMissingObligation() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with { Id = "conservative", Obligations = [] }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "obligation 'integration'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectAWeakenedResourceDependency() + { + var database = new EvidenceResourceDeclaration("database", "aspire_health", 30, []); + var migration = new EvidenceResourceDeclaration("migration", "completion", 30, ["database"]); + var targeted = CreateRequirementProfile("integration") with + { + Resources = [database, migration], + Producers = [CreateRequirementProfile("integration").Producers[0] with { RequiredResources = ["migration"] }], + }; + var otherwiseValid = targeted with + { + Id = "conservative", + Resources = [database, migration with { Requires = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "resource dependency 'database'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectAProducerThatNoLongerRequiresATargetedResource() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = [targeted.Producers[0] with { RequiredResources = [] }], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "resource 'database' required by producer 'integration-tests'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectWeakenedArtifactBounds() + { + var targeted = CreateRequirementProfile("integration"); + var otherwiseValid = targeted with + { + Id = "conservative", + Producers = + [ + targeted.Producers[0] with + { + ArtifactSlots = [targeted.Producers[0].ArtifactSlots[0] with { MaximumBytes = 2048 }], + }, + ], + }; + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "artifact slot 'integration-tests/report'"); + } + + [Fact] + public void ValidateGatePolicy_ShouldRejectAnObligationThatNoLongerRequiresItsProducer() + { + var targeted = CreateRequirementProfile("integration"); + var coverage = CreateCoverageProfile(EvidenceProfileScope.Targeted); + var coverageProducer = coverage.Producers[0] with + { + AssertionIds = [.. coverage.Producers[0].AssertionIds, targeted.Obligations[0].RequiredAssertionId], + }; + var otherwiseValid = new EvidenceProfile( + "conservative", + EvidenceProfileScope.Targeted, + targeted.Resources, + [targeted.Producers[0], coverageProducer], + [ + targeted.Obligations[0] with { RequiredProducerIds = ["coverage"] }, + coverage.Obligations[0], + ]); + + AssertGatePolicyFailure(CreateGatePolicy(otherwiseValid, targeted), "producer 'integration-tests' required by obligation 'integration'"); + } + + [Fact] + public void ResolveForGate_ShouldAcceptAConservativeSupersetWithAdditionalEvidence() + { + var targeted = CreateRequirementProfile("integration"); + var additionalResource = new EvidenceResourceDeclaration("cache", "completion", 45, []); + var requiredProducer = targeted.Producers[0] with + { + RequiredResources = ["database", "cache"], + AssertionIds = ["integration/passed@1", "integration/details@1"], + ArtifactSlots = + [ + targeted.Producers[0].ArtifactSlots[0] with { MaximumBytes = 512 }, + new EvidenceArtifactSlot("details", "integration", "application/json", Required: false, MaximumBytes: 256), + ], + }; + var coverage = CreateCoverageProfile(EvidenceProfileScope.Targeted); + var conservative = new EvidenceProfile( + "conservative", + EvidenceProfileScope.Targeted, + [.. targeted.Resources, additionalResource], + [requiredProducer, coverage.Producers[0]], + [ + targeted.Obligations[0], + coverage.Obligations[0], + ]); + var policy = CreateGatePolicy(conservative, targeted); + + var plan = new EvidencePlanner().ResolveForGate(policy, [GatePath(0, "integration.cs"), new NormalizedDiffPath("unmapped/file.cs")]); + + Assert.Equal("conservative", plan.Profile.Id); + Assert.Contains(plan.Profile.Resources, resource => resource.Id == "cache"); + Assert.Contains(plan.Profile.Producers, producer => producer.Id == "coverage"); + Assert.Contains(plan.Profile.Producers.Single(producer => producer.Id == "integration-tests").ArtifactSlots, slot => slot.LogicalName == "details"); + } + + [Fact] + public void ResolveForGate_ShouldKeepExplicitEmptyTargetedDocumentationProfile() + { + var documentation = CreateNoEvidenceProfile(); + var code = CreateCoverageProfile(EvidenceProfileScope.Targeted); + var policy = CreateGatePolicy(code with { Id = "conservative" }, documentation, code); + + var plan = new EvidencePlanner().ResolveForGate(policy, [GatePath(0, "guide.md")]); + var manifest = EvidenceManifestBuilder.Build(plan, []); + + Assert.Equal("no-evidence", plan.Profile.Id); + Assert.Empty(plan.Profile.Producers); + Assert.Equal(EvidenceClaimKind.NoEvidenceRequired, manifest.ClaimKind); + } + [Fact] public void UnifiedDiffReader_ShouldReadAddedDeletedAndModifiedPaths() { @@ -852,6 +1120,52 @@ private static void AssertPlanningCode(Action action, string code) Assert.Equal(code, exception.Code); } + private static void AssertGatePolicyFailure(EvidencePolicy policy, string expectedRequirement) + { + var exception = Assert.Throws(() => EvidencePlanner.ValidateGatePolicy(policy)); + + Assert.Equal("ASEVD129", exception.Code); + Assert.Contains(expectedRequirement, exception.Message, StringComparison.Ordinal); + } + + private static EvidencePolicy CreateGatePolicy(EvidenceProfile conservative, params EvidenceProfile[] targetedProfiles) + { + var profiles = new List { conservative }; + profiles.AddRange(targetedProfiles); + var rules = targetedProfiles + .Select((profile, index) => new EvidencePolicyRule($"target-{index}", $"gate/{index}/*", profile.Id)) + .ToArray(); + + return new EvidencePolicy("gate-policy", "1", conservative.Id, profiles, rules); + } + + private static EvidenceProfile MergeProfiles(string id, params EvidenceProfile[] profiles) => new( + id, + EvidenceProfileScope.Targeted, + profiles.SelectMany(static profile => profile.Resources).ToArray(), + profiles.SelectMany(static profile => profile.Producers).ToArray(), + profiles.SelectMany(static profile => profile.Obligations).ToArray()); + + private static EvidenceProfile CreateRequirementProfile(string id) + { + var assertionId = "integration/passed@1"; + return new EvidenceProfile( + id, + EvidenceProfileScope.Targeted, + [new EvidenceResourceDeclaration("database", "aspire_health", 30, [])], + [new EvidenceProducerDeclaration( + "integration-tests", + "integration-tests", + "1.0.0", + ["database"], + [assertionId], + [new EvidenceArtifactSlot("report", "integration", "application/json", Required: true, MaximumBytes: 1024)], + 60)], + [new EvidenceObligation("integration", "integration", "The integration profile must pass.", ["integration-tests"], assertionId)]); + } + + private static NormalizedDiffPath GatePath(int profileIndex, string path) => new($"gate/{profileIndex}/{path}"); + private static EvidencePolicy CreatePolicy() => new( "sample", "1", diff --git a/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePullRequestGateVerifierTests.cs b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePullRequestGateVerifierTests.cs new file mode 100644 index 000000000..8c2d0fcfe --- /dev/null +++ b/Cli/ForgeTrust.AppSurface.Cli.Tests/EvidencePullRequestGateVerifierTests.cs @@ -0,0 +1,518 @@ +using System.Diagnostics; +using ForgeTrust.AppSurface.Evidence.Contracts; +using ForgeTrust.AppSurface.Evidence.Planner; +using ForgeTrust.AppSurface.Testing; + +namespace ForgeTrust.AppSurface.Cli.Tests; + +public sealed class EvidencePullRequestGateVerifierTests +{ + [Fact] + public async Task VerifyAsync_ShouldAcceptCompleteRevisionBoundEvidenceAndReturnTrustedSummary() + { + await using var fixture = await GateFixture.CreateAsync(); + + var result = await fixture.VerifyAsync(); + + Assert.True(result.IsEligible); + Assert.Equal("ASEVG000", result.Code); + Assert.NotNull(result.Summary); + Assert.Equal("targeted", result.Summary.ProfileId); + Assert.Equal("matched-policy-rules", result.Summary.SelectionRationale); + Assert.Equal(["compile"], result.Summary.SelectedObligationIds); + Assert.Equal(["compile"], result.Summary.ClosedObligationIds); + Assert.Empty(result.Summary.MissingObligationIds); + Assert.Equal("source", Assert.Single(result.Summary.MatchedRules).Id); + Assert.Equal(fixture.Plan.BaseRevision![..12], result.Summary.BaseRevisionShort); + Assert.Equal(fixture.Plan.HeadRevision![..12], result.Summary.HeadRevisionShort); + Assert.Equal("compile", Assert.Single(result.Summary.ObligationRationales).Id); + } + + [Fact] + public async Task VerifyAsync_ShouldAcceptExplicitEmptyDocumentationClaimWithoutArtifactHandoff() + { + await using var fixture = await GateFixture.CreateAsync(documentationOnly: true); + + var result = await fixture.VerifyAsync( + trustedArtifactHandoffRootPath: null, + artifactVerifier: null, + omitArtifactRoot: true, + useFakeArtifactVerifier: false); + + Assert.True(result.IsEligible); + Assert.Equal(EvidenceClaimKind.NoEvidenceRequired, fixture.Manifest.ClaimKind); + Assert.NotNull(result.Summary); + Assert.Equal("docs", result.Summary.ProfileId); + Assert.Empty(result.Summary.SelectedObligationIds); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Empty(result.Summary.MissingObligationIds); + } + + [Fact] + public async Task VerifyAsync_ShouldFailClosedWhenNonemptyProfileHasNoTrustedArtifactRoot() + { + await using var fixture = await GateFixture.CreateAsync(); + + var result = await fixture.VerifyAsync( + trustedArtifactHandoffRootPath: null, + artifactVerifier: null, + omitArtifactRoot: true, + useFakeArtifactVerifier: false); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG009", result.Code); + Assert.NotNull(result.Summary); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Equal(["compile"], result.Summary.MissingObligationIds); + } + + [Fact] + public async Task VerifyAsync_ShouldRequireDeclaredAndIndependentlyAttestedIsolationForNonemptyEvidence() + { + await using var fixture = await GateFixture.CreateAsync(); + var missingManifestEnvelope = EvidenceManifestBuilder.Build( + fixture.Plan, + fixture.Manifest.ProducerResults); + + var missingEnvelopeResult = await fixture.VerifyAsync(manifest: missingManifestEnvelope); + var missingAuthorityResult = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectEnvelopeAttested = false }); + + Assert.Equal("ASEVG004", missingEnvelopeResult.Code); + Assert.Equal("ASEVG007", missingAuthorityResult.Code); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectForgeryEvenWhenPlanAndManifestDigestsAreRecomputed() + { + await using var fixture = await GateFixture.CreateAsync(); + var forgedPlan = fixture.Plan with { MatchedRuleIds = ["forged-rule"], PlanDigest = string.Empty }; + forgedPlan = forgedPlan with { PlanDigest = EvidenceDigest.CanonicalSha256(forgedPlan) }; + var forgedManifest = EvidenceManifestBuilder.Build(forgedPlan, fixture.Manifest.ProducerResults); + + var result = await fixture.VerifyAsync(plan: forgedPlan, manifest: forgedManifest); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG003", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectLegacyV1Plan() + { + await using var fixture = await GateFixture.CreateAsync(); + var legacyPlan = fixture.Plan with { ContractVersion = "1.0", PlanDigest = string.Empty }; + legacyPlan = legacyPlan with { PlanDigest = EvidenceDigest.CanonicalSha256(legacyPlan) }; + + var result = await fixture.VerifyAsync(plan: legacyPlan); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG002", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectTrustedPolicySubstitution() + { + await using var fixture = await GateFixture.CreateAsync(); + + var result = await fixture.VerifyAsync(policy: fixture.Policy with { Id = "other-policy" }); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG003", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectExpectedRunMismatchBeforeReturningSummary() + { + await using var fixture = await GateFixture.CreateAsync(); + + var result = await fixture.VerifyAsync(expectedIdentity: fixture.ExpectedIdentity with + { + RunIdentity = fixture.ExpectedIdentity.RunIdentity with { WorkflowRunAttempt = 2 }, + }); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG007", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectManifestRunIdentityMismatch() + { + await using var fixture = await GateFixture.CreateAsync(); + var mismatched = fixture.Manifest with + { + PullRequestRunIdentity = fixture.ExpectedIdentity.RunIdentity with { PullRequestNumber = 778 }, + ManifestDigest = string.Empty, + }; + mismatched = mismatched with { ManifestDigest = EvidenceDigest.CanonicalSha256(mismatched) }; + + var result = await fixture.VerifyAsync(manifest: mismatched); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectUnavailableOrMismatchedCurrentAuthority() + { + await using var fixture = await GateFixture.CreateAsync(); + + var unavailable = await fixture.VerifyAsync(authorityProvider: new FakeAuthorityProvider(null)); + var movedBase = await fixture.VerifyAsync(authority: fixture.Authority with { BaseRevision = new string('a', 40) }); + var movedHead = await fixture.VerifyAsync(authority: fixture.Authority with { HeadRevision = new string('b', 40) }); + var wrongJob = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectJobId = "other-job" }); + var wrongCheckout = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectJobHeadRevision = new string('c', 40) }); + var failedJob = await fixture.VerifyAsync(authority: fixture.Authority with { SubjectJobConclusion = "failure" }); + + Assert.Equal("ASEVG006", unavailable.Code); + Assert.All([movedBase, movedHead, wrongJob, wrongCheckout, failedJob], result => Assert.Equal("ASEVG007", result.Code)); + Assert.All([unavailable, movedBase, movedHead, wrongJob, wrongCheckout, failedJob], result => Assert.NotNull(result.Summary)); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectObservationOnlyAndCleanupFailure() + { + await using var fixture = await GateFixture.CreateAsync(); + var observation = EvidenceManifestBuilder.Build( + fixture.Plan, + fixture.Manifest.ProducerResults, + observationOnly: true); + var cleanupFailure = EvidenceManifestBuilder.Build( + fixture.Plan, + fixture.Manifest.ProducerResults, + metrics: new EvidenceExecutionMetrics(CleanupCompleted: false)); + var artifactVerifier = new FakeArtifactVerifier(true); + + var observationResult = await fixture.VerifyAsync(manifest: observation, artifactVerifier: artifactVerifier); + var cleanupResult = await fixture.VerifyAsync(manifest: cleanupFailure, artifactVerifier: artifactVerifier); + + Assert.Equal("ASEVG005", observationResult.Code); + Assert.Equal("ASEVG004", cleanupResult.Code); + Assert.False(observationResult.IsEligible); + Assert.False(cleanupResult.IsEligible); + } + + [Fact] + public async Task VerifyAsync_ShouldReportMissingObligationFromVerifiedPlanForIncompleteManifest() + { + await using var fixture = await GateFixture.CreateAsync(includeRequiredAssertion: false, includeArtifact: false); + var incompleteManifest = EvidenceManifestBuilder.Build(fixture.Plan, fixture.Manifest.ProducerResults); + + var result = await fixture.VerifyAsync(manifest: incompleteManifest, artifactVerifier: new FakeArtifactVerifier(true)); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG004", result.Code); + Assert.NotNull(result.Summary); + Assert.Equal(["compile"], result.Summary.SelectedObligationIds); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Equal(["compile"], result.Summary.MissingObligationIds); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectReleaseProfileSelectedForPullRequest() + { + await using var fixture = await GateFixture.CreateAsync(); + var releasePlan = fixture.Plan with + { + Profile = fixture.Plan.Profile with { Scope = EvidenceProfileScope.Release }, + PlanDigest = string.Empty, + }; + releasePlan = releasePlan with { PlanDigest = EvidenceDigest.CanonicalSha256(releasePlan) }; + var releaseManifest = EvidenceManifestBuilder.Build(releasePlan, fixture.Manifest.ProducerResults); + + var result = await fixture.VerifyAsync(plan: releasePlan, manifest: releaseManifest); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG003", result.Code); + Assert.Null(result.Summary); + } + + [Fact] + public async Task NoFollowArtifactVerifier_ShouldRejectForgedDigestMissingFileAndSymlinkOnLinux() + { + if (!OperatingSystem.IsLinux()) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + var verifier = new EvidencePullRequestGateNoFollowArtifactVerifier(); + + var valid = await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest); + Assert.True(valid); + + EvidenceArtifactResult artifact = fixture.Manifest.ProducerResults.Single().Artifacts!.Single(); + var forged = ReplaceArtifact(fixture.Manifest, artifact with { Sha256 = new string('0', 64) }); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, forged)); + + File.Delete(fixture.ArtifactPath); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + + var symlinkTarget = Path.Join(fixture.ArtifactRoot, "symlink-target.txt"); + File.WriteAllText(symlinkTarget, "artifact bytes"); + File.CreateSymbolicLink(fixture.ArtifactPath, symlinkTarget); + Assert.False(await verifier.VerifyArtifactsAsync(fixture.ArtifactRoot, fixture.Plan, fixture.Manifest)); + } + + [Fact] + public async Task VerifyAsync_ShouldRejectRecomputedManifestWithForgedArtifactHash() + { + if (!OperatingSystem.IsLinux()) + { + return; + } + + await using var fixture = await GateFixture.CreateAsync(); + EvidenceArtifactResult artifact = fixture.Manifest.ProducerResults.Single().Artifacts!.Single(); + var forgedManifest = ReplaceArtifact(fixture.Manifest, artifact with { Sha256 = new string('0', 64) }); + + var result = await fixture.VerifyAsync( + manifest: forgedManifest, + artifactVerifier: new EvidencePullRequestGateNoFollowArtifactVerifier()); + + Assert.False(result.IsEligible); + Assert.Equal("ASEVG010", result.Code); + Assert.NotNull(result.Summary); + Assert.Empty(result.Summary.ClosedObligationIds); + Assert.Equal(["compile"], result.Summary.MissingObligationIds); + } + + private static EvidenceManifest ReplaceArtifact(EvidenceManifest manifest, EvidenceArtifactResult replacement) + { + var producer = Assert.Single(manifest.ProducerResults); + var updated = manifest with + { + ProducerResults = [producer with { Artifacts = [replacement] }], + ManifestDigest = string.Empty, + }; + return updated with { ManifestDigest = EvidenceDigest.CanonicalSha256(updated) }; + } + + private sealed class FakeArtifactVerifier(bool result) : IEvidencePullRequestGateArtifactVerifier + { + public Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default) => Task.FromResult(result); + } + + private sealed class FakeAuthorityProvider(EvidencePullRequestGateAuthoritySnapshot? snapshot) + : IEvidencePullRequestGateAuthorityProvider + { + public Task ReadFreshAsync( + EvidencePullRequestGateExpectedIdentity expectedIdentity, + CancellationToken cancellationToken = default) => Task.FromResult(snapshot); + } + + private sealed class GateFixture : IAsyncDisposable + { + private readonly string _repositoryPath; + + private GateFixture( + string repositoryPath, + string artifactRoot, + string artifactPath, + EvidencePolicy policy, + EvidencePullRequestRunIdentity runIdentity, + EvidencePullRequestGateExpectedIdentity expectedIdentity, + EvidencePlan plan, + EvidenceManifest manifest, + EvidencePullRequestGateAuthoritySnapshot authority) + { + _repositoryPath = repositoryPath; + ArtifactRoot = artifactRoot; + ArtifactPath = artifactPath; + Policy = policy; + RunIdentity = runIdentity; + ExpectedIdentity = expectedIdentity; + Plan = plan; + Manifest = manifest; + Authority = authority; + } + + public string ArtifactRoot { get; } + + public string ArtifactPath { get; } + + public EvidencePolicy Policy { get; } + + public EvidencePullRequestRunIdentity RunIdentity { get; } + + public EvidencePullRequestGateExpectedIdentity ExpectedIdentity { get; } + + public EvidencePlan Plan { get; } + + public EvidenceManifest Manifest { get; } + + public EvidencePullRequestGateAuthoritySnapshot Authority { get; } + + public static async Task CreateAsync( + bool documentationOnly = false, + bool includeRequiredAssertion = true, + bool includeArtifact = true) + { + var repositoryPath = Path.Join(Path.GetTempPath(), $"appsurface-pr-gate-{Guid.NewGuid():N}"); + Directory.CreateDirectory(repositoryPath); + RunGit(repositoryPath, "init", "-q"); + var sourcePath = documentationOnly ? "docs/readme.md" : "src/project.cs"; + WriteFile(repositoryPath, sourcePath, "before\n"); + RunGit(repositoryPath, "add", sourcePath); + Commit(repositoryPath, "base"); + var baseRevision = RunGit(repositoryPath, "rev-parse", "HEAD").Trim(); + WriteFile(repositoryPath, sourcePath, "after\n"); + RunGit(repositoryPath, "add", sourcePath); + Commit(repositoryPath, "head"); + var headRevision = RunGit(repositoryPath, "rev-parse", "HEAD").Trim(); + + var targetProducer = new EvidenceProducerDeclaration( + "build", + "build", + "1", + [], + ["build/passed"], + [new EvidenceArtifactSlot("report", "reports", "text/plain", Required: false, MaximumBytes: 1024)], + TimeoutSeconds: 30); + var targeted = new EvidenceProfile( + "targeted", + EvidenceProfileScope.Targeted, + [], + [targetProducer], + [new EvidenceObligation("compile", "code", "Compile the changed source.", ["build"], "build/passed")]); + var docs = new EvidenceProfile("docs", EvidenceProfileScope.Targeted, [], [], []); + var policy = new EvidencePolicy( + "pr-gate", + "1", + "targeted", + [targeted, docs], + [new EvidencePolicyRule("source", "src/**", "targeted"), new EvidencePolicyRule("documentation", "docs/**", "docs")]); + + var runIdentity = new EvidencePullRequestRunIdentity(321, 321, 777, "main", 654321, 1); + var expectedIdentity = new EvidencePullRequestGateExpectedIdentity( + "forge-trust/AppSurface", + "pull_request_target", + "evidence-gate.yml", + "evidence-subject", + runIdentity); + var snapshot = await EvidenceGitChangeCapture.CaptureAsync(repositoryPath, baseRevision, headRevision); + var planner = new EvidencePlanner(); + var plan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(planner, policy, snapshot, runIdentity); + + var artifactRoot = Path.Join(repositoryPath, "handoff"); + var producerArtifactRoot = Path.Join(artifactRoot, "build"); + Directory.CreateDirectory(producerArtifactRoot); + IReadOnlyList artifacts = []; + var artifactPath = Path.Join(producerArtifactRoot, "reports", "build.txt"); + if (includeArtifact) + { + var writer = new EvidenceArtifactWriter(targetProducer, producerArtifactRoot); + artifacts = [await writer.WriteAsync("report", "reports/build.txt", "trusted artifact bytes"u8.ToArray())]; + } + + var producerResult = new EvidenceProducerResult( + "build", + EvidenceProducerOutcome.Passed, + includeRequiredAssertion ? ["build/passed"] : [], + Artifacts: artifacts); + var manifest = EvidenceManifestBuilder.Build( + plan, + documentationOnly ? [] : [producerResult], + envelopeStatus: documentationOnly ? EvidenceEnvelopeStatus.NotRequired : EvidenceEnvelopeStatus.ValidatedNotAttested); + if (documentationOnly) + { + manifest = EvidenceManifestBuilder.Build(plan, []); + } + + var authority = new EvidencePullRequestGateAuthoritySnapshot( + expectedIdentity.Repository, + expectedIdentity.EventName, + baseRevision, + headRevision, + expectedIdentity.WorkflowId, + runIdentity, + expectedIdentity.SubjectJobId, + headRevision, + "success", + SubjectEnvelopeAttested: !documentationOnly); + return new GateFixture( + repositoryPath, + artifactRoot, + artifactPath, + policy, + runIdentity, + expectedIdentity, + plan, + manifest, + authority); + } + + public Task VerifyAsync( + EvidencePlan? plan = null, + EvidenceManifest? manifest = null, + EvidencePolicy? policy = null, + EvidencePullRequestGateExpectedIdentity? expectedIdentity = null, + EvidencePullRequestGateAuthoritySnapshot? authority = null, + IEvidencePullRequestGateAuthorityProvider? authorityProvider = null, + IEvidencePullRequestGateArtifactVerifier? artifactVerifier = null, + string? trustedArtifactHandoffRootPath = null, + bool omitArtifactRoot = false, + bool useFakeArtifactVerifier = true) + { + var planner = new EvidencePlanner(); + return EvidencePullRequestGateVerifier.VerifyAsync( + planner, + policy ?? Policy, + _repositoryPath, + expectedIdentity ?? ExpectedIdentity, + authorityProvider ?? new FakeAuthorityProvider(authority ?? Authority), + omitArtifactRoot ? null : trustedArtifactHandoffRootPath ?? ArtifactRoot, + artifactVerifier ?? (useFakeArtifactVerifier ? new FakeArtifactVerifier(true) : null), + plan ?? Plan, + manifest ?? Manifest); + } + + public ValueTask DisposeAsync() + { + Directory.Delete(_repositoryPath, recursive: true); + return ValueTask.CompletedTask; + } + + private static void WriteFile(string root, string relativePath, string contents) + { + var path = TestPathUtils.PathUnder(root, relativePath.Replace('/', Path.DirectorySeparatorChar)); + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + File.WriteAllText(path, contents); + } + + private static void Commit(string repository, string message) => RunGit( + repository, + "-c", "user.name=AppSurface Test", + "-c", "user.email=appsurface@example.invalid", + "commit", "-qm", message); + + private static string RunGit(string repository, params string[] arguments) + { + var start = new ProcessStartInfo("git") + { + WorkingDirectory = repository, + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var output = process.StandardOutput.ReadToEnd(); + var error = process.StandardError.ReadToEnd(); + process.WaitForExit(); + Assert.True(process.ExitCode == 0, $"Git fixture command failed: {error}"); + return output; + } + } +} diff --git a/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs b/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs index 6f82428da..c0c0be2a8 100644 --- a/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs +++ b/Cli/ForgeTrust.AppSurface.Cli/EvidenceCommands.cs @@ -188,12 +188,19 @@ public override async ValueTask ExecuteAsync(IConsole console) } } - var manifest = EvidenceManifestBuilder.Build(plan, results, ObservationOnly, resourceResults: resourceResults); + // The built-in CLI does not authenticate CI job provenance or isolate head-controlled execution. + // A revision-bound local run is useful evidence to inspect, but only the trusted host may promote it. + var manifest = EvidenceManifestBuilder.Build( + plan, + results, + ObservationOnly || string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal), + resourceResults: resourceResults); await Workflow.WriteManifestAsync(manifest, OutputDirectory, cancellationToken); await console.Output.WriteLineAsync(EvidenceCliWorkflow.FormatSummary(manifest)); await console.Output.WriteLineAsync($"Artifacts: {Path.Join(OutputDirectory, "evidence-plan.json")}, {Path.Join(OutputDirectory, "evidence-manifest.json")}, {Path.Join(OutputDirectory, "evidence-summary.json")}"); await WriteGitHubSummaryAsync(manifest, cancellationToken); - if (manifest.ClaimKind == EvidenceClaimKind.None) + if (manifest.ClaimKind == EvidenceClaimKind.None + || (GateMode && manifest.ClaimKind == EvidenceClaimKind.ObservationOnly)) { throw new CommandException("ASEVD211: Evidence is incomplete. Inspect evidence-summary.json and the producer output before allowing a gate to proceed."); } @@ -252,6 +259,14 @@ internal sealed partial class EvidenceVerifyCommand(EvidenceCliWorkflow workflow [CommandOption("plan", Description = "Generated evidence-plan.json path. Defaults next to the manifest.")] public string? PlanPath { get; set; } + /// Gets or sets the trusted base-owned policy required for v2 verification. + [CommandOption("policy", Description = "Trusted base-owned policy path required for revision-bound v2 verification.")] + public string? PolicyPath { get; set; } + + /// Gets or sets the trusted Git object store required for v2 verification. + [CommandOption("repository", Description = "Trusted Git object store containing both exact commits for v2 verification.")] + public string? RepositoryPath { get; set; } + /// public async ValueTask ExecuteAsync(IConsole console) { @@ -265,7 +280,7 @@ public async ValueTask ExecuteAsync(IConsole console) var planPath = string.IsNullOrWhiteSpace(PlanPath) ? Path.Join(Path.GetDirectoryName(Path.GetFullPath(ManifestPath))!, "evidence-plan.json") : PlanPath; - var (_, manifest) = await _workflow.VerifyAsync(planPath, ManifestPath, console.RegisterCancellationHandler()); + var (_, manifest) = await _workflow.VerifyAsync(planPath, ManifestPath, console.RegisterCancellationHandler(), PolicyPath, RepositoryPath); await console.Output.WriteLineAsync($"Evidence manifest verified: {manifest.ClaimKind} ({manifest.Eligibility})"); } catch (EvidenceCliException exception) @@ -303,5 +318,25 @@ internal abstract partial class EvidencePlanningCommandBase(EvidenceCliWorkflow /// /// Creates the explicit policy-and-diff input consumed by a planning operation. /// - protected EvidencePlanningRequest CreatePlanningRequest() => new(PolicyPath, Paths, DiffFile); + protected EvidencePlanningRequest CreatePlanningRequest() => new(PolicyPath, Paths, DiffFile, BaseRevision, HeadRevision, RepositoryPath, GateMode, PullRequestRunIdentityFile); + + /// Gets or sets the complete base commit ID for revision-bound planning. + [CommandOption("base-revision", Description = "Complete base Git commit ID. Requires --head-revision and --diff-file.")] + public string? BaseRevision { get; set; } + + /// Gets or sets the complete head commit ID for revision-bound planning. + [CommandOption("head-revision", Description = "Complete head Git commit ID. Requires --base-revision and --diff-file.")] + public string? HeadRevision { get; set; } + + /// Gets or sets the trusted Git object-store directory containing both exact commits. + [CommandOption("repository", Description = "Git object-store directory for revision capture. Defaults to the current directory.")] + public string? RepositoryPath { get; set; } + + /// Gets or sets whether path-only local planning must be rejected. + [CommandOption("gate-mode", Description = "Require revision-bound inputs; local path-only evidence is never gate eligible.")] + public bool GateMode { get; set; } + + /// Gets or sets the trusted controller's canonical PR/run identity JSON path. + [CommandOption("pr-run-identity", Description = "Canonical controller-captured PR/run identity JSON for a revision-bound CI plan.")] + public string? PullRequestRunIdentityFile { get; set; } } diff --git a/Cli/ForgeTrust.AppSurface.Cli/README.md b/Cli/ForgeTrust.AppSurface.Cli/README.md index 91ae5720b..65b705f14 100644 --- a/Cli/ForgeTrust.AppSurface.Cli/README.md +++ b/Cli/ForgeTrust.AppSurface.Cli/README.md @@ -561,6 +561,8 @@ appsurface evidence verify ./TestResults/evidence/evidence-manifest.json `init --sample` is safe to run in an existing repository: it creates a marked policy, host skeleton, and README and refuses to overwrite unmarked files. `doctor` does not start tests or resources; it reports whether the selected policy needs Docker, a browser runtime, or a protected release envelope. `explain` writes `evidence-plan.json` and a concise human summary before any producer runs. `run` writes the plan, `evidence-manifest.json`, and `evidence-summary.json`; it also appends a short claim summary to `$GITHUB_STEP_SUMMARY` when that CI-provided path exists. `verify` validates plan/manifest digest binding without rerunning producers. +For revision-bound PR planning, pass the complete `--base-revision`, complete `--head-revision`, and byte-exact `--diff-file` together. `--repository` identifies the Git object store (default: current directory for planning), and `--gate-mode` rejects path-only input. A trusted controller may also pass `--pr-run-identity` pointing at canonical JSON with numeric `repositoryId`, `headRepositoryId`, `pullRequestNumber`, `workflowRunId`, `workflowRunAttempt`, and a bounded `targetBranch`; partial or local-only input cannot use it. The [cookbook](../../guides/evidencehost-cookbook.md#revision-bound-pr-rehearsal) supplies the exact diff command and a complete `explain`/`run`/`verify` rehearsal. Version-2 plans bind the source diff and NUL status digests separately from the normalized path digest. `verify` requires `--policy` from a separately trusted base checkout and `--repository` for v2, then regenerates the plan from those inputs. The CLI still cannot authenticate GitHub PR freshness or job provenance: its v2 `run` is `ObservationOnly`, and `--gate-mode` exits nonzero for it. Version-1 path and diff commands remain local compatibility paths and cannot authorize the new required check. + The built-in producer reuses the private [`ForgeTrust.AppSurface.Evidence.Coverage`](../../Evidence/ForgeTrust.AppSurface.Evidence.Coverage/README.md) engine used by `coverage run` and `coverage gate`; it writes the normal gate and patch-target artifacts beside its coverage output. When a policy requires patch thresholds, `evidence run` measures the same bounded `--diff-file` snapshot used to plan the selected profile, rather than reopening that path after execution starts. Browser E2E and resource-backed evidence belong in the separate consumer-owned [`ForgeTrust.AppSurface.Evidence.Aspire`](../../Evidence/ForgeTrust.AppSurface.Evidence.Aspire/README.md) lifecycle. An explicit policy-selected empty profile may claim `NoEvidenceRequired`; unavailable capability, filtered required tests, a failed producer, a missing assertion, an unready declared resource, or a failed declared coverage threshold produces `ClaimKind.None` and command failure. `--observation-only` records a diagnostic claim that is deliberately ineligible for a PR or release gate. The v1 workflow has no outbound telemetry, no automatic assembly/test discovery, no Docker sandbox, no independent artifact attestation, and no semantic classifier that silently labels arbitrary getters or constructors low value. Keep generated-code exclusions and the coverage thresholds in the reviewed Evidence policy explicit. See the [EvidenceHost cookbook](../../guides/evidencehost-cookbook.md) for policy, E2E, release-envelope, and incomplete-profile patterns. diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs index d161e8e06..342b24e4c 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/EvidenceCliWorkflow.cs @@ -144,6 +144,42 @@ internal async Task ResolveAsync(EvidencePlanningReq ArgumentNullException.ThrowIfNull(request); cancellationToken.ThrowIfCancellationRequested(); var policy = await ReadPolicyAsync(request.PolicyPath, cancellationToken).ConfigureAwait(false); + var revisionRequested = request.BaseRevision is not null || request.HeadRevision is not null; + if (request.PullRequestRunIdentityFile is not null && !revisionRequested) + { + throw new EvidenceCliException("ASEVD233", "PR/run identity requires revision-bound planning.", "Supply complete --base-revision and --head-revision with the exact --diff-file."); + } + + if (revisionRequested) + { + if (request.BaseRevision is null || request.HeadRevision is null || request.DiffFile is null || request.Paths.Count != 0) + { + throw new EvidenceCliException("ASEVD230", "Revision-bound planning requires --base-revision, --head-revision and --diff-file, without --path.", "Supply complete Git commit IDs and a byte-exact diff captured from that pair."); + } + + var captured = await EvidenceGitChangeCapture.CaptureAsync( + request.RepositoryPath ?? Directory.GetCurrentDirectory(), + request.BaseRevision, + request.HeadRevision, + cancellationToken).ConfigureAwait(false); + var supplied = await ReadDiffSnapshotAsync(request.DiffFile, cancellationToken).ConfigureAwait(false); + if (!captured.SourceDiff.Span.SequenceEqual(supplied.Bytes.Span)) + { + throw new EvidenceCliException("ASEVD231", "The supplied diff bytes do not match the exact Git commit pair.", "Regenerate --diff-file from the complete --base-revision and --head-revision using the documented fixed Git options."); + } + + var runIdentity = request.PullRequestRunIdentityFile is null + ? null + : await ReadCanonicalAsync(request.PullRequestRunIdentityFile, cancellationToken).ConfigureAwait(false); + var plan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(_planner, policy, captured, runIdentity); + return new EvidencePlanningResolution(plan, supplied); + } + + if (request.GateMode) + { + throw new EvidenceCliException("ASEVD230", "Gate mode requires revision-bound planning.", "Supply --base-revision, --head-revision and --diff-file; path-only local plans cannot authorize a gate."); + } + var inputs = await ReadPathsAndSnapshotAsync(request, cancellationToken).ConfigureAwait(false); return new EvidencePlanningResolution(_planner.Resolve(policy, inputs.Paths), inputs.Snapshot); } @@ -190,7 +226,9 @@ await File.WriteAllTextAsync( public async Task<(EvidencePlan Plan, EvidenceManifest Manifest)> VerifyAsync( string planPath, string manifestPath, - CancellationToken cancellationToken) + CancellationToken cancellationToken, + string? trustedPolicyPath = null, + string? repositoryPath = null) { var plan = await ReadCanonicalAsync(planPath, cancellationToken).ConfigureAwait(false); var manifest = await ReadCanonicalAsync(manifestPath, cancellationToken).ConfigureAwait(false); @@ -205,7 +243,22 @@ await File.WriteAllTextAsync( EvidencePlan resolvedPlan; try { - resolvedPlan = _planner.Resolve(plan.PolicySnapshot, plan.ChangedPaths); + if (string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal)) + { + if (trustedPolicyPath is null || repositoryPath is null) + { + throw new EvidenceCliException("ASEVD232", "Revision-bound verification requires a trusted policy and Git object store.", "Pass --policy from the trusted base and --repository containing both exact commits."); + } + + var trustedPolicy = await ReadPolicyAsync(trustedPolicyPath, cancellationToken).ConfigureAwait(false); + await EvidenceRevisionPlanBuilder.VerifyAsync( + _planner, trustedPolicy, repositoryPath, plan, cancellationToken).ConfigureAwait(false); + resolvedPlan = plan; + } + else + { + resolvedPlan = _planner.Resolve(plan.PolicySnapshot, plan.ChangedPaths); + } } catch (EvidencePlanningException exception) { @@ -236,13 +289,31 @@ public static string FormatSummary(EvidencePlan plan) return string.Join( Environment.NewLine, $"Evidence plan: {plan.Profile.Id} ({plan.Profile.Scope.ToString().ToLowerInvariant()})", + $"Plan digest: {plan.PlanDigest}", + string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal) + ? $"Revisions: {plan.BaseRevision![..12]}..{plan.HeadRevision![..12]} (source diff {plan.SourceDiffDigest})" + : "Revisions: local v1 input (not a CI gate authorization)", $"Why: {string.Join(", ", plan.MatchedRuleIds)}", - $"Changed paths: {string.Join(", ", plan.ChangedPaths.Select(static path => path.Path))}", + $"Changed paths ({plan.ChangedPaths.Count}): {FormatChangedPaths(plan.ChangedPaths)}", $"Obligations: {obligations}", $"Required producers: {FormatIds(plan.Profile.Producers.Select(static producer => producer.Id))}", $"Required resources: {FormatIds(plan.Profile.Resources.Select(static resource => resource.Id))}"); } + private static string FormatChangedPaths(IReadOnlyList paths) + { + const int maximumDisplayedPaths = 12; + const int maximumPathCharacters = 100; + var displayed = paths.Take(maximumDisplayedPaths) + .Select(path => path.Path.Length <= maximumPathCharacters + ? path.Path + : string.Concat(path.Path.AsSpan(0, maximumPathCharacters), "…")); + var result = string.Join(", ", displayed); + return paths.Count > maximumDisplayedPaths + ? $"{result}, … (+{paths.Count - maximumDisplayedPaths} more)" + : result; + } + /// /// Formats a deterministic, human-readable summary of an evidence claim and any remaining obligations. /// @@ -387,19 +458,45 @@ private static async Task WriteCanonicalAsync(string path, TValue value, private static async Task ReadCanonicalAsync(string path, CancellationToken cancellationToken) { - if (!File.Exists(path)) - { - throw new EvidenceCliException("ASEVD208", $"Evidence file '{path}' does not exist.", "Pass paths from the same generated evidence output directory."); - } - try { - return EvidenceCanonicalJson.Deserialize(await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false)); + const int maximumEvidenceBytes = 4 * 1024 * 1024; + await using var source = File.OpenRead(path); + await using var captured = new MemoryStream(); + var buffer = new byte[80 * 1024]; + while (true) + { + var count = await source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + if (count == 0) + { + break; + } + + if (captured.Length + count > maximumEvidenceBytes) + { + throw new EvidenceCliException("ASEVD209", "Evidence JSON exceeds the 4 MiB verification limit.", "Keep plans and manifests bounded; do not embed raw test output."); + } + + await captured.WriteAsync(buffer.AsMemory(0, count), cancellationToken).ConfigureAwait(false); + } + + var bytes = captured.ToArray(); + var value = EvidenceCanonicalJson.Deserialize(bytes); + if (!EvidenceCanonicalJson.Serialize(value).AsSpan().SequenceEqual(bytes)) + { + throw new EvidenceCliException("ASEVD209", "Evidence JSON is not canonical.", "Use unedited evidence-plan.json and evidence-manifest.json generated by AppSurface."); + } + + return value; } catch (JsonException exception) { throw new EvidenceCliException("ASEVD209", $"Evidence file '{path}' is not valid JSON: {exception.Message}", "Regenerate evidence instead of editing the output."); } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) + { + throw new EvidenceCliException("ASEVD208", $"Evidence file '{path}' could not be read.", "Pass readable plan and manifest files from the same generated evidence output directory."); + } } private static bool ContainsGeneratedMarker(string path) => File.ReadAllText(path).Contains(GeneratedMarker, StringComparison.Ordinal); @@ -517,7 +614,15 @@ An incomplete profile is not complete evidence. Keep normal AppHost composition /// /// Describes a policy and explicit changed-path input for an EvidenceHost planning operation. /// -internal sealed record EvidencePlanningRequest(string PolicyPath, IReadOnlyList Paths, string? DiffFile); +internal sealed record EvidencePlanningRequest( + string PolicyPath, + IReadOnlyList Paths, + string? DiffFile, + string? BaseRevision = null, + string? HeadRevision = null, + string? RepositoryPath = null, + bool GateMode = false, + string? PullRequestRunIdentityFile = null); /// /// Binds a resolved plan to the immutable diff bytes used to derive its changed paths. diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md index 908b2f93f..8d49ea7e1 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md @@ -2,7 +2,7 @@ `ForgeTrust.AppSurface.Evidence.Cli` supplies the internal workflow used by the public `appsurface evidence` commands. Most adopters install the [AppSurface CLI](../../Cli/ForgeTrust.AppSurface.Cli/README.md), not this package directly. -Start with the [EvidenceHost guide](../../start-here/evidencehost.md). The workflow reads only explicit policy and diff inputs; it does not scan consumer assemblies, discover tests, provision third-party services, or report outbound usage telemetry. +Start with the [EvidenceHost guide](../../start-here/evidencehost.md). The workflow reads explicit policy and diff inputs; revision-bound mode also invokes fixed-options Git against the supplied object store. It does not scan consumer assemblies, discover tests, provision third-party services, or report outbound usage telemetry. ## Release Guidance @@ -28,7 +28,9 @@ appsurface evidence verify TestResults/evidence/evidence-manifest.json | `doctor` | Resolves policy and reports policy, diff, Docker, browser, and release-envelope prerequisites without starting anything. | | `explain` | Writes the resolved plan and a human-readable summary without running producers. | | `run` | Runs selected built-in coverage evidence, writes a canonical plan/manifest/summary, and writes a GitHub step summary when available. Consumer-owned browser/E2E or resource-backed producers run through the separate Aspire EvidenceHost package. | -| `verify` | Recomputes binding and digest verification without running any producer. | +| `verify` | Reads at most 4 MiB per canonical plan or manifest, then recomputes binding and digests without running a producer. v2 also requires a separately trusted `--policy` and `--repository` to regenerate the exact Git change. | + +Revision-bound `doctor`, `explain`, and `run` require `--base-revision`, `--head-revision`, and `--diff-file` together, with no `--path`. `--repository` points at the trusted object store and defaults to the current directory for these planning commands. `--gate-mode` rejects local path-only planning. A trusted controller may add `--pr-run-identity` with canonical PR/run identity JSON; it is not accepted for a local-only plan. A mismatch between the supplied source diff and the fixed-options Git diff fails with `ASEVD231`; partial input fails with `ASEVD230`; identity without revisions fails with `ASEVD233`. The [cookbook rehearsal](../../guides/evidencehost-cookbook.md#revision-bound-pr-rehearsal) shows a copyable command sequence. Built-in `run` treats v2 results as `ObservationOnly` because the local CLI cannot authenticate CI job provenance or subject isolation; gate mode exits nonzero on that observation. External gate authorization requires the [base-owned verifier](../../docs/designs/issue-777-policy-driven-ci-evidence-gate.md) to check current PR identity and execution provenance. ## Incomplete profiles are not complete evidence diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs index 7ccf71fea..3ff1d6daf 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceContracts.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -306,6 +307,24 @@ public sealed record EvidencePolicy( IReadOnlyList Profiles, IReadOnlyList Rules); +/// +/// Records bounded pull-request and workflow identity captured by the trusted controller. +/// These fields are provenance to compare with an authoritative CI provider, not proof by themselves. +/// +/// GitHub repository's stable numeric identifier. +/// Head repository's stable numeric identifier; differs for forks. +/// Pull-request number in the target repository. +/// Target branch name at capture time. +/// GitHub Actions workflow-run identifier. +/// Positive attempt number for that run. +public sealed record EvidencePullRequestRunIdentity( + long RepositoryId, + long HeadRepositoryId, + int PullRequestNumber, + string TargetBranch, + long WorkflowRunId, + int WorkflowRunAttempt); + /// /// Captures the immutable result of policy resolution before resource or producer execution. /// @@ -318,6 +337,11 @@ public sealed record EvidencePolicy( /// Rules that explain selection. /// SHA-256 digest of canonical plan bytes excluding this digest field. /// Canonical checked-in policy snapshot used for resolution and later verification. +/// Complete base commit ID for a v2 revision-bound plan; absent for legacy local plans. +/// Complete head commit ID for a v2 revision-bound plan; absent for legacy local plans. +/// SHA-256 of the exact fixed-options Git diff bytes for a v2 plan. +/// SHA-256 of the exact NUL-delimited Git name-status bytes for a v2 plan. +/// Controller-captured PR/run identity for a CI v2 plan; absent in local rehearsal. public sealed record EvidencePlan( string ContractVersion, string PolicyId, @@ -327,7 +351,12 @@ public sealed record EvidencePlan( IReadOnlyList ChangedPaths, IReadOnlyList MatchedRuleIds, string PlanDigest, - EvidencePolicy? PolicySnapshot = null); + EvidencePolicy? PolicySnapshot = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? BaseRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? HeadRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SourceDiffDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? NameStatusDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] EvidencePullRequestRunIdentity? PullRequestRunIdentity = null); /// /// Captures a bounded producer result returned to the EvidenceHost. @@ -381,6 +410,11 @@ public sealed record EvidenceExecutionMetrics( /// Bounded producer terminal results. /// Secret-free lifecycle timing and cleanup state. /// SHA-256 digest of canonical manifest bytes excluding this digest field. +/// Complete base commit ID copied from a v2 plan. +/// Complete head commit ID copied from a v2 plan. +/// SHA-256 of the exact Git diff bytes copied from a v2 plan. +/// SHA-256 of the exact Git name-status bytes copied from a v2 plan. +/// Controller-captured PR/run identity copied from a v2 plan. public sealed record EvidenceManifest( string ContractVersion, string PlanDigest, @@ -394,7 +428,12 @@ public sealed record EvidenceManifest( IReadOnlyList UnmediatedObligationIds, IReadOnlyList ProducerResults, EvidenceExecutionMetrics Metrics, - string ManifestDigest); + string ManifestDigest, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? BaseRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? HeadRevision = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? SourceDiffDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? NameStatusDigest = null, + [property: JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] EvidencePullRequestRunIdentity? PullRequestRunIdentity = null); /// /// Supplies the immutable execution context exposed to a registered evidence producer. @@ -436,6 +475,8 @@ public sealed class EvidenceArtifactWriter /// Maximum total artifact bytes accepted by one v1 producer declaration. public const long MaximumTotalArtifactBytes = 256L * 1024 * 1024; + private const int StreamBufferSize = 81_920; + private readonly EvidenceProducerDeclaration _producer; private readonly string _rootPath; private readonly object _sync = new(); @@ -518,6 +559,110 @@ public async ValueTask WriteAsync( } } + /// + /// Copies one declared artifact from a readable stream while hashing it, without buffering the complete artifact. + /// The source stream remains owned by the caller and must yield exactly bytes. + /// + /// Declared artifact slot identifier. + /// Normalized artifact-root-relative destination path. + /// Readable source stream. The writer does not dispose it. + /// Exact expected byte count, checked against both slot and v1 producer limits before reading. + /// Cancellation requested by the EvidenceHost lifecycle. + /// Hash and metadata for the copied artifact. + /// + /// This method writes to a path beneath the controlled artifact root and does not provide no-follow or + /// descriptor-relative extraction guarantees. Use it only for separately validated trusted streams; it is not + /// a safe copier for paths or streams supplied directly by an untrusted extraction boundary. + /// + public async ValueTask WriteAsync( + string logicalName, + string relativePath, + Stream contents, + long declaredLengthBytes, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(contents); + if (!contents.CanRead) + { + throw new ArgumentException("Evidence artifact source streams must be readable.", nameof(contents)); + } + + if (declaredLengthBytes < 0) + { + throw new ArgumentOutOfRangeException(nameof(declaredLengthBytes)); + } + + if (_producer.ArtifactSlots.FirstOrDefault(slot => string.Equals(slot.LogicalName, logicalName, StringComparison.Ordinal)) is not { } slot) + { + throw new InvalidOperationException($"Artifact '{logicalName}' is not declared by producer '{_producer.Id}'."); + } + + var normalizedPath = EvidenceArtifactValidation.NormalizeRelativePath(relativePath); + EvidenceArtifactValidation.ValidatePathForSlot(slot, normalizedPath); + ReserveArtifact(logicalName, normalizedPath, declaredLengthBytes, slot.MaximumBytes); + + string? temporaryPath = null; + try + { + cancellationToken.ThrowIfCancellationRequested(); + var destination = EvidenceArtifactValidation.GetContainedPath(_rootPath, normalizedPath); + Directory.CreateDirectory(Path.GetDirectoryName(destination)!); + temporaryPath = destination + "." + Guid.NewGuid().ToString("N") + ".tmp"; + + string digest; + long copiedLength; + await using (var destinationStream = new FileStream( + temporaryPath, + FileMode.CreateNew, + FileAccess.Write, + FileShare.None, + StreamBufferSize, + FileOptions.Asynchronous | FileOptions.SequentialScan)) + { + var result = await CopyAndHashAsync(contents, destinationStream, declaredLengthBytes, cancellationToken).ConfigureAwait(false); + copiedLength = result.Length; + digest = result.Sha256; + await destinationStream.FlushAsync(cancellationToken).ConfigureAwait(false); + } + + if (copiedLength != declaredLengthBytes) + { + throw new InvalidDataException($"Artifact '{logicalName}' stream length did not match its declared length."); + } + + cancellationToken.ThrowIfCancellationRequested(); + File.Move(temporaryPath, destination, overwrite: true); + var artifact = new EvidenceArtifactResult(logicalName, normalizedPath, slot.MediaType, copiedLength, digest); + lock (_sync) + { + _artifacts[logicalName] = artifact; + } + + return artifact; + } + catch + { + if (temporaryPath is not null) + { + try + { + File.Delete(temporaryPath); + } + catch (IOException) + { + // Preserve the original write, read, or cancellation failure. + } + catch (UnauthorizedAccessException) + { + // Preserve the original write, read, or cancellation failure. + } + } + + ReleaseArtifact(logicalName, normalizedPath, declaredLengthBytes); + throw; + } + } + /// /// Revalidates the final on-disk bytes for every artifact written through this writer. /// @@ -525,19 +670,42 @@ public async ValueTask WriteAsync( /// when every artifact still has its declared length and digest. public async Task VerifyWrittenArtifactsAsync(CancellationToken cancellationToken = default) { + long totalBytes = 0; foreach (var artifact in WrittenArtifacts) { string path; try { + var slot = _producer.ArtifactSlots.FirstOrDefault(candidate => + string.Equals(candidate.LogicalName, artifact.LogicalName, StringComparison.Ordinal)); + if (slot is null + || artifact.LengthBytes < 0 + || artifact.LengthBytes > slot.MaximumBytes + || artifact.LengthBytes > MaximumTotalArtifactBytes - totalBytes) + { + return false; + } + + totalBytes += artifact.LengthBytes; path = EvidenceArtifactValidation.GetContainedPath(_rootPath, artifact.RelativePath); - var bytes = await File.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false); - if (bytes.LongLength != artifact.LengthBytes - || !string.Equals(EvidenceDigest.Sha256(bytes), artifact.Sha256, StringComparison.Ordinal)) + await using var stream = new FileStream( + path, + FileMode.Open, + FileAccess.Read, + FileShare.Read, + StreamBufferSize, + FileOptions.Asynchronous | FileOptions.SequentialScan); + var result = await CopyAndHashAsync(stream, null, artifact.LengthBytes, cancellationToken).ConfigureAwait(false); + if (result.Length != artifact.LengthBytes + || !string.Equals(result.Sha256, artifact.Sha256, StringComparison.Ordinal)) { return false; } } + catch (InvalidDataException) + { + return false; + } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException) { return false; @@ -547,7 +715,7 @@ public async Task VerifyWrittenArtifactsAsync(CancellationToken cancellati return true; } - private void ReserveArtifact(string logicalName, string normalizedPath, int lengthBytes, long maximumBytes) + private void ReserveArtifact(string logicalName, string normalizedPath, long lengthBytes, long maximumBytes) { lock (_sync) { @@ -574,7 +742,7 @@ private void ReserveArtifact(string logicalName, string normalizedPath, int leng } } - private void ReleaseArtifact(string logicalName, string normalizedPath, int lengthBytes) + private void ReleaseArtifact(string logicalName, string normalizedPath, long lengthBytes) { lock (_sync) { @@ -583,6 +751,52 @@ private void ReleaseArtifact(string logicalName, string normalizedPath, int leng _totalBytes -= lengthBytes; } } + + private static async Task<(long Length, string Sha256)> CopyAndHashAsync( + Stream source, + Stream? destination, + long maximumBytes, + CancellationToken cancellationToken) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = ArrayPool.Shared.Rent(StreamBufferSize); + long length = 0; + try + { + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + var remaining = maximumBytes - length; + var readSize = remaining > 0 + ? (int)Math.Min(StreamBufferSize, Math.Min(buffer.Length, remaining)) + : 1; + var bytesRead = await source.ReadAsync(buffer.AsMemory(0, readSize), cancellationToken).ConfigureAwait(false); + if (bytesRead == 0) + { + break; + } + + if (remaining == 0) + { + throw new InvalidDataException("Evidence artifact stream exceeds its declared or allowed length."); + } + + hash.AppendData(buffer, 0, bytesRead); + if (destination is not null) + { + await destination.WriteAsync(buffer.AsMemory(0, bytesRead), cancellationToken).ConfigureAwait(false); + } + + length += bytesRead; + } + + return (length, Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant()); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } } /// @@ -920,7 +1134,12 @@ public static EvidenceManifest Build( UnmediatedObligationIds: unmediated.OrderBy(static id => id, StringComparer.Ordinal).ToArray(), ProducerResults: producerResults.OrderBy(static result => result.ProducerId, StringComparer.Ordinal).ToArray(), Metrics: metrics, - ManifestDigest: string.Empty); + ManifestDigest: string.Empty, + BaseRevision: plan.BaseRevision, + HeadRevision: plan.HeadRevision, + SourceDiffDigest: plan.SourceDiffDigest, + NameStatusDigest: plan.NameStatusDigest, + PullRequestRunIdentity: plan.PullRequestRunIdentity); return draft with { ManifestDigest = EvidenceDigest.CanonicalSha256(draft) }; } @@ -939,7 +1158,14 @@ public static bool Verify(EvidencePlan plan, EvidenceManifest manifest) ArgumentNullException.ThrowIfNull(manifest); var planWithoutDigest = plan with { PlanDigest = string.Empty }; - if (plan.PolicySnapshot is null + if (!HasValidRevisionBinding(plan) + || !string.Equals(plan.ContractVersion, manifest.ContractVersion, StringComparison.Ordinal) + || !string.Equals(plan.BaseRevision, manifest.BaseRevision, StringComparison.Ordinal) + || !string.Equals(plan.HeadRevision, manifest.HeadRevision, StringComparison.Ordinal) + || !string.Equals(plan.SourceDiffDigest, manifest.SourceDiffDigest, StringComparison.Ordinal) + || !string.Equals(plan.NameStatusDigest, manifest.NameStatusDigest, StringComparison.Ordinal) + || !Equals(plan.PullRequestRunIdentity, manifest.PullRequestRunIdentity) + || plan.PolicySnapshot is null || !string.Equals(plan.PolicyDigest, EvidenceDigest.CanonicalSha256(plan.PolicySnapshot), StringComparison.Ordinal) || !string.Equals(plan.DiffDigest, EvidenceDigest.CanonicalSha256(plan.ChangedPaths), StringComparison.Ordinal) || !string.Equals(plan.PlanDigest, EvidenceDigest.CanonicalSha256(planWithoutDigest), StringComparison.Ordinal) @@ -963,6 +1189,40 @@ public static bool Verify(EvidencePlan plan, EvidenceManifest manifest) manifest.Metrics); return string.Equals(manifest.ManifestDigest, expected.ManifestDigest, StringComparison.Ordinal); } + + private static bool HasValidRevisionBinding(EvidencePlan plan) + { + if (string.Equals(plan.ContractVersion, "1.0", StringComparison.Ordinal)) + { + return plan.BaseRevision is null + && plan.HeadRevision is null + && plan.SourceDiffDigest is null + && plan.NameStatusDigest is null + && plan.PullRequestRunIdentity is null; + } + + return string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal) + && IsLowerHex(plan.BaseRevision, 40, 64) + && plan.HeadRevision?.Length == plan.BaseRevision?.Length + && IsLowerHex(plan.HeadRevision, 40, 64) + && IsLowerHex(plan.SourceDiffDigest, 64) + && IsLowerHex(plan.NameStatusDigest, 64) + && (plan.PullRequestRunIdentity is null + || plan.PullRequestRunIdentity is + { + RepositoryId: > 0, + HeadRepositoryId: > 0, + PullRequestNumber: > 0, + TargetBranch.Length: > 0 and <= 128, + WorkflowRunId: > 0, + WorkflowRunAttempt: > 0, + }); + } + + private static bool IsLowerHex(string? value, params int[] allowedLengths) + => value is not null + && allowedLengths.Contains(value.Length) + && value.All(static character => character is >= '0' and <= '9' or >= 'a' and <= 'f'); } /// diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceNoFollowArtifactExtractor.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceNoFollowArtifactExtractor.cs new file mode 100644 index 000000000..548b5d8ad --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/EvidenceNoFollowArtifactExtractor.cs @@ -0,0 +1,724 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using System.Text; +using Microsoft.Win32.SafeHandles; + +namespace ForgeTrust.AppSurface.Evidence.Contracts; + +/// +/// Identifies one untrusted scratch file and its declared evidence artifact destination. +/// +/// Declared logical artifact slot name. +/// Canonical slash-separated path relative to the trusted scratch directory. +/// Canonical slash-separated path beneath the evidence writer root and declared slot. +public sealed record EvidenceNoFollowArtifact( + string LogicalName, + string SourceRelativePath, + string DestinationRelativePath); + +/// +/// Lowers the extractor's built-in file, byte, and elapsed-time ceilings for one extraction call. +/// +/// +/// Limits may be reduced by the caller but cannot exceed 64 files, the evidence writer's 256 MiB +/// per-producer total, or two minutes. Each individual artifact is also bounded by its declared slot. +/// +public sealed record EvidenceNoFollowArtifactExtractionLimits +{ + /// The absolute maximum number of source files in one extraction call. + public const int MaximumAllowedFileCount = 64; + + /// The absolute maximum aggregate source size in one extraction call. + public const long MaximumAllowedTotalBytes = EvidenceArtifactWriter.MaximumTotalArtifactBytes; + + /// The absolute maximum wall-clock duration of one extraction call. + public static readonly TimeSpan MaximumAllowedDuration = TimeSpan.FromMinutes(2); + + /// Gets the maximum number of files accepted by one extraction call. + public int MaximumFileCount { get; init; } = MaximumAllowedFileCount; + + /// Gets the maximum aggregate source size accepted by one extraction call. + public long MaximumTotalBytes { get; init; } = MaximumAllowedTotalBytes; + + /// Gets the maximum wall-clock duration of one extraction call. + public TimeSpan MaximumDuration { get; init; } = MaximumAllowedDuration; +} + +/// +/// Copies explicitly selected scratch files into declared evidence artifact slots using Linux no-follow opens. +/// +/// +/// The caller must provide an already-open handle to the trusted scratch directory. The extractor requires Linux +/// x64 or arm64 with the openat2 syscall and statx; it fails closed when either facility or a required +/// resolution flag is unavailable. It never falls back to caller-path-based source reads. +/// +public static class EvidenceNoFollowArtifactExtractor +{ + private const int StreamBufferSize = 81_920; + private const int MaximumRelativePathBytes = 4_096; + private const int MaximumSegmentBytes = 255; + + private const long OpenAt2SyscallNumber = 437; + + private const ulong OpenReadOnly = 0; + private const ulong OpenCloseOnExec = 0x0008_0000; + private const ulong OpenNoFollow = 0x0002_0000; + private const ulong OpenNonBlocking = 0x0000_0800; + private const ulong OpenNoControllingTerminal = 0x0000_0100; + private const ulong ResolveNoMagicLinks = 0x02; + private const ulong ResolveNoSymlinks = 0x04; + private const ulong ResolveBeneath = 0x08; + + private const int AtEmptyPath = 0x1000; + private const uint StatxBasicStats = 0x07ff; + private const uint StatxType = 1 << 0; + private const uint StatxMode = 1 << 1; + private const uint StatxLinkCount = 1 << 2; + private const uint StatxModifyTime = 1 << 6; + private const uint StatxChangeTime = 1 << 7; + private const uint StatxInode = 1 << 8; + private const uint StatxSize = 1 << 9; + private const uint StatxRequiredMask = StatxType | StatxMode | StatxLinkCount | StatxModifyTime | StatxChangeTime | StatxInode | StatxSize; + private const ushort FileTypeMask = 0xf000; + private const ushort RegularFileType = 0x8000; + private const ushort DirectoryFileType = 0x4000; + + private const int ErrorInvalidArgument = 22; + private const int ErrorNoSys = 38; + private const int ErrorTooLarge = 7; + + private static readonly UTF8Encoding StrictUtf8 = new(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true); + + /// + /// Opens each listed source beneath without following symlinks and streams + /// its bytes through . + /// + /// Already-open handle to the trusted scratch directory. The extractor borrows it for this call. + /// Writer that owns the declared destination slots and artifact root. + /// Explicit source-to-destination mappings. Directories are never enumerated. + /// Optional stricter file-count, aggregate-byte, and duration limits. + /// Caller cancellation token. + /// The metadata for artifacts completed by this call, in input order. + /// The operating system, architecture, kernel, or libc lacks required enforcement. + /// A source or destination path is not canonical and root-relative, or the input contains duplicates. + /// A source is not a single-link regular file, changes while being copied, or exceeds the selected limits. + /// A source cannot be opened or inspected through the required Linux descriptor APIs. + /// The extraction exceeds its configured duration. + /// + /// Source paths must use forward slashes and contain no empty, dot, or parent segments. The extractor checks each + /// opened file's type, link count, identity, size, modification time, and change time. It also hashes a second + /// read through the same open descriptor and compares it with the bytes streamed to the writer before promotion. + /// A later failure does not roll back artifacts already completed earlier in the same call because the writer + /// exposes no batch transaction. + /// + public static async Task> ExtractAsync( + SafeFileHandle trustedScratchRoot, + EvidenceArtifactWriter writer, + IReadOnlyList artifacts, + EvidenceNoFollowArtifactExtractionLimits? limits = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(trustedScratchRoot); + ArgumentNullException.ThrowIfNull(writer); + ArgumentNullException.ThrowIfNull(artifacts); + + var effectiveLimits = limits ?? new EvidenceNoFollowArtifactExtractionLimits(); + ValidateLimits(effectiveLimits); + + var requestedArtifacts = artifacts.ToArray(); + if (requestedArtifacts.Length > effectiveLimits.MaximumFileCount) + { + throw new InvalidDataException("The artifact list exceeds the configured file-count limit."); + } + + var requests = ValidateRequests(requestedArtifacts); + EnsureLinuxEnforcementAvailable(); + cancellationToken.ThrowIfCancellationRequested(); + + var startedTimestamp = Stopwatch.GetTimestamp(); + using var operationCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + operationCancellation.CancelAfter(effectiveLimits.MaximumDuration); + var operationToken = operationCancellation.Token; + + var rootHandleAdded = false; + var openedFiles = new List(requests.Count); + try + { + trustedScratchRoot.DangerousAddRef(ref rootHandleAdded); + if (!rootHandleAdded || trustedScratchRoot.IsInvalid || trustedScratchRoot.IsClosed) + { + throw new ArgumentException("The trusted scratch root must be an open directory handle.", nameof(trustedScratchRoot)); + } + + var rootSnapshot = ReadSnapshot(trustedScratchRoot); + if ((rootSnapshot.Mode & FileTypeMask) != DirectoryFileType) + { + throw new ArgumentException("The trusted scratch root handle must refer to a directory.", nameof(trustedScratchRoot)); + } + + var rootDescriptor = trustedScratchRoot.DangerousGetHandle().ToInt32(); + var identities = new HashSet(); + long totalBytes = 0; + foreach (var request in requests) + { + operationToken.ThrowIfCancellationRequested(); + var fileHandle = OpenRelativeRegularCandidate(rootDescriptor, request.SourceRelativePath); + try + { + var snapshot = ReadSnapshot(fileHandle); + if ((snapshot.Mode & FileTypeMask) != RegularFileType) + { + throw new InvalidDataException($"Source '{request.SourceRelativePath}' is not a regular file."); + } + + if (snapshot.LinkCount != 1) + { + throw new InvalidDataException($"Source '{request.SourceRelativePath}' has more than one hard link."); + } + + if (!identities.Add(snapshot.Identity)) + { + throw new InvalidDataException("The artifact list refers to the same underlying file more than once."); + } + + if (snapshot.Size > (ulong)effectiveLimits.MaximumTotalBytes + || snapshot.Size > long.MaxValue + || (ulong)totalBytes > (ulong)effectiveLimits.MaximumTotalBytes - snapshot.Size) + { + throw new InvalidDataException("The artifact sources exceed the configured aggregate byte limit."); + } + + totalBytes += (long)snapshot.Size; + openedFiles.Add(new OpenedArtifact(request, fileHandle, snapshot)); + fileHandle = null!; + } + finally + { + fileHandle?.Dispose(); + } + } + + var results = new List(openedFiles.Count); + foreach (var openedFile in openedFiles) + { + operationToken.ThrowIfCancellationRequested(); + EnsureWithinDuration(startedTimestamp, effectiveLimits.MaximumDuration); + + await using var source = new FileStream( + openedFile.Handle, + FileAccess.Read, + StreamBufferSize, + isAsync: false); + using var verifiedSource = new VerifiedSourceStream( + source, + openedFile.Handle, + openedFile.Snapshot, + checked((long)openedFile.Snapshot.Size), + startedTimestamp, + effectiveLimits.MaximumDuration); + + var result = await writer.WriteAsync( + openedFile.Request.LogicalName, + openedFile.Request.DestinationRelativePath, + verifiedSource, + checked((long)openedFile.Snapshot.Size), + operationToken).ConfigureAwait(false); + results.Add(result); + } + + return results; + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new TimeoutException("The Linux no-follow artifact extraction exceeded its configured duration."); + } + finally + { + foreach (var openedFile in openedFiles) + { + openedFile.Handle.Dispose(); + } + + if (rootHandleAdded) + { + trustedScratchRoot.DangerousRelease(); + } + } + } + + private static IReadOnlyList ValidateRequests(IReadOnlyList artifacts) + { + var logicalNames = new HashSet(StringComparer.Ordinal); + var sourcePaths = new HashSet(StringComparer.Ordinal); + var destinationPaths = new HashSet(StringComparer.Ordinal); + var requests = new List(artifacts.Count); + + foreach (var artifact in artifacts) + { + ArgumentNullException.ThrowIfNull(artifact); + if (string.IsNullOrWhiteSpace(artifact.LogicalName)) + { + throw new ArgumentException("Artifact logical names cannot be empty.", nameof(artifacts)); + } + + var sourcePath = ValidateRelativePath(artifact.SourceRelativePath, nameof(artifacts)); + var destinationPath = ValidateRelativePath(artifact.DestinationRelativePath, nameof(artifacts)); + if (!logicalNames.Add(artifact.LogicalName) + || !sourcePaths.Add(sourcePath) + || !destinationPaths.Add(destinationPath)) + { + throw new ArgumentException("Artifact logical names, source paths, and destination paths must be unique.", nameof(artifacts)); + } + + requests.Add(new ValidatedRequest(artifact.LogicalName, sourcePath, destinationPath)); + } + + return requests; + } + + private static string ValidateRelativePath(string? path, string parameterName) + { + if (string.IsNullOrWhiteSpace(path) + || path[0] == '/' + || path.Contains('\\') + || path.Contains('\0')) + { + throw new ArgumentException("Artifact paths must be canonical, slash-separated relative paths.", parameterName); + } + + byte[] encoded; + try + { + encoded = StrictUtf8.GetBytes(path); + } + catch (EncoderFallbackException exception) + { + throw new ArgumentException("Artifact paths must contain valid UTF-8 characters.", parameterName, exception); + } + + if (encoded.Length > MaximumRelativePathBytes) + { + throw new ArgumentException("Artifact paths exceed the Linux relative-path byte limit.", parameterName); + } + + foreach (var segment in path.Split('/')) + { + if (segment.Length == 0 || segment is "." or "..") + { + throw new ArgumentException("Artifact paths cannot contain empty, dot, or parent segments.", parameterName); + } + + int segmentLength; + try + { + segmentLength = StrictUtf8.GetByteCount(segment); + } + catch (EncoderFallbackException exception) + { + throw new ArgumentException("Artifact paths must contain valid UTF-8 characters.", parameterName, exception); + } + + if (segmentLength > MaximumSegmentBytes || segment.Any(char.IsControl)) + { + throw new ArgumentException("Artifact path segments exceed Linux filename limits or contain control characters.", parameterName); + } + } + + return path; + } + + private static void ValidateLimits(EvidenceNoFollowArtifactExtractionLimits limits) + { + if (limits.MaximumFileCount is < 1 or > EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount) + { + throw new ArgumentOutOfRangeException(nameof(limits), "The file-count limit must be between 1 and 64."); + } + + if (limits.MaximumTotalBytes is < 1 or > EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedTotalBytes) + { + throw new ArgumentOutOfRangeException(nameof(limits), "The aggregate byte limit must be between 1 byte and 256 MiB."); + } + + if (limits.MaximumDuration <= TimeSpan.Zero + || limits.MaximumDuration > EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedDuration) + { + throw new ArgumentOutOfRangeException(nameof(limits), "The duration limit must be positive and no greater than two minutes."); + } + } + + private static void EnsureLinuxEnforcementAvailable() + { + if (!OperatingSystem.IsLinux()) + { + throw new PlatformNotSupportedException("No-follow artifact extraction requires Linux openat2 and statx."); + } + + if (RuntimeInformation.ProcessArchitecture is not (Architecture.X64 or Architecture.Arm64)) + { + throw new PlatformNotSupportedException("No-follow artifact extraction currently supports Linux x64 and arm64 only."); + } + } + + private static SafeFileHandle OpenRelativeRegularCandidate(int rootDescriptor, string relativePath) + { + var how = new LinuxOpenHow + { + Flags = OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenNonBlocking | OpenNoControllingTerminal, + Resolve = ResolveBeneath | ResolveNoSymlinks | ResolveNoMagicLinks, + }; + + var descriptor = InvokeOpenAt2(rootDescriptor, relativePath, ref how); + return new SafeFileHandle(new IntPtr(descriptor), ownsHandle: true); + } + + private static int InvokeOpenAt2(int rootDescriptor, string relativePath, ref LinuxOpenHow how) + { + var pathPointer = Marshal.StringToCoTaskMemUTF8(relativePath); + try + { + var result = Syscall(OpenAt2SyscallNumber, rootDescriptor, pathPointer, ref how, (nuint)Marshal.SizeOf()); + if (result >= 0 && result <= int.MaxValue) + { + return (int)result; + } + + var error = Marshal.GetLastPInvokeError(); + if (error is ErrorNoSys or ErrorInvalidArgument or ErrorTooLarge) + { + throw new PlatformNotSupportedException( + "This Linux kernel does not enforce the required openat2 resolution flags; extraction was refused."); + } + + throw new IOException($"Linux openat2 refused the scratch artifact path (errno {error})."); + } + finally + { + Marshal.FreeCoTaskMem(pathPointer); + } + } + + private static FileSnapshot ReadSnapshot(SafeFileHandle handle) + { + LinuxStatx statx; + try + { + if (Statx( + handle.DangerousGetHandle().ToInt32(), + string.Empty, + AtEmptyPath, + StatxBasicStats, + out statx) != 0) + { + var error = Marshal.GetLastPInvokeError(); + if (error == ErrorNoSys) + { + throw new PlatformNotSupportedException("This Linux libc or kernel does not provide statx; extraction was refused."); + } + + throw new IOException($"Linux statx could not inspect the opened scratch entry (errno {error})."); + } + } + catch (EntryPointNotFoundException exception) + { + throw new PlatformNotSupportedException("This Linux libc does not export statx; extraction was refused.", exception); + } + + if ((statx.Mask & StatxRequiredMask) != StatxRequiredMask) + { + throw new PlatformNotSupportedException("Linux statx did not return the metadata required for safe extraction."); + } + + return new FileSnapshot( + statx.DeviceMajor, + statx.DeviceMinor, + statx.Inode, + statx.Mode, + statx.LinkCount, + statx.Size, + statx.ModifyTime.Seconds, + statx.ModifyTime.Nanoseconds, + statx.ChangeTime.Seconds, + statx.ChangeTime.Nanoseconds); + } + + private static void EnsureWithinDuration(long startedTimestamp, TimeSpan maximumDuration) + { + if (Stopwatch.GetElapsedTime(startedTimestamp) >= maximumDuration) + { + throw new TimeoutException("The Linux no-follow artifact extraction exceeded its configured duration."); + } + } + + private static void EnsureUnchanged(FileSnapshot before, FileSnapshot after) + { + if (before != after) + { + throw new InvalidDataException("A scratch artifact changed while it was being extracted."); + } + } + + private sealed class VerifiedSourceStream : Stream + { + private readonly FileStream _source; + private readonly SafeFileHandle _handle; + private readonly FileSnapshot _initialSnapshot; + private readonly long _expectedLength; + private readonly long _startedTimestamp; + private readonly TimeSpan _maximumDuration; + private readonly IncrementalHash _firstPassHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + private long _bytesRead; + private bool _validated; + + public VerifiedSourceStream( + FileStream source, + SafeFileHandle handle, + FileSnapshot initialSnapshot, + long expectedLength, + long startedTimestamp, + TimeSpan maximumDuration) + { + _source = source; + _handle = handle; + _initialSnapshot = initialSnapshot; + _expectedLength = expectedLength; + _startedTimestamp = startedTimestamp; + _maximumDuration = maximumDuration; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => _expectedLength; + + public override long Position + { + get => _bytesRead; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) + { + ArgumentNullException.ThrowIfNull(buffer); + return Read(buffer.AsSpan(offset, count)); + } + + public override int Read(Span buffer) + { + var bytesRead = _source.Read(buffer); + ProcessFirstPassBytes(buffer[..bytesRead]); + if (bytesRead == 0) + { + ValidateAtEndAsync(CancellationToken.None).GetAwaiter().GetResult(); + } + + return bytesRead; + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + var bytesRead = await _source.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + ProcessFirstPassBytes(buffer.Span[..bytesRead]); + if (bytesRead == 0) + { + await ValidateAtEndAsync(cancellationToken).ConfigureAwait(false); + } + + return bytesRead; + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(buffer); + return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); + } + + public override void Flush() => throw new NotSupportedException(); + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _firstPassHash.Dispose(); + } + + base.Dispose(disposing); + } + + private void ProcessFirstPassBytes(ReadOnlySpan bytes) + { + EnsureWithinDuration(_startedTimestamp, _maximumDuration); + if (bytes.Length == 0) + { + return; + } + + if (_bytesRead > _expectedLength - bytes.Length) + { + return; + } + + _firstPassHash.AppendData(bytes); + _bytesRead += bytes.Length; + } + + private async Task ValidateAtEndAsync(CancellationToken cancellationToken) + { + if (_validated) + { + return; + } + + EnsureWithinDuration(_startedTimestamp, _maximumDuration); + if (_bytesRead != _expectedLength) + { + throw new InvalidDataException("A scratch artifact ended before its opened descriptor size."); + } + + EnsureUnchanged(_initialSnapshot, ReadSnapshot(_handle)); + var firstDigest = _firstPassHash.GetHashAndReset(); + _source.Position = 0; + + using var secondPassHash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[StreamBufferSize]; + long secondPassBytes = 0; + while (true) + { + cancellationToken.ThrowIfCancellationRequested(); + EnsureWithinDuration(_startedTimestamp, _maximumDuration); + var bytesRead = await _source.ReadAsync(buffer.AsMemory(), cancellationToken).ConfigureAwait(false); + if (bytesRead == 0) + { + break; + } + + if (secondPassBytes > _expectedLength - bytesRead) + { + throw new InvalidDataException("A scratch artifact grew while its content was being verified."); + } + + secondPassHash.AppendData(buffer, 0, bytesRead); + secondPassBytes += bytesRead; + } + + var secondDigest = secondPassHash.GetHashAndReset(); + EnsureUnchanged(_initialSnapshot, ReadSnapshot(_handle)); + if (secondPassBytes != _expectedLength + || !CryptographicOperations.FixedTimeEquals(firstDigest, secondDigest)) + { + throw new InvalidDataException("A scratch artifact's content changed while it was being extracted."); + } + + _validated = true; + } + } + + private sealed class OpenedArtifact( + ValidatedRequest request, + SafeFileHandle handle, + FileSnapshot snapshot) : IDisposable + { + public ValidatedRequest Request { get; } = request; + + public SafeFileHandle Handle { get; } = handle; + + public FileSnapshot Snapshot { get; } = snapshot; + + public void Dispose() => Handle.Dispose(); + } + + private sealed record ValidatedRequest(string LogicalName, string SourceRelativePath, string DestinationRelativePath); + + private readonly record struct FileIdentity(uint DeviceMajor, uint DeviceMinor, ulong Inode); + + private readonly record struct FileSnapshot( + uint DeviceMajor, + uint DeviceMinor, + ulong Inode, + ushort Mode, + uint LinkCount, + ulong Size, + long ModifySeconds, + uint ModifyNanoseconds, + long ChangeSeconds, + uint ChangeNanoseconds) + { + public FileIdentity Identity => new(DeviceMajor, DeviceMinor, Inode); + } + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxOpenHow + { + public ulong Flags; + public ulong Mode; + public ulong Resolve; + } + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxStatxTimestamp + { + public long Seconds; + public uint Nanoseconds; + private int _reserved; + } + + [StructLayout(LayoutKind.Sequential, Size = 256)] + private struct LinuxStatx + { + public uint Mask; + private uint _blockSize; + private ulong _attributes; + public uint LinkCount; + private uint _userId; + private uint _groupId; + public ushort Mode; + private ushort _spare0; + public ulong Inode; + public ulong Size; + private ulong _blocks; + private ulong _attributesMask; + private LinuxStatxTimestamp _accessTime; + private LinuxStatxTimestamp _birthTime; + public LinuxStatxTimestamp ChangeTime; + public LinuxStatxTimestamp ModifyTime; + private uint _rdevMajor; + private uint _rdevMinor; + public uint DeviceMajor; + public uint DeviceMinor; + private ulong _mountId; + private uint _dioMemoryAlignment; + private uint _dioOffsetAlignment; + private ulong _spare1; + private ulong _spare2; + private ulong _spare3; + private ulong _spare4; + private ulong _spare5; + private ulong _spare6; + private ulong _spare7; + private ulong _spare8; + private ulong _spare9; + private ulong _spare10; + private ulong _spare11; + private ulong _spare12; + } + + [DllImport("libc", EntryPoint = "syscall", SetLastError = true)] + private static extern long Syscall(long number, int directoryDescriptor, IntPtr path, ref LinuxOpenHow how, nuint size); + + [DllImport("libc", EntryPoint = "statx", SetLastError = true)] + private static extern int Statx( + int directoryDescriptor, + [MarshalAs(UnmanagedType.LPUTF8Str)] string path, + int flags, + uint mask, + out LinuxStatx statx); +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md index 6f7d0cd57..a75dfbef9 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md @@ -16,6 +16,10 @@ for current release risk, migration guidance, and readiness. An `EvidencePolicy` resolves into an immutable `EvidencePlan`. A run records declared `EvidenceProducerResult` values and then uses `EvidenceManifestBuilder.Build(...)` to produce an `EvidenceManifest`. Both plan and manifest have canonical JSON and SHA-256 digests, so a gate can verify a result without rerunning the test suite. +Local path or text-diff planning retains contract version `1.0`. Revision-bound pull-request planning emits version `2.0` only when supplied a complete base commit ID, complete head commit ID, and a source diff that byte-for-byte matches the fixed-options Git diff for that pair. The v2 plan and manifest carry `BaseRevision`, `HeadRevision`, `SourceDiffDigest`, and `NameStatusDigest`. `DiffDigest` continues to bind the normalized path inventory; it is distinct from the exact source-diff digest. A trusted controller can also record `EvidencePullRequestRunIdentity` in the plan and manifest: numeric repository/head repository IDs, PR number, target branch, run ID, and attempt. A local rehearsal omits it; the final verifier must compare it with authoritative GitHub data. Optional v2 fields are omitted from v1 canonical JSON, preserving existing v1 digests. A v1 local manifest may still describe its local claim, but the [AppSurface CI gate design](../../docs/designs/issue-777-policy-driven-ci-evidence-gate.md) does not accept v1 as authorization. + +`EvidenceRevisionPlanBuilder.ResolveForPullRequest(...)` requires the conservative mixed-profile policy and rejects a release-only profile on a PR. `EvidenceRevisionPlanBuilder.VerifyAsync(...)` independently regenerates the Git diff/status and policy selection from a trusted object store and trusted base-owned policy. `EvidenceManifestBuilder.Verify(...)` checks internal plan/manifest consistency, including v2 field shape and equality, but cannot authenticate the GitHub event, trusted policy source, or subject job. The final CI verifier must check those external facts and current PR base/head before issuing a gate verdict. + | Type family | Purpose | | --- | --- | | `EvidencePolicy`, `EvidenceProfile`, `EvidencePolicyRule` | Checked-in change-risk policy and explicitly selected profile. | @@ -23,6 +27,32 @@ An `EvidencePolicy` resolves into an immutable `EvidencePlan`. A run records dec | `EvidencePlan`, `NormalizedDiffPath` | Deterministic resolved input. The plan binds policy identity, diff, selected profile, and matched rules. | | `EvidenceProducerResult`, `EvidenceManifest` | Terminal producer outcomes and the resulting gate claim. | | `EvidenceCanonicalJson`, `EvidenceDigest`, `EvidenceManifestBuilder` | Canonical serialization, digesting, claim calculation, and manifest verification. | +| `EvidenceArtifactWriter`, `EvidenceArtifactValidation` | Bounded artifact copying, streamed integrity verification, and declaration/path validation. | +| `EvidenceNoFollowArtifactExtractor` | Linux descriptor-relative extraction of explicitly selected untrusted scratch files into declared artifact slots. | + +## Writing and verifying artifacts + +`EvidenceArtifactWriter.WriteAsync(logicalName, relativePath, ReadOnlyMemory, cancellationToken)` remains available for artifacts already held in memory. Producers handling larger artifacts should use the stream overload: + +```csharp +await using var input = File.OpenRead(sourcePath); +var artifact = await context.Artifacts!.WriteAsync( + "report", + "coverage/report.json", + input, + declaredLengthBytes, + cancellationToken); +``` + +The stream overload requires a readable stream and an explicit, non-negative declared length. It checks that length against the selected slot's `MaximumBytes` and the remaining per-producer v1 allowance before reading. The v1 producer allowance is 256 MiB total across all artifact slots. The stream must yield exactly the declared number of bytes: an early end or any extra byte fails with `InvalidDataException`; an over-limit declaration fails before the stream is consumed. SHA-256 is computed as bytes are copied through a fixed-size buffer, so memory use does not grow with artifact size. The writer does not seek or rewind the input, and it does not dispose it; callers should pass a stream positioned at the artifact's first byte. A short stream is read through EOF, while an overlong stream is read through at most one byte beyond the declaration before failing. Cancellation propagates and a failed or cancelled stream write releases its reservation and removes its partial destination when possible. + +After writing, `VerifyWrittenArtifactsAsync(cancellationToken)` opens each destination as a stream and recomputes its length and digest with the same bounded-buffer approach. It returns `false` if an artifact is missing, exceeds its slot or producer limit, or no longer matches the metadata; cancellation propagates. Verification detects later changes to the copied file, while the returned `EvidenceArtifactResult` contains only the declared name, normalized relative path, media type, byte length, and digest. + +The writer's destination handling is path-based beneath a controlled evidence root. Neither the stream overload nor `VerifyWrittenArtifactsAsync` is a no-follow, descriptor-relative extraction primitive. Pass only separately validated trusted streams and use a dedicated no-follow extraction boundary for untrusted scratch paths; a path that appears contained is not proof that symlinks or concurrent path changes were excluded. Prefer the stream overload when the artifact is not already in memory, and use the memory overload for small content that the producer already owns as a byte buffer. + +For untrusted scratch output on Linux x64 or arm64, use `EvidenceNoFollowArtifactExtractor.ExtractAsync` with an already-open handle to the trusted scratch directory, an `EvidenceArtifactWriter` configured for the declared producer, and an explicit list of `EvidenceNoFollowArtifact` source/destination mappings. The extractor opens each source relative to that handle with Linux `openat2` no-symlink and beneath-root constraints, verifies regular-file identity and a single hard link with `statx`, streams it into the declared slot, and checks for mutation. It does not discover files or accept a subject-provided artifact list as authority. Source and destination paths must be canonical slash-separated relative paths without empty, `.` or `..` components; duplicate mappings are rejected. + +By default one extraction accepts at most 64 files and 256 MiB in two minutes, in addition to each slot's own byte limit. `EvidenceNoFollowArtifactExtractionLimits` can lower those limits but cannot raise them. Unsupported operating systems, architectures, or kernels fail closed; there is no path-based fallback. Extraction is sequential, not transactional: an error on a later file does not undo already written artifacts, so a caller must treat the whole producer result as failed and clean its artifact root before any claim. This primitive validates scratch-to-writer copying; the [trusted PR verifier](../ForgeTrust.AppSurface.Evidence.Planner/README.md) must separately authenticate the final handoff artifact bytes and job provenance. `EvidenceClaimKind.TargetedComplete` is eligible for a pull-request gate; `ReleaseComplete` is eligible only for a release gate and requires `ValidatedNotAttested` envelope status. `ObservationOnly` is deliberately informative, never gate-eligible. `NoEvidenceRequired` is valid only when the selected profile declares no resources, producers, or obligations. @@ -44,5 +74,6 @@ An unavailable capability, timeout, skipped producer, incomplete test profile, o - Do not treat a coverage collection artifact as a gate pass unless its producer has closed the assertion declared by the selected policy. - Do not claim independent attestation in v1. An accepted envelope is represented as `ValidatedNotAttested`. - Do not edit generated plan or manifest JSON. `EvidenceManifestBuilder.Verify(...)` and `appsurface evidence verify` detect inconsistent or edited claim fields by recomputing internal digests; they do not authenticate their inputs. Gates must obtain the plan and manifest through a trusted CI channel. +- Do not interpret `2.0` as a runtime sandbox claim. Revision binding says which commit pair was planned; a trusted controller and verifier must still establish job provenance, isolation, cleanup, and current PR identity. The built-in `appsurface evidence run` emits `ObservationOnly` for v2 inputs because that local command cannot establish those conditions. Read next: the [planner README](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md), the [Aspire lifecycle README](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Aspire/README.md), and the [EvidenceHost cookbook](https://github.com/forge-trust/AppSurface/blob/main/guides/evidencehost-cookbook.md). diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceGitChangeCapture.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceGitChangeCapture.cs new file mode 100644 index 000000000..f977c6ad2 --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceGitChangeCapture.cs @@ -0,0 +1,424 @@ +using System.Diagnostics; +using System.Text; +using ForgeTrust.AppSurface.Evidence.Contracts; + +namespace ForgeTrust.AppSurface.Evidence.Planner; + +/// +/// Captures the two byte-exact Git representations used by a revision-bound evidence gate. +/// +/// +/// A source diff binds the plan to exact Git output; a separate NUL-delimited status stream +/// selects paths even when a binary, mode, symlink, or submodule change has no text hunk. +/// Neither representation authenticates the repository or a remote PR by itself. +/// +public sealed class EvidenceGitChangeSnapshot +{ + private readonly byte[] _sourceDiff; + private readonly byte[] _nameStatus; + + internal EvidenceGitChangeSnapshot( + string baseRevision, + string headRevision, + byte[] sourceDiff, + byte[] nameStatus, + IReadOnlyList changedPaths) + { + BaseRevision = baseRevision; + HeadRevision = headRevision; + _sourceDiff = sourceDiff; + _nameStatus = nameStatus; + SourceDiffDigest = EvidenceDigest.Sha256(sourceDiff); + NameStatusDigest = EvidenceDigest.Sha256(nameStatus); + ChangedPaths = Array.AsReadOnly(changedPaths.ToArray()); + } + + /// Gets the complete canonical base commit object ID. + public string BaseRevision { get; } + + /// Gets the complete canonical head commit object ID. + public string HeadRevision { get; } + + /// Gets the bounded source diff bytes. Callers must not treat them as executable instructions. + public ReadOnlyMemory SourceDiff => _sourceDiff; + + /// Gets the bounded NUL-delimited name-status bytes. + public ReadOnlyMemory NameStatus => _nameStatus; + + /// Gets the SHA-256 of the exact source diff bytes. + public string SourceDiffDigest { get; } + + /// Gets the SHA-256 of the exact name-status bytes. + public string NameStatusDigest { get; } + + /// Gets the normalized changed paths used for policy selection. + public IReadOnlyList ChangedPaths { get; } +} + +/// +/// Runs Git with fixed diff options against two complete commit IDs in a trusted object store. +/// +/// +/// Supply a trusted bare or object-only checkout containing both commits. The caller is responsible +/// for fetching the exact objects, pinning the Git version in CI, and independently checking current +/// PR or tag identity before a gate verdict. This type never reads the ambient checkout's HEAD. +/// +public static class EvidenceGitChangeCapture +{ + /// Maximum captured source diff size for the first AppSurface gate. + public const int MaximumSourceDiffBytes = 20 * 1024 * 1024; + + /// Maximum number of changed records accepted for policy selection. + public const int MaximumChangedRecords = 10_000; + + /// Maximum UTF-8 byte length of one changed repository path. + public const int MaximumPathBytes = 4 * 1024; + + /// Maximum wall-clock seconds for capture of both Git representations. + public const int MaximumCaptureSeconds = 120; + + private const int MaximumNameStatusBytes = 85 * 1024 * 1024; + private static readonly UTF8Encoding StrictUtf8 = new(false, true); + + /// + /// Captures and validates a byte-exact diff and NUL status stream for the same commit pair. + /// + /// Trusted Git object store containing both commits. + /// Full 40- or 64-character lower-case commit ID. + /// Full commit ID in the same object format. + /// Cancellation for Git execution and bounded reads. + /// A bounded snapshot suitable for trusted policy planning. + public static async Task CaptureAsync( + string repositoryPath, + string baseRevision, + string headRevision, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(repositoryPath); + ValidateRevision(baseRevision); + ValidateRevision(headRevision); + if (baseRevision.Length != headRevision.Length) + { + throw new EvidencePlanningException("ASEVD130", "Git revisions use different object ID formats.", "Supply two complete commit IDs from the same repository."); + } + + var repository = Path.GetFullPath(repositoryPath); + if (!Directory.Exists(repository)) + { + throw new EvidencePlanningException("ASEVD131", "The trusted Git object store is unavailable.", "Fetch the exact base and head commits into a trusted object-only checkout."); + } + + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + deadline.CancelAfter(TimeSpan.FromSeconds(MaximumCaptureSeconds)); + try + { + return await CaptureWithinDeadlineAsync(repository, baseRevision, headRevision, deadline.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) + { + throw new EvidencePlanningException("ASEVD137", "Exact Git change capture exceeded its deadline.", "Retry in the pinned runner or reduce the change before a reviewed deadline increase."); + } + } + + private static async Task CaptureWithinDeadlineAsync( + string repository, + string baseRevision, + string headRevision, + CancellationToken cancellationToken) + { + await RequireCommitAsync(repository, baseRevision, cancellationToken).ConfigureAwait(false); + await RequireCommitAsync(repository, headRevision, cancellationToken).ConfigureAwait(false); + + var sourceDiff = await RunGitAsync( + repository, + ["-c", "diff.external=", "-c", "diff.noprefix=false", "-c", "diff.mnemonicprefix=false", "-c", "diff.algorithm=myers", "diff", "--no-ext-diff", "--no-textconv", "--no-color", "--binary", "--full-index", "--unified=3", "--find-renames=50%", "--find-copies=50%", "--submodule=short", "--ignore-submodules=none", "--no-relative", "--src-prefix=a/", "--dst-prefix=b/", baseRevision, headRevision, "--"], + MaximumSourceDiffBytes, + cancellationToken).ConfigureAwait(false); + var nameStatus = await RunGitAsync( + repository, + ["-c", "diff.external=", "-c", "diff.noprefix=false", "-c", "diff.mnemonicprefix=false", "-c", "diff.algorithm=myers", "diff", "--name-status", "-z", "--no-ext-diff", "--no-textconv", "--no-color", "--find-renames=50%", "--find-copies=50%", "--submodule=short", "--ignore-submodules=none", "--no-relative", baseRevision, headRevision, "--"], + MaximumNameStatusBytes, + cancellationToken).ConfigureAwait(false); + if (sourceDiff.Length == 0 && nameStatus.Length != 0) + { + throw new EvidencePlanningException("ASEVD133", "Git source diff is empty while changed paths are reported.", "Recapture both representations from the same exact commit pair."); + } + + var paths = ParseNameStatus(nameStatus); + if (paths.Count == 0) + { + throw new EvidencePlanningException("ASEVD132", "The exact Git revisions have no changed paths.", "Use a commit pair with an explicit policy-selected change; never infer a no-evidence claim from an empty diff."); + } + + return new EvidenceGitChangeSnapshot(baseRevision, headRevision, sourceDiff, nameStatus, paths); + } + + /// + /// Regenerates both Git representations and rejects a changed or substituted snapshot. + /// + /// The same trusted object store used for capture. + /// Snapshot whose exact bytes and normalized paths must still bind. + /// Cancellation for Git execution. + /// A task that completes only when both representations match. + public static async Task VerifyAsync( + string repositoryPath, + EvidenceGitChangeSnapshot snapshot, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(snapshot); + var regenerated = await CaptureAsync(repositoryPath, snapshot.BaseRevision, snapshot.HeadRevision, cancellationToken).ConfigureAwait(false); + if (!regenerated.SourceDiff.Span.SequenceEqual(snapshot.SourceDiff.Span) + || !regenerated.NameStatus.Span.SequenceEqual(snapshot.NameStatus.Span) + || !regenerated.ChangedPaths.SequenceEqual(snapshot.ChangedPaths)) + { + throw new EvidencePlanningException("ASEVD133", "Git change bytes or selected paths differ from the captured snapshot.", "Discard the stale plan and recapture both representations from the exact commit objects."); + } + } + + /// + /// Strictly parses git diff --name-status -z bytes, including both rename or copy paths. + /// + /// Complete NUL-delimited Git stdout. + /// Changed paths in Git's order. + public static IReadOnlyList ParseNameStatus(ReadOnlySpan bytes) + { + if (bytes.Length > MaximumNameStatusBytes) + { + throw MalformedStatus(); + } + + var changes = new List(); + var seen = new HashSet(StringComparer.Ordinal); + var offset = 0; + while (offset < bytes.Length) + { + if (changes.Count >= MaximumChangedRecords) + { + throw new EvidencePlanningException("ASEVD134", "Git reported too many changed records.", "Reduce the change or revise the reviewed gate limit and its tests."); + } + + var status = ReadField(bytes, ref offset); + var isPair = status.Length > 0 && (status[0] == 'R' || status[0] == 'C'); + if (!IsSupportedStatus(status)) + { + throw MalformedStatus(); + } + + var firstPath = ReadPath(bytes, ref offset); + var path = isPair ? ReadPath(bytes, ref offset) : firstPath; + if (!seen.Add(path)) + { + throw MalformedStatus(); + } + + changes.Add(new NormalizedDiffPath(path, StatusKind(status[0]), isPair ? firstPath : null)); + } + + return changes; + } + + private static string ReadPath(ReadOnlySpan bytes, ref int offset) + { + var field = ReadFieldBytes(bytes, ref offset); + if (field.Length is 0 or > MaximumPathBytes) + { + throw MalformedStatus(); + } + + string path; + try + { + path = StrictUtf8.GetString(field); + } + catch (DecoderFallbackException) + { + throw MalformedStatus(); + } + + if (path.StartsWith('/') + || path.EndsWith('/') + || path.Contains('\\') + || path.Any(char.IsControl) + || path.Split('/').Any(static segment => segment.Length == 0 || segment is "." or "..")) + { + throw MalformedStatus(); + } + + return path; + } + + private static string ReadField(ReadOnlySpan bytes, ref int offset) + { + var field = ReadFieldBytes(bytes, ref offset); + if (field.Length is 0 or > 4) + { + throw MalformedStatus(); + } + + try + { + return StrictUtf8.GetString(field); + } + catch (DecoderFallbackException) + { + throw MalformedStatus(); + } + } + + private static ReadOnlySpan ReadFieldBytes(ReadOnlySpan bytes, ref int offset) + { + var terminator = bytes[offset..].IndexOf((byte)0); + if (terminator < 0) + { + throw MalformedStatus(); + } + + var field = bytes.Slice(offset, terminator); + offset += terminator + 1; + return field; + } + + private static bool IsSupportedStatus(string status) + { + if (status is "A" or "D" or "M" or "T") + { + return true; + } + + return status.Length is >= 2 and <= 4 + && status[0] is 'R' or 'C' + && int.TryParse(status.AsSpan(1), out var score) + && score is >= 0 and <= 100; + } + + private static string StatusKind(char status) => status switch + { + 'A' => "added", + 'D' => "deleted", + 'M' => "modified", + 'T' => "typechanged", + 'R' => "renamed", + 'C' => "copied", + _ => throw MalformedStatus(), + }; + + private static EvidencePlanningException MalformedStatus() => + new("ASEVD135", "Git name-status output is malformed or contains an unsafe path.", "Recapture the exact commit pair with the pinned Git runner; do not fall back to text-hunk path selection."); + + private static void ValidateRevision(string revision) + { + if (string.IsNullOrWhiteSpace(revision) + || revision.Length is not (40 or 64) + || revision.Any(static character => character is not (>= '0' and <= '9' or >= 'a' and <= 'f'))) + { + throw new EvidencePlanningException("ASEVD130", "A Git revision is not a complete lower-case commit ID.", "Supply the complete base and head object IDs, not refs or abbreviated SHAs."); + } + } + + private static async Task RequireCommitAsync(string repository, string revision, CancellationToken cancellationToken) + { + var result = await RunGitAsync(repository, ["cat-file", "-t", revision], 32, cancellationToken).ConfigureAwait(false); + if (!result.AsSpan().SequenceEqual("commit\n"u8)) + { + throw new EvidencePlanningException("ASEVD131", "An exact Git revision is not a commit object.", "Fetch the complete base and head commits into the trusted object store."); + } + } + + private static async Task RunGitAsync( + string repository, + IReadOnlyList arguments, + int maximumBytes, + CancellationToken cancellationToken) + { + var start = new ProcessStartInfo("git") + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + CreateNoWindow = true, + }; + start.ArgumentList.Add("--no-pager"); + start.ArgumentList.Add("-C"); + start.ArgumentList.Add(repository); + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + // A trusted object-store path must not be redirected by inherited Git environment + // variables such as GIT_DIR or GIT_ALTERNATE_OBJECT_DIRECTORIES. Keep only the + // fixed settings below, independent of the caller's ambient checkout. + foreach (var key in start.Environment.Keys.Where(static key => key.StartsWith("GIT_", StringComparison.OrdinalIgnoreCase)).ToArray()) + { + start.Environment.Remove(key); + } + + start.Environment["GIT_CONFIG_NOSYSTEM"] = "1"; + start.Environment["GIT_CONFIG_GLOBAL"] = OperatingSystem.IsWindows() ? "NUL" : "/dev/null"; + start.Environment["GIT_CONFIG_COUNT"] = "0"; + start.Environment["GIT_CONFIG_PARAMETERS"] = string.Empty; + start.Environment["GIT_EXTERNAL_DIFF"] = string.Empty; + start.Environment["GIT_DIFF_OPTS"] = string.Empty; + start.Environment["GIT_PAGER"] = "cat"; + start.Environment["LC_ALL"] = "C"; + + using var process = new Process { StartInfo = start }; + try + { + if (!process.Start()) + { + throw new EvidencePlanningException("ASEVD136", "The trusted Git process did not start.", "Install the pinned Git version in the gate runner."); + } + + var stdoutTask = ReadBoundedAsync(process.StandardOutput.BaseStream, maximumBytes, cancellationToken); + var stderrTask = ReadBoundedAsync(process.StandardError.BaseStream, 4096, cancellationToken); + try + { + var stdout = await stdoutTask.ConfigureAwait(false); + await stderrTask.ConfigureAwait(false); + await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); + if (process.ExitCode != 0) + { + throw new EvidencePlanningException("ASEVD136", "Git could not read the exact commit pair.", "Fetch both complete commits into the trusted object store and recapture the change."); + } + + return stdout; + } + catch + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + } + + throw; + } + } + catch (Exception exception) when (exception is System.ComponentModel.Win32Exception or IOException) + { + throw new EvidencePlanningException("ASEVD136", "The trusted Git process is unavailable.", "Install the pinned Git version and ensure its object store is readable."); + } + } + + private static async Task ReadBoundedAsync(Stream stream, int maximumBytes, CancellationToken cancellationToken) + { + await using var captured = new MemoryStream(); + var buffer = new byte[81920]; + while (true) + { + var request = (int)Math.Min(buffer.Length, maximumBytes - captured.Length + 1); + var count = await stream.ReadAsync(buffer.AsMemory(0, request), cancellationToken).ConfigureAwait(false); + if (count == 0) + { + return captured.ToArray(); + } + + if (captured.Length + count > maximumBytes) + { + throw new EvidencePlanningException("ASEVD134", "Git output exceeds the reviewed gate byte limit.", "Reduce the change or revise the reviewed gate limit and its tests."); + } + + await captured.WriteAsync(buffer.AsMemory(0, count), cancellationToken).ConfigureAwait(false); + } + } +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs index 892e3fe13..b08893004 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePlanner.cs @@ -20,6 +20,32 @@ public EvidencePlan Resolve(EvidencePolicy policy, IReadOnlyList + /// Resolves a plan for a pull-request gate after verifying that mixed targeted profiles + /// cannot lose requirements when selection falls back to the conservative profile. + /// + /// Versioned consumer policy used by the trusted gate. + /// Explicit normalized changed paths, including both sides of renames. + /// A hash-bound evidence plan whose mixed-profile fallback is validated as a superset. + /// + /// This is an opt-in gate API. + /// and retain their local v1 behavior and do not + /// enforce cross-profile closure. + /// + public EvidencePlan ResolveForGate(EvidencePolicy policy, IReadOnlyList changedPaths) + { + ArgumentNullException.ThrowIfNull(policy); + ArgumentNullException.ThrowIfNull(changedPaths); + + ValidateGatePolicy(policy); + return ResolveValidated(policy, changedPaths); + } + + private static EvidencePlan ResolveValidated(EvidencePolicy policy, IReadOnlyList changedPaths) + { if (changedPaths.Count == 0) { throw new EvidencePlanningException( @@ -129,6 +155,240 @@ public static void ValidatePolicy(EvidencePolicy policy) } } + /// + /// Validates that a policy's conservative fallback preserves every requirement from each + /// rule-selected targeted profile that may participate in a mixed pull-request diff. + /// + /// Policy to validate before using it for a pull-request gate. + /// + /// The check includes resources and their readiness declarations, producers and their resource + /// wiring, assertions, artifact slots, and obligations. Additional conservative requirements + /// are allowed. Targeted profiles with no evidence requirements, such as an explicit docs-only + /// profile, are valid and contribute no requirements to the superset check. Release profiles + /// are outside this pull-request check and need their own event and eligibility validation. + /// Existing local v1 callers may continue to use . + /// + /// is . + /// The policy is invalid or its conservative profile + /// omits or weakens a targeted profile requirement. + public static void ValidateGatePolicy(EvidencePolicy policy) + { + ValidatePolicy(policy); + + var profiles = policy.Profiles.ToDictionary(static profile => profile.Id, StringComparer.Ordinal); + var conservativeProfile = profiles[policy.ConservativeProfileId]; + if (conservativeProfile.Scope != EvidenceProfileScope.Targeted) + { + throw new EvidencePlanningException( + "ASEVD129", + $"Conservative profile '{conservativeProfile.Id}' is not a targeted pull-request profile.", + "Use a targeted PR policy and validate release profiles only in the protected release context."); + } + + var releaseRule = policy.Rules.FirstOrDefault(rule => profiles[rule.ProfileId].Scope != EvidenceProfileScope.Targeted); + if (releaseRule is not null) + { + throw new EvidencePlanningException( + "ASEVD129", + $"Pull-request gate rule '{releaseRule.Id}' selects non-targeted profile '{releaseRule.ProfileId}'.", + "Map pull-request changes to targeted profiles; select release profiles only from the validated protected release context."); + } + + var targetedProfiles = policy.Rules + .Select(rule => profiles[rule.ProfileId]) + .DistinctBy(static profile => profile.Id, StringComparer.Ordinal) + .Where(profile => !string.Equals(profile.Id, conservativeProfile.Id, StringComparison.Ordinal)) + .OrderBy(static profile => profile.Id, StringComparer.Ordinal); + + foreach (var targetedProfile in targetedProfiles) + { + ValidateConservativeProfileSuperset(conservativeProfile, targetedProfile); + } + } + + private static void ValidateConservativeProfileSuperset(EvidenceProfile conservativeProfile, EvidenceProfile targetedProfile) + { + var conservativeResources = conservativeProfile.Resources.ToDictionary(static resource => resource.Id, StringComparer.Ordinal); + foreach (var requiredResource in targetedProfile.Resources.OrderBy(static resource => resource.Id, StringComparer.Ordinal)) + { + if (!conservativeResources.TryGetValue(requiredResource.Id, out var candidateResource)) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"resource '{requiredResource.Id}'", + "the declaration is missing"); + } + + if (!string.Equals(candidateResource.Readiness, requiredResource.Readiness, StringComparison.Ordinal) + || candidateResource.DeadlineSeconds > requiredResource.DeadlineSeconds) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"resource '{requiredResource.Id}'", + "the readiness mode or deadline is weaker than the targeted declaration"); + } + + var missingDependency = requiredResource.Requires + .Where(dependencyId => !candidateResource.Requires.Contains(dependencyId, StringComparer.Ordinal)) + .OrderBy(static dependencyId => dependencyId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingDependency is not null) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"resource dependency '{missingDependency}' for resource '{requiredResource.Id}'", + "the dependency is missing"); + } + } + + var conservativeProducers = conservativeProfile.Producers.ToDictionary(static producer => producer.Id, StringComparer.Ordinal); + foreach (var requiredProducer in targetedProfile.Producers.OrderBy(static producer => producer.Id, StringComparer.Ordinal)) + { + if (!conservativeProducers.TryGetValue(requiredProducer.Id, out var candidateProducer)) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"producer '{requiredProducer.Id}'", + "the declaration is missing"); + } + + if (!string.Equals(candidateProducer.Kind, requiredProducer.Kind, StringComparison.Ordinal) + || !string.Equals(candidateProducer.Version, requiredProducer.Version, StringComparison.Ordinal) + || candidateProducer.TimeoutSeconds > requiredProducer.TimeoutSeconds + || !PreservesCoverageGate(candidateProducer.CoverageGate, requiredProducer.CoverageGate)) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"producer '{requiredProducer.Id}'", + "the kind, version, deadline, or coverage gate does not preserve the targeted declaration"); + } + + var missingResource = requiredProducer.RequiredResources + .Where(resourceId => !candidateProducer.RequiredResources.Contains(resourceId, StringComparer.Ordinal)) + .OrderBy(static resourceId => resourceId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingResource is not null) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"resource '{missingResource}' required by producer '{requiredProducer.Id}'", + "the producer no longer requires it"); + } + + var missingAssertion = requiredProducer.AssertionIds + .Where(assertionId => !candidateProducer.AssertionIds.Contains(assertionId, StringComparer.Ordinal)) + .OrderBy(static assertionId => assertionId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingAssertion is not null) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"assertion '{missingAssertion}' on producer '{requiredProducer.Id}'", + "the assertion is missing"); + } + + var conservativeArtifactSlots = candidateProducer.ArtifactSlots.ToDictionary(static slot => slot.LogicalName, StringComparer.Ordinal); + foreach (var requiredSlot in requiredProducer.ArtifactSlots.OrderBy(static slot => slot.LogicalName, StringComparer.Ordinal)) + { + if (!conservativeArtifactSlots.TryGetValue(requiredSlot.LogicalName, out var candidateSlot)) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"artifact slot '{requiredProducer.Id}/{requiredSlot.LogicalName}'", + "the declaration is missing"); + } + + if (!string.Equals(candidateSlot.RelativeRoot, requiredSlot.RelativeRoot, StringComparison.Ordinal) + || !string.Equals(candidateSlot.MediaType, requiredSlot.MediaType, StringComparison.Ordinal) + || (requiredSlot.Required && !candidateSlot.Required) + || candidateSlot.MaximumBytes > requiredSlot.MaximumBytes) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"artifact slot '{requiredProducer.Id}/{requiredSlot.LogicalName}'", + "its root, media type, required flag, or byte limit weakens the targeted declaration"); + } + } + } + + var conservativeObligations = conservativeProfile.Obligations.ToDictionary(static obligation => obligation.Id, StringComparer.Ordinal); + foreach (var requiredObligation in targetedProfile.Obligations.OrderBy(static obligation => obligation.Id, StringComparer.Ordinal)) + { + if (!conservativeObligations.TryGetValue(requiredObligation.Id, out var candidateObligation)) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"obligation '{requiredObligation.Id}'", + "the declaration is missing"); + } + + if (!string.Equals(candidateObligation.RiskClass, requiredObligation.RiskClass, StringComparison.Ordinal) + || !string.Equals(candidateObligation.Rationale, requiredObligation.Rationale, StringComparison.Ordinal) + || !string.Equals(candidateObligation.RequiredAssertionId, requiredObligation.RequiredAssertionId, StringComparison.Ordinal)) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"obligation '{requiredObligation.Id}'", + "its risk class, rationale, or required assertion does not preserve the targeted declaration"); + } + + var missingProducer = requiredObligation.RequiredProducerIds + .Where(producerId => !candidateObligation.RequiredProducerIds.Contains(producerId, StringComparer.Ordinal)) + .OrderBy(static producerId => producerId, StringComparer.Ordinal) + .FirstOrDefault(); + if (missingProducer is not null) + { + throw GatePolicyValidationFailure( + conservativeProfile, + targetedProfile, + $"producer '{missingProducer}' required by obligation '{requiredObligation.Id}'", + "the obligation no longer requires it"); + } + } + } + + private static EvidencePlanningException GatePolicyValidationFailure( + EvidenceProfile conservativeProfile, + EvidenceProfile targetedProfile, + string requirement, + string detail) => + new( + "ASEVD129", + $"Conservative profile '{conservativeProfile.Id}' does not preserve {requirement} required by targeted profile '{targetedProfile.Id}': {detail}.", + "Add the missing or equivalent requirement to the conservative profile, or use an explicit combined profile for the pull-request paths."); + + private static bool PreservesCoverageGate( + EvidenceCoverageGateRequirements? candidate, + EvidenceCoverageGateRequirements? required) + { + if (required is null) + { + return true; + } + + return candidate is not null + && candidate.MinLinePercent >= required.MinLinePercent + && candidate.MinBranchPercent >= required.MinBranchPercent + && OptionalThresholdIsPreserved(candidate.MinPatchLinePercent, required.MinPatchLinePercent) + && OptionalThresholdIsPreserved(candidate.MinPatchBranchPercent, required.MinPatchBranchPercent) + && string.Equals(candidate.PatchLineMode, required.PatchLineMode, StringComparison.OrdinalIgnoreCase) + && candidate.TolerancePercent <= required.TolerancePercent; + } + + private static bool OptionalThresholdIsPreserved(decimal? candidate, decimal? required) => + required is null || (candidate is { } candidateValue && candidateValue >= required.Value); + private static void ValidateProfile(EvidenceProfile profile) { if (profile.Resources.Count > EvidenceProfileLimits.MaximumResources diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePullRequestGateVerifier.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePullRequestGateVerifier.cs new file mode 100644 index 000000000..046b888e2 --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidencePullRequestGateVerifier.cs @@ -0,0 +1,1128 @@ +using System.Runtime.InteropServices; +using System.Security.Cryptography; +using ForgeTrust.AppSurface.Evidence.Contracts; +using Microsoft.Win32.SafeHandles; + +namespace ForgeTrust.AppSurface.Evidence.Planner; + +/// +/// Identifies the pull request and subject job expected by the trusted controller. +/// +/// Canonical base repository in owner/name form. +/// Validated workflow event name. +/// Controller-owned workflow identity. +/// Controller-owned subject job identity. +/// Controller-owned numeric repository, PR, run, and attempt identity. +public sealed record EvidencePullRequestGateExpectedIdentity( + string Repository, + string EventName, + string WorkflowId, + string SubjectJobId, + EvidencePullRequestRunIdentity RunIdentity); + +/// +/// Reports one fresh PR view and the authoritative provenance of its subject job. +/// +/// Base repository containing the pull request. +/// Event that created the workflow run. +/// Current target-branch commit ID. +/// Current pull request head commit ID. +/// Workflow associated with the subject job. +/// Authoritative PR, repository, run, and attempt identity. +/// Subject job identity. +/// Commit checked out by the subject job. +/// Authoritative terminal job conclusion. +/// Whether an independent trusted observation confirmed the subject job's isolation envelope. +public sealed record EvidencePullRequestGateAuthoritySnapshot( + string Repository, + string EventName, + string BaseRevision, + string HeadRevision, + string WorkflowId, + EvidencePullRequestRunIdentity RunIdentity, + string SubjectJobId, + string SubjectJobHeadRevision, + string SubjectJobConclusion, + bool SubjectEnvelopeAttested = false); + +/// Describes one matched trusted policy rule in a bounded gate result. +/// Trusted policy rule identifier, or the bounded conservative-fallback identifier. +/// Trusted policy pattern, or a fixed conservative-fallback description. +/// Trusted profile selected by the rule. +public sealed record EvidencePullRequestGateRuleSummary(string Id, string Pattern, string ProfileId); + +/// Describes why one trusted obligation was selected. +/// Trusted obligation identifier. +/// Trusted obligation risk class. +/// Trusted policy rationale, bounded for rendering. +public sealed record EvidencePullRequestGateObligationRationale(string Id, string RiskClass, string Rationale); + +/// +/// Bounded rendering data derived from the plan independently verified against trusted policy and Git. +/// +/// Selected profile identifier from the verified plan. +/// Fixed explanation of direct-rule or conservative-fallback selection. +/// Bounded matched-rule details from trusted policy. +/// Bounded identifiers selected by the verified profile. +/// Bounded verified closure identifiers that are also selected by the verified profile. +/// Bounded selected identifiers not independently closed by validated producer assertions. +/// Bounded trusted rationale for selected obligations. +/// First 12 characters of the verified base object ID. +/// First 12 characters of the verified head object ID. +/// Number of matched rules omitted from this rendering summary. +/// Number of selected obligation IDs omitted from this summary. +/// Number of closed obligation IDs omitted from this summary. +/// Number of missing obligation IDs omitted from this summary. +/// Number of obligation rationales omitted from this summary. +/// Whether the verified profile selects a resource, producer, or obligation. +public sealed record EvidencePullRequestGateSummary( + string ProfileId, + string SelectionRationale, + IReadOnlyList MatchedRules, + IReadOnlyList SelectedObligationIds, + IReadOnlyList ClosedObligationIds, + IReadOnlyList MissingObligationIds, + IReadOnlyList ObligationRationales, + string BaseRevisionShort, + string HeadRevisionShort, + int OmittedMatchedRuleCount, + int OmittedSelectedObligationCount, + int OmittedClosedObligationCount, + int OmittedMissingObligationCount, + int OmittedObligationRationaleCount, + bool ProfileHasEvidence); + +/// +/// Provides an authoritative, fresh PR revision and subject-job provenance observation. +/// +public interface IEvidencePullRequestGateAuthorityProvider +{ + /// + /// Reads the current PR target/head and the run/job association for the expected controller context. + /// + /// Identity captured by the trusted controller. + /// Cancellation for the authority lookup. + /// A fresh observation, or when it is unavailable. + Task ReadFreshAsync( + EvidencePullRequestGateExpectedIdentity expectedIdentity, + CancellationToken cancellationToken = default); +} + +/// +/// Verifies the bytes behind manifest artifact metadata using the trusted extracted-artifact root. +/// +/// +/// Implementations must open artifacts without following links, enforce the declared artifact roots, +/// and hash the bytes actually read. Returning asserts that every artifact +/// record in the manifest matches its declared logical slot, media type, length, and digest. The gate +/// never treats manifest metadata alone as byte proof. +/// +public interface IEvidencePullRequestGateArtifactVerifier +{ + /// Verifies artifact bytes associated with one independently verified plan. + /// Controller-owned extracted-artifact handoff directory. + /// Plan already recreated from trusted policy and exact Git objects. + /// Bounded manifest whose artifact bytes must be checked. + /// Cancellation for bounded no-follow reads. + /// only when all artifact records are confirmed from bytes. + Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default); +} + +/// +/// Verifies declared artifact bytes by opening every path beneath a trusted handoff root without following links. +/// +/// +/// This implementation requires Linux x64 or arm64 with openat2 and statx. It fails closed on other +/// platforms or when those kernel facilities are unavailable. The supplied root must be a controller-owned +/// directory containing one subdirectory per producer, matching the EvidenceHost artifact layout. +/// +public sealed class EvidencePullRequestGateNoFollowArtifactVerifier : IEvidencePullRequestGateArtifactVerifier +{ + private const long OpenAt2SyscallNumber = 437; + private const ulong OpenReadOnly = 0; + private const ulong OpenCloseOnExec = 0x0008_0000; + private const ulong OpenNoFollow = 0x0002_0000; + private const ulong OpenNonBlocking = 0x0000_0800; + private const ulong OpenNoControllingTerminal = 0x0000_0100; + private const ulong OpenDirectory = 0x0001_0000; + private const ulong ResolveNoMagicLinks = 0x02; + private const ulong ResolveNoSymlinks = 0x04; + private const ulong ResolveBeneath = 0x08; + private const int AtEmptyPath = 0x1000; + private const uint StatxBasicStats = 0x07ff; + private const uint StatxRequiredMask = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9); + private const ushort FileTypeMask = 0xf000; + private const ushort RegularFileType = 0x8000; + private const ushort DirectoryFileType = 0x4000; + private const int MaximumFiles = EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedFileCount; + private const long MaximumTotalBytes = EvidenceNoFollowArtifactExtractionLimits.MaximumAllowedTotalBytes; + private const int StreamBufferSize = 81_920; + + /// + public async Task VerifyArtifactsAsync( + string trustedArtifactHandoffRootPath, + EvidencePlan verifiedPlan, + EvidenceManifest candidateManifest, + CancellationToken cancellationToken = default) + { + ArgumentException.ThrowIfNullOrWhiteSpace(trustedArtifactHandoffRootPath); + ArgumentNullException.ThrowIfNull(verifiedPlan); + ArgumentNullException.ThrowIfNull(candidateManifest); + cancellationToken.ThrowIfCancellationRequested(); + + if (!OperatingSystem.IsLinux() || RuntimeInformation.ProcessArchitecture is not (Architecture.X64 or Architecture.Arm64)) + { + return false; + } + + try + { + using var rootHandle = OpenTrustedRoot(trustedArtifactHandoffRootPath); + var rootSnapshot = ReadSnapshot(rootHandle); + if ((rootSnapshot.Mode & FileTypeMask) != DirectoryFileType) + { + return false; + } + + var producerResults = candidateManifest.ProducerResults + .GroupBy(static result => result.ProducerId, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.Ordinal); + if (producerResults.Count != candidateManifest.ProducerResults.Count) + { + return false; + } + + var verifiedFiles = 0; + long totalBytes = 0; + var identities = new HashSet(); + foreach (var producer in verifiedPlan.Profile.Producers) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!producerResults.TryGetValue(producer.Id, out var result) + || !EvidenceArtifactValidation.AreValid(producer, result.Artifacts)) + { + return false; + } + + foreach (var artifact in result.Artifacts ?? []) + { + cancellationToken.ThrowIfCancellationRequested(); + if (++verifiedFiles > MaximumFiles + || !TryGetDeclaredSlot(producer, artifact, out var slot) + || !TryGetCanonicalArtifactPath(producer.Id, artifact.RelativePath, out var relativePath)) + { + return false; + } + + using var fileHandle = OpenRelative(rootHandle, relativePath); + var before = ReadSnapshot(fileHandle); + if ((before.Mode & FileTypeMask) != RegularFileType + || before.LinkCount != 1 + || before.Size > long.MaxValue + || (long)before.Size != artifact.LengthBytes + || artifact.LengthBytes > slot.MaximumBytes + || !identities.Add(before.Identity) + || artifact.LengthBytes > MaximumTotalBytes - totalBytes) + { + return false; + } + + totalBytes += artifact.LengthBytes; + var actualDigest = await HashExactBytesAsync(fileHandle, artifact.LengthBytes, cancellationToken).ConfigureAwait(false); + var after = ReadSnapshot(fileHandle); + if (!before.Equals(after) + || !string.Equals(actualDigest, artifact.Sha256, StringComparison.Ordinal)) + { + return false; + } + } + } + + return producerResults.Keys.All(producerId => verifiedPlan.Profile.Producers.Any(producer => producer.Id == producerId)); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + throw; + } + catch (Exception) + { + return false; + } + } + + private static bool TryGetDeclaredSlot( + EvidenceProducerDeclaration producer, + EvidenceArtifactResult artifact, + out EvidenceArtifactSlot slot) + { + slot = producer.ArtifactSlots.FirstOrDefault(candidate => candidate.LogicalName == artifact.LogicalName)!; + if (slot is null + || artifact.LengthBytes < 0 + || artifact.LengthBytes > slot.MaximumBytes + || !string.Equals(artifact.MediaType, slot.MediaType, StringComparison.Ordinal)) + { + return false; + } + + try + { + EvidenceArtifactValidation.ValidatePathForSlot(slot, artifact.RelativePath); + return true; + } + catch (ArgumentException) + { + return false; + } + } + + private static bool TryGetCanonicalArtifactPath(string producerId, string relativePath, out string artifactPath) + { + artifactPath = string.Empty; + if (producerId.Length == 0 + || relativePath.Length == 0 + || producerId.Contains('\\') + || relativePath.Contains('\\') + || producerId.Any(char.IsControl) + || relativePath.Any(char.IsControl)) + { + return false; + } + + try + { + artifactPath = $"{producerId}/{relativePath}"; + var normalized = EvidenceArtifactValidation.NormalizeRelativePath(artifactPath); + return string.Equals(normalized, artifactPath, StringComparison.Ordinal) + && System.Text.Encoding.UTF8.GetByteCount(artifactPath) <= EvidenceGitChangeCapture.MaximumPathBytes; + } + catch (ArgumentException) + { + return false; + } + } + + private static async Task HashExactBytesAsync( + SafeFileHandle fileHandle, + long expectedLength, + CancellationToken cancellationToken) + { + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + var buffer = new byte[StreamBufferSize]; + long total = 0; + while (true) + { + var read = await RandomAccess.ReadAsync(fileHandle, buffer.AsMemory(), total, cancellationToken).ConfigureAwait(false); + if (read == 0) + { + break; + } + + if (read > expectedLength - total) + { + throw new InvalidDataException("Artifact bytes exceed the declared length."); + } + + total += read; + hash.AppendData(buffer, 0, read); + } + + if (total != expectedLength) + { + throw new InvalidDataException("Artifact bytes do not match the declared length."); + } + + return Convert.ToHexString(hash.GetHashAndReset()).ToLowerInvariant(); + } + + private static SafeFileHandle OpenTrustedRoot(string rootPath) + { + var fullPath = Path.GetFullPath(rootPath); + if (!Path.IsPathFullyQualified(fullPath) || !fullPath.StartsWith(Path.DirectorySeparatorChar)) + { + throw new ArgumentException("The artifact handoff root must be an absolute Linux path.", nameof(rootPath)); + } + + var anchorDescriptor = OpenDirectoryPath("/"); + using var anchor = new SafeFileHandle(new IntPtr(anchorDescriptor), ownsHandle: true); + var relativeRoot = fullPath[1..]; + if (relativeRoot.Length == 0) + { + return OpenDirectoryPathHandle("/"); + } + + var how = new LinuxOpenHow + { + Flags = OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenNonBlocking | OpenNoControllingTerminal | OpenDirectory, + Resolve = ResolveBeneath | ResolveNoSymlinks | ResolveNoMagicLinks, + }; + return new SafeFileHandle(new IntPtr(InvokeOpenAt2(anchor.DangerousGetHandle().ToInt32(), relativeRoot, ref how)), ownsHandle: true); + } + + private static SafeFileHandle OpenRelative(SafeFileHandle rootHandle, string relativePath) + { + var how = new LinuxOpenHow + { + Flags = OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenNonBlocking | OpenNoControllingTerminal, + Resolve = ResolveBeneath | ResolveNoSymlinks | ResolveNoMagicLinks, + }; + return new SafeFileHandle(new IntPtr(InvokeOpenAt2(rootHandle.DangerousGetHandle().ToInt32(), relativePath, ref how)), ownsHandle: true); + } + + private static int OpenDirectoryPath(string path) + { + var descriptor = OpenDirectoryNative(path, OpenReadOnly | OpenCloseOnExec | OpenNoFollow | OpenDirectory); + if (descriptor < 0) + { + throw new IOException("The trusted artifact root could not be opened."); + } + + return descriptor; + } + + private static SafeFileHandle OpenDirectoryPathHandle(string path) => + new(new IntPtr(OpenDirectoryPath(path)), ownsHandle: true); + + private static int InvokeOpenAt2(int rootDescriptor, string relativePath, ref LinuxOpenHow how) + { + var pathPointer = Marshal.StringToCoTaskMemUTF8(relativePath); + try + { + var result = Syscall(OpenAt2SyscallNumber, rootDescriptor, pathPointer, ref how, (nuint)Marshal.SizeOf()); + if (result >= 0 && result <= int.MaxValue) + { + return (int)result; + } + + throw new IOException("Linux refused the no-follow artifact path."); + } + finally + { + Marshal.FreeCoTaskMem(pathPointer); + } + } + + private static FileSnapshot ReadSnapshot(SafeFileHandle handle) + { + if (Statx(handle.DangerousGetHandle().ToInt32(), string.Empty, AtEmptyPath, StatxBasicStats, out var statx) != 0 + || (statx.Mask & StatxRequiredMask) != StatxRequiredMask) + { + throw new IOException("Linux could not inspect the opened artifact safely."); + } + + return new FileSnapshot( + statx.DeviceMajor, + statx.DeviceMinor, + statx.Inode, + statx.Mode, + statx.LinkCount, + statx.Size, + statx.ModifyTime.Seconds, + statx.ModifyTime.Nanoseconds, + statx.ChangeTime.Seconds, + statx.ChangeTime.Nanoseconds); + } + + private static int OpenDirectoryNative(string path, ulong flags) => OpenNative(path, checked((int)flags)); + + [DllImport("libc", EntryPoint = "open", SetLastError = true)] + private static extern int OpenNative([MarshalAs(UnmanagedType.LPUTF8Str)] string path, int flags); + + [DllImport("libc", EntryPoint = "syscall", SetLastError = true)] + private static extern long Syscall(long number, int directoryDescriptor, IntPtr path, ref LinuxOpenHow how, nuint size); + + [DllImport("libc", EntryPoint = "statx", SetLastError = true)] + private static extern int Statx( + int directoryDescriptor, + [MarshalAs(UnmanagedType.LPUTF8Str)] string path, + int flags, + uint mask, + out LinuxStatx statx); + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxOpenHow + { + public ulong Flags; + public ulong Mode; + public ulong Resolve; + } + + [StructLayout(LayoutKind.Sequential)] + private struct LinuxStatxTimestamp + { + public long Seconds; + public uint Nanoseconds; + private int _reserved; + } + + [StructLayout(LayoutKind.Sequential, Size = 256)] + private struct LinuxStatx + { + public uint Mask; + private uint _blockSize; + private ulong _attributes; + public uint LinkCount; + private uint _userId; + private uint _groupId; + public ushort Mode; + private ushort _spare0; + public ulong Inode; + public ulong Size; + private ulong _blocks; + private ulong _attributesMask; + private LinuxStatxTimestamp _accessTime; + private LinuxStatxTimestamp _birthTime; + public LinuxStatxTimestamp ChangeTime; + public LinuxStatxTimestamp ModifyTime; + private uint _rdevMajor; + private uint _rdevMinor; + public uint DeviceMajor; + public uint DeviceMinor; + private ulong _mountId; + private uint _dioMemoryAlignment; + private uint _dioOffsetAlignment; + private ulong _spare1; + private ulong _spare2; + private ulong _spare3; + private ulong _spare4; + private ulong _spare5; + private ulong _spare6; + private ulong _spare7; + private ulong _spare8; + private ulong _spare9; + private ulong _spare10; + private ulong _spare11; + private ulong _spare12; + } + + private readonly record struct FileIdentity(uint DeviceMajor, uint DeviceMinor, ulong Inode); + + private readonly record struct FileSnapshot( + uint DeviceMajor, + uint DeviceMinor, + ulong Inode, + ushort Mode, + uint LinkCount, + ulong Size, + long ModifySeconds, + uint ModifyNanoseconds, + long ChangeSeconds, + uint ChangeNanoseconds) + { + public FileIdentity Identity => new(DeviceMajor, DeviceMinor, Inode); + } +} + +/// +/// Returns a bounded PR-gate result without including untrusted manifest or provider diagnostics. +/// +/// Whether the current PR may consume the evidence as a passing gate. +/// Stable diagnostic code. +/// Fixed, secret-safe diagnostic text. +/// Bounded summary after independent plan verification; absent on pre-plan failures. +public sealed record EvidencePullRequestGateVerificationResult( + bool IsEligible, + string Code, + string Diagnostic, + EvidencePullRequestGateSummary? Summary = null); + +/// +/// Independently verifies revision-bound PR evidence at the trusted controller boundary. +/// +/// +/// The policy and Git object store are trusted inputs supplied separately from the untrusted plan +/// and manifest. The verifier recreates the v2 plan from exact Git objects, checks manifest +/// self-consistency and every selected obligation, then reads authoritative PR and job state just +/// before returning. It never uses the plan's policy snapshot or revision values as authority. +/// +public static class EvidencePullRequestGateVerifier +{ + /// Maximum canonical plan or manifest size accepted by this verifier. + public const int MaximumContractBytes = 4 * 1024 * 1024; + + /// Maximum aggregate UTF-16 text units traversed in an input contract. + public const int MaximumContractTextUnits = 1 * 1024 * 1024; + + /// Maximum time allowed for the final authoritative provider lookup. + public const int MaximumAuthorityReadSeconds = 10; + + /// Maximum time allowed for trusted no-follow artifact byte verification. + public const int MaximumArtifactVerificationSeconds = 120; + + /// Maximum number of identifiers or rationale entries returned in a rendering summary. + public const int MaximumSummaryItems = 64; + + private static readonly EvidencePullRequestGateVerificationResult InvalidIdentity = + Failure("ASEVG001", "The trusted controller identity is invalid."); + private static readonly EvidencePullRequestGateVerificationResult InvalidPlan = + Failure("ASEVG002", "The supplied plan is missing, oversized, or is not revision-bound v2 evidence."); + private static readonly EvidencePullRequestGateVerificationResult PlanMismatch = + Failure("ASEVG003", "The plan does not match the trusted policy and exact Git change."); + private static readonly EvidencePullRequestGateVerificationResult InvalidManifest = + Failure("ASEVG004", "The manifest is invalid, incomplete, or does not close every selected obligation and cleanup requirement."); + private static readonly EvidencePullRequestGateVerificationResult NotGateEligible = + Failure("ASEVG005", "The evidence claim is observational, out of scope, or not eligible for a pull-request gate."); + private static readonly EvidencePullRequestGateVerificationResult AuthorityUnavailable = + Failure("ASEVG006", "Fresh pull-request or subject-job authority could not be verified."); + private static readonly EvidencePullRequestGateVerificationResult AuthorityMismatch = + Failure("ASEVG007", "The current pull request or subject-job provenance does not match this evidence run."); + private static readonly EvidencePullRequestGateVerificationResult Cancelled = + Failure("ASEVG008", "Pull-request evidence verification was cancelled."); + private static readonly EvidencePullRequestGateVerificationResult ArtifactVerifierUnavailable = + Failure("ASEVG009", "Trusted artifact byte verification is unavailable for this nonempty evidence profile."); + private static readonly EvidencePullRequestGateVerificationResult ArtifactVerificationFailed = + Failure("ASEVG010", "One or more extracted evidence artifacts could not be verified from bytes."); + private static readonly EvidencePullRequestGateVerificationResult Eligible = + new(true, "ASEVG000", "The current pull request has complete, revision-bound, gate-eligible evidence."); + + /// + /// Verifies untrusted plan and manifest values against controller-owned policy, Git objects, + /// and a final authoritative observation of the pull request and subject job. + /// + /// Trusted evidence planner. + /// Policy loaded from the protected base revision. + /// Trusted object store containing the exact PR commits. + /// PR, workflow run, and subject-job identity captured by the controller. + /// Provider for fresh current PR revisions and job provenance. + /// Trusted extracted-artifact root, or only for an empty profile. + /// Trusted no-follow artifact verifier; required for nonempty profiles. + /// Plan received through the subject-job handoff. + /// Manifest received through the subject-job handoff. + /// Cancellation for Git and authority operations. + /// A bounded result with fixed diagnostics and no raw untrusted output. + public static async Task VerifyAsync( + EvidencePlanner planner, + EvidencePolicy trustedBaseOwnedPolicy, + string trustedGitObjectStorePath, + EvidencePullRequestGateExpectedIdentity expectedIdentity, + IEvidencePullRequestGateAuthorityProvider authorityProvider, + string? trustedArtifactHandoffRootPath, + IEvidencePullRequestGateArtifactVerifier? artifactVerifier, + EvidencePlan untrustedPlan, + EvidenceManifest untrustedManifest, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(planner); + ArgumentNullException.ThrowIfNull(trustedBaseOwnedPolicy); + ArgumentException.ThrowIfNullOrWhiteSpace(trustedGitObjectStorePath); + ArgumentNullException.ThrowIfNull(expectedIdentity); + ArgumentNullException.ThrowIfNull(authorityProvider); + + if (!HasValidExpectedIdentity(expectedIdentity)) + { + return InvalidIdentity; + } + + try + { + if (untrustedPlan is null + || untrustedManifest is null + || !string.Equals(untrustedPlan.ContractVersion, "2.0", StringComparison.Ordinal) + || !HasValidRevision(untrustedPlan.BaseRevision) + || !HasValidRevision(untrustedPlan.HeadRevision) + || untrustedPlan.BaseRevision!.Length != untrustedPlan.HeadRevision!.Length + || !IsBoundedPlan(untrustedPlan) + || !IsBoundedManifest(untrustedManifest)) + { + return InvalidPlan; + } + } + catch (Exception) + { + return InvalidPlan; + } + + if (!Equals(untrustedPlan.PullRequestRunIdentity, expectedIdentity.RunIdentity)) + { + return AuthorityMismatch; + } + + if (!Equals(untrustedManifest.PullRequestRunIdentity, expectedIdentity.RunIdentity)) + { + return InvalidManifest; + } + + try + { + await EvidenceRevisionPlanBuilder.VerifyAsync( + planner, + trustedBaseOwnedPolicy, + trustedGitObjectStorePath, + untrustedPlan, + cancellationToken, + expectedIdentity.RunIdentity).ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return Cancelled; + } + catch (Exception) + { + return PlanMismatch; + } + + bool manifestIsConsistent; + try + { + manifestIsConsistent = EvidenceManifestBuilder.Verify(untrustedPlan, untrustedManifest); + } + catch (Exception) + { + return InvalidManifest; + } + + if (!manifestIsConsistent) + { + return WithSummary(InvalidManifest, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, false, false); + } + + if (untrustedManifest.ClaimKind == EvidenceClaimKind.ObservationOnly) + { + return WithSummary(NotGateEligible, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + var hasEmptyProfile = IsEmptyProfile(untrustedPlan.Profile); + var artifactsVerified = hasEmptyProfile; + if (!hasEmptyProfile) + { + if (string.IsNullOrWhiteSpace(trustedArtifactHandoffRootPath)) + { + return WithSummary(ArtifactVerifierUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + if (artifactVerifier is null) + { + return WithSummary(ArtifactVerifierUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + using var artifactDeadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + artifactDeadline.CancelAfter(TimeSpan.FromSeconds(MaximumArtifactVerificationSeconds)); + try + { + artifactsVerified = await artifactVerifier.VerifyArtifactsAsync( + trustedArtifactHandoffRootPath, + untrustedPlan, + untrustedManifest, + artifactDeadline.Token) + .WaitAsync(TimeSpan.FromSeconds(MaximumArtifactVerificationSeconds), cancellationToken) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return WithSummary(Cancelled, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + catch (Exception) + { + return WithSummary(ArtifactVerificationFailed, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + + if (!artifactsVerified) + { + return WithSummary(ArtifactVerificationFailed, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, false); + } + } + + if (!HasCompleteGateEvidence(untrustedPlan, untrustedManifest)) + { + return WithSummary(InvalidManifest, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, artifactsVerified); + } + + EvidencePullRequestGateAuthoritySnapshot? authority; + using (var authorityDeadline = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) + { + authorityDeadline.CancelAfter(TimeSpan.FromSeconds(MaximumAuthorityReadSeconds)); + try + { + authority = await authorityProvider.ReadFreshAsync(expectedIdentity, authorityDeadline.Token) + .WaitAsync(TimeSpan.FromSeconds(MaximumAuthorityReadSeconds), cancellationToken) + .ConfigureAwait(false); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + return Cancelled; + } + catch (Exception) + { + return WithSummary(AuthorityUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, artifactsVerified); + } + } + + if (authority is null) + { + return WithSummary(AuthorityUnavailable, untrustedPlan, trustedBaseOwnedPolicy, untrustedManifest, true, artifactsVerified); + } + + return WithSummary( + MatchesCurrentAuthority(expectedIdentity, authority, untrustedPlan, untrustedManifest) ? Eligible : AuthorityMismatch, + untrustedPlan, + trustedBaseOwnedPolicy, + untrustedManifest, + true, + artifactsVerified); + } + + private static EvidencePullRequestGateVerificationResult WithSummary( + EvidencePullRequestGateVerificationResult result, + EvidencePlan verifiedPlan, + EvidencePolicy trustedPolicy, + EvidenceManifest candidateManifest, + bool manifestIsConsistent, + bool artifactsVerified) => + result with + { + Summary = CreateSummary(verifiedPlan, trustedPolicy, candidateManifest, manifestIsConsistent, artifactsVerified), + }; + + private static EvidencePullRequestGateSummary CreateSummary( + EvidencePlan verifiedPlan, + EvidencePolicy trustedPolicy, + EvidenceManifest candidateManifest, + bool manifestIsConsistent, + bool artifactsVerified) + { + var selected = verifiedPlan.Profile.Obligations + .Select(static obligation => obligation.Id) + .Distinct(StringComparer.Ordinal) + .OrderBy(static id => id, StringComparer.Ordinal) + .ToArray(); + var closed = manifestIsConsistent && artifactsVerified + ? verifiedPlan.Profile.Obligations + .Where(obligation => obligation.RequiredProducerIds.All(producerId => + candidateManifest.ProducerResults.Any(result => result.ProducerId == producerId + && result.Outcome == EvidenceProducerOutcome.Passed + && result.SatisfiedAssertionIds.Contains(obligation.RequiredAssertionId, StringComparer.Ordinal)))) + .Select(static obligation => obligation.Id) + .Distinct(StringComparer.Ordinal) + .OrderBy(static id => id, StringComparer.Ordinal) + .ToArray() + : []; + var missing = selected.Except(closed, StringComparer.Ordinal).OrderBy(static id => id, StringComparer.Ordinal).ToArray(); + + var matchedRules = verifiedPlan.MatchedRuleIds + .Distinct(StringComparer.Ordinal) + .OrderBy(static id => id, StringComparer.Ordinal) + .Select(id => CreateRuleSummary(id, trustedPolicy)) + .Where(static rule => rule is not null) + .Select(static rule => rule!) + .ToArray(); + var rationales = verifiedPlan.Profile.Obligations + .OrderBy(static obligation => obligation.Id, StringComparer.Ordinal) + .Select(static obligation => new EvidencePullRequestGateObligationRationale( + obligation.Id, + obligation.RiskClass, + Truncate(obligation.Rationale, 256))) + .ToArray(); + + var fallbackId = $"conservative:{trustedPolicy.ConservativeProfileId}"; + return new EvidencePullRequestGateSummary( + verifiedPlan.Profile.Id, + verifiedPlan.MatchedRuleIds.Contains(fallbackId, StringComparer.Ordinal) ? "conservative-fallback" : "matched-policy-rules", + TakeBounded(matchedRules, out var omittedRules), + TakeBounded(selected, out var omittedSelected), + TakeBounded(closed, out var omittedClosed), + TakeBounded(missing, out var omittedMissing), + TakeBounded(rationales, out var omittedRationales), + verifiedPlan.BaseRevision![..12], + verifiedPlan.HeadRevision![..12], + omittedRules, + omittedSelected, + omittedClosed, + omittedMissing, + omittedRationales, + !IsEmptyProfile(verifiedPlan.Profile)); + } + + private static EvidencePullRequestGateRuleSummary? CreateRuleSummary(string ruleId, EvidencePolicy trustedPolicy) + { + var rule = trustedPolicy.Rules.FirstOrDefault(candidate => string.Equals(candidate.Id, ruleId, StringComparison.Ordinal)); + if (rule is not null) + { + return new EvidencePullRequestGateRuleSummary(rule.Id, Truncate(rule.Pattern, 256), rule.ProfileId); + } + + var fallbackId = $"conservative:{trustedPolicy.ConservativeProfileId}"; + return string.Equals(ruleId, fallbackId, StringComparison.Ordinal) + ? new EvidencePullRequestGateRuleSummary(ruleId, "conservative fallback", trustedPolicy.ConservativeProfileId) + : null; + } + + private static IReadOnlyList TakeBounded(IReadOnlyList values, out int omittedCount) + { + omittedCount = Math.Max(0, values.Count - MaximumSummaryItems); + return Array.AsReadOnly(values.Take(MaximumSummaryItems).ToArray()); + } + + private static string Truncate(string value, int maximumLength) => value.Length <= maximumLength + ? value + : value[..maximumLength]; + + private static bool IsEmptyProfile(EvidenceProfile profile) => + profile.Resources.Count == 0 && profile.Producers.Count == 0 && profile.Obligations.Count == 0; + + private static bool HasCompleteGateEvidence(EvidencePlan plan, EvidenceManifest manifest) + { + if (plan.Profile.Scope != EvidenceProfileScope.Targeted + || manifest.ContractVersion != "2.0" + || manifest.ExecutionVerdict != EvidenceExecutionVerdict.Passed + || manifest.Eligibility != EvidenceClaimEligibility.PullRequestGate + || manifest.EnvelopeStatus is EvidenceEnvelopeStatus.Unavailable or EvidenceEnvelopeStatus.Invalid + || !manifest.Metrics.CleanupCompleted + || manifest.Metrics.PlanningMilliseconds < 0 + || manifest.Metrics.ResourceReadinessMilliseconds < 0 + || manifest.Metrics.ProducerMilliseconds < 0 + || manifest.Metrics.CleanupMilliseconds < 0 + || manifest.Metrics.TotalMilliseconds < 0) + { + return false; + } + + var noEvidenceRequired = plan.Profile.Resources.Count == 0 + && plan.Profile.Producers.Count == 0 + && plan.Profile.Obligations.Count == 0; + if (manifest.EnvelopeStatus != (noEvidenceRequired + ? EvidenceEnvelopeStatus.NotRequired + : EvidenceEnvelopeStatus.ValidatedNotAttested)) + { + return false; + } + + var requiredClaim = noEvidenceRequired ? EvidenceClaimKind.NoEvidenceRequired : EvidenceClaimKind.TargetedComplete; + if (manifest.ClaimKind != requiredClaim) + { + return false; + } + + var expectedObligations = plan.Profile.Obligations + .Select(static obligation => obligation.Id) + .OrderBy(static id => id, StringComparer.Ordinal) + .ToArray(); + if (!manifest.SelectedObligationIds.SequenceEqual(expectedObligations, StringComparer.Ordinal) + || !manifest.ClosedObligationIds.SequenceEqual(expectedObligations, StringComparer.Ordinal) + || manifest.UnmediatedObligationIds.Count != 0) + { + return false; + } + + var resourceResults = manifest.ResourceResults + .GroupBy(static result => result.ResourceId, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.Ordinal); + if (resourceResults.Count != plan.Profile.Resources.Count + || plan.Profile.Resources.Any(resource => + !resourceResults.TryGetValue(resource.Id, out var result) + || result.Outcome != EvidenceResourceOutcome.Ready + || result.ElapsedMilliseconds < 0)) + { + return false; + } + + var producerResults = manifest.ProducerResults + .GroupBy(static result => result.ProducerId, StringComparer.Ordinal) + .ToDictionary(static group => group.Key, static group => group.First(), StringComparer.Ordinal); + if (producerResults.Count != plan.Profile.Producers.Count + || plan.Profile.Producers.Any(producer => + !producerResults.TryGetValue(producer.Id, out var result) + || result.Outcome != EvidenceProducerOutcome.Passed + || result.ElapsedMilliseconds < 0 + || !EvidenceArtifactValidation.AreValid(producer, result.Artifacts))) + { + return false; + } + + return plan.Profile.Obligations.All(obligation => obligation.RequiredProducerIds.All(producerId => + producerResults.TryGetValue(producerId, out var result) + && result.Outcome == EvidenceProducerOutcome.Passed + && result.SatisfiedAssertionIds.Contains(obligation.RequiredAssertionId, StringComparer.Ordinal))); + } + + private static bool MatchesCurrentAuthority( + EvidencePullRequestGateExpectedIdentity expected, + EvidencePullRequestGateAuthoritySnapshot current, + EvidencePlan plan, + EvidenceManifest manifest) => + current.RunIdentity is not null + && current.RunIdentity.HeadRepositoryId == current.RunIdentity.RepositoryId + && string.Equals(current.Repository, expected.Repository, StringComparison.OrdinalIgnoreCase) + && string.Equals(current.EventName, expected.EventName, StringComparison.Ordinal) + && Equals(current.RunIdentity, expected.RunIdentity) + && Equals(plan.PullRequestRunIdentity, current.RunIdentity) + && Equals(plan.PullRequestRunIdentity, expected.RunIdentity) + && current.BaseRevision == plan.BaseRevision + && current.HeadRevision == plan.HeadRevision + && string.Equals(current.WorkflowId, expected.WorkflowId, StringComparison.Ordinal) + && string.Equals(current.SubjectJobId, expected.SubjectJobId, StringComparison.Ordinal) + && current.SubjectJobHeadRevision == plan.HeadRevision + && (IsEmptyProfile(plan.Profile) || current.SubjectEnvelopeAttested) + && string.Equals(current.SubjectJobConclusion, "success", StringComparison.OrdinalIgnoreCase); + + private static bool HasValidExpectedIdentity(EvidencePullRequestGateExpectedIdentity identity) => + identity.RunIdentity is not null + && identity.RunIdentity.RepositoryId > 0 + && identity.RunIdentity.HeadRepositoryId > 0 + && identity.RunIdentity.PullRequestNumber > 0 + && identity.RunIdentity.WorkflowRunId > 0 + && identity.RunIdentity.WorkflowRunAttempt > 0 + && IsSafeIdentityText(identity.RunIdentity.TargetBranch, 128) + && IsSafeIdentityText(identity.Repository, 255) + && identity.Repository.Count(static character => character == '/') == 1 + && (identity.EventName is "pull_request" or "pull_request_target") + && IsSafeIdentityText(identity.WorkflowId, 256) + && IsSafeIdentityText(identity.SubjectJobId, 128); + + private static bool IsSafeIdentityText(string? value, int maximumLength) => + !string.IsNullOrWhiteSpace(value) + && value.Length <= maximumLength + && !value.Any(char.IsControl); + + private static bool HasValidRevision(string? revision) => + revision is { Length: 40 or 64 } + && revision.All(static character => character is >= '0' and <= '9' or >= 'a' and <= 'f'); + + private static bool IsBoundedPlan(EvidencePlan plan) + { + var budget = new TextBudget(); + return plan.Profile is not null + && plan.PullRequestRunIdentity is not null + && IsBoundedRunIdentity(plan.PullRequestRunIdentity, budget) + && plan.PolicySnapshot is not null + && plan.ChangedPaths is { Count: <= EvidenceGitChangeCapture.MaximumChangedRecords } + && plan.MatchedRuleIds is { Count: <= EvidenceGitChangeCapture.MaximumChangedRecords * 2 } + && IsBoundedPolicy(plan.PolicySnapshot, budget) + && AddText(budget, plan.ContractVersion, plan.PolicyId, plan.PolicyDigest, plan.DiffDigest, plan.PlanDigest, + plan.BaseRevision, plan.HeadRevision, plan.SourceDiffDigest, plan.NameStatusDigest) + && AddMany(budget, plan.MatchedRuleIds, 128) + && plan.ChangedPaths.All(path => path is not null + && AddText(budget, path.Path, path.Kind, path.PreviousPath) + && path.Path.Length <= EvidenceGitChangeCapture.MaximumPathBytes + && (path.PreviousPath is null || path.PreviousPath.Length <= EvidenceGitChangeCapture.MaximumPathBytes)) + && IsBoundedProfile(plan.Profile, budget) + && EvidenceCanonicalJson.Serialize(plan).Length <= MaximumContractBytes; + } + + private static bool IsBoundedManifest(EvidenceManifest manifest) + { + var budget = new TextBudget(); + if (manifest.PullRequestRunIdentity is null + || !IsBoundedRunIdentity(manifest.PullRequestRunIdentity, budget) + || manifest.ResourceResults is not { Count: <= EvidenceProfileLimits.MaximumResources } + || manifest.SelectedObligationIds is not { Count: <= EvidenceProfileLimits.MaximumObligations } + || manifest.ClosedObligationIds is not { Count: <= EvidenceProfileLimits.MaximumObligations } + || manifest.UnmediatedObligationIds is not { Count: <= EvidenceProfileLimits.MaximumObligations } + || manifest.ProducerResults is not { Count: <= EvidenceProfileLimits.MaximumProducers } + || manifest.Metrics is null) + { + return false; + } + + return AddText(budget, manifest.ContractVersion, manifest.PlanDigest, manifest.ManifestDigest, + manifest.BaseRevision, manifest.HeadRevision, manifest.SourceDiffDigest, manifest.NameStatusDigest, + manifest.Metrics.CleanupDiagnostic) + && manifest.ResourceResults.All(result => result is not null + && AddText(budget, result.ResourceId, result.Diagnostic) + && result.Diagnostic is null or { Length: <= 512 }) + && AddMany(budget, manifest.SelectedObligationIds, 128) + && AddMany(budget, manifest.ClosedObligationIds, 128) + && AddMany(budget, manifest.UnmediatedObligationIds, 128) + && manifest.ProducerResults.All(result => result is not null + && AddText(budget, result.ProducerId, result.Diagnostic) + && result.Diagnostic is null or { Length: <= 512 } + && result.SatisfiedAssertionIds is { Count: <= 256 } + && result.Artifacts is { Count: <= 128 } + && AddMany(budget, result.SatisfiedAssertionIds, 128) + && result.Artifacts.All(artifact => artifact is not null + && AddText(budget, artifact.LogicalName, artifact.RelativePath, artifact.MediaType, artifact.Sha256))) + && EvidenceCanonicalJson.Serialize(manifest).Length <= MaximumContractBytes; + } + + private static bool IsBoundedPolicy(EvidencePolicy policy, TextBudget budget) => + policy.Profiles is { Count: > 0 and <= 128 } + && policy.Rules is { Count: <= 10_000 } + && AddText(budget, policy.Id, policy.Version, policy.ConservativeProfileId) + && policy.Profiles.All(profile => profile is not null && IsBoundedProfile(profile, budget)) + && policy.Rules.All(rule => rule is not null && AddText(budget, rule.Id, rule.Pattern, rule.ProfileId)); + + private static bool IsBoundedRunIdentity(EvidencePullRequestRunIdentity identity, TextBudget budget) => + identity.RepositoryId > 0 + && identity.HeadRepositoryId > 0 + && identity.PullRequestNumber > 0 + && identity.WorkflowRunId > 0 + && identity.WorkflowRunAttempt > 0 + && identity.TargetBranch is { Length: > 0 and <= 128 } + && !identity.TargetBranch.Any(char.IsControl) + && budget.TryAdd(identity.TargetBranch); + + private static bool IsBoundedProfile(EvidenceProfile profile, TextBudget budget) => + profile is not null + && profile.Resources is { Count: <= EvidenceProfileLimits.MaximumResources } + && profile.Producers is { Count: <= EvidenceProfileLimits.MaximumProducers } + && profile.Obligations is { Count: <= EvidenceProfileLimits.MaximumObligations } + && AddText(budget, profile.Id) + && profile.Resources.All(resource => resource is not null + && resource.Requires is { Count: <= EvidenceProfileLimits.MaximumResources } + && AddText(budget, resource.Id, resource.Readiness) + && AddMany(budget, resource.Requires, 128)) + && profile.Producers.All(producer => producer is not null + && producer.RequiredResources is { Count: <= EvidenceProfileLimits.MaximumResources } + && producer.AssertionIds is { Count: <= 256 } + && producer.ArtifactSlots is { Count: <= 128 } + && AddText(budget, producer.Id, producer.Kind, producer.Version) + && AddMany(budget, producer.RequiredResources, 128) + && AddMany(budget, producer.AssertionIds, 128) + && producer.ArtifactSlots.All(slot => slot is not null && AddText(budget, slot.LogicalName, slot.RelativeRoot, slot.MediaType))) + && profile.Obligations.All(obligation => obligation is not null + && obligation.RequiredProducerIds is { Count: <= EvidenceProfileLimits.MaximumProducers } + && AddText(budget, obligation.Id, obligation.RiskClass, obligation.Rationale, obligation.RequiredAssertionId) + && AddMany(budget, obligation.RequiredProducerIds, 128)); + + private static bool AddMany(TextBudget budget, IEnumerable? values, int maximumItemLength) + { + if (values is null) + { + return false; + } + + foreach (var value in values) + { + if (value is null || value.Length > maximumItemLength || !budget.TryAdd(value)) + { + return false; + } + } + + return true; + } + + private static bool AddText(TextBudget budget, params string?[] values) + { + foreach (var value in values) + { + if (value is not null && (value.Length > EvidenceGitChangeCapture.MaximumPathBytes || !budget.TryAdd(value))) + { + return false; + } + } + + return true; + } + + private static EvidencePullRequestGateVerificationResult Failure(string code, string diagnostic) => + new(false, code, diagnostic); + + private sealed class TextBudget + { + private int _used; + + public bool TryAdd(string value) + { + if (value.Length > MaximumContractTextUnits - _used) + { + return false; + } + + _used += value.Length; + return true; + } + } +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceRevisionPlanBuilder.cs b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceRevisionPlanBuilder.cs new file mode 100644 index 000000000..730763fb1 --- /dev/null +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/EvidenceRevisionPlanBuilder.cs @@ -0,0 +1,120 @@ +using ForgeTrust.AppSurface.Evidence.Contracts; + +namespace ForgeTrust.AppSurface.Evidence.Planner; + +/// +/// Binds an independently captured Git change to the closed pull-request policy selection. +/// +/// +/// A v2 plan proves internal consistency only. A gate must supply its own trusted policy and Git +/// object store to , and must separately check the current PR identity +/// and the subject job's provenance immediately before issuing a verdict. +/// +public static class EvidenceRevisionPlanBuilder +{ + /// + /// Resolves a v2 plan from exact, full commit IDs and fixed-options Git diff/status bytes. + /// + /// The policy resolver. + /// Trusted, base-owned pull-request policy. + /// Captured exact Git change. + /// Optional trusted controller-captured PR/run identity; local rehearsal omits it. + /// A canonical digest-bound v2 plan. + public static EvidencePlan ResolveForPullRequest( + EvidencePlanner planner, + EvidencePolicy policy, + EvidenceGitChangeSnapshot snapshot, + EvidencePullRequestRunIdentity? runIdentity = null) + { + ArgumentNullException.ThrowIfNull(planner); + ArgumentNullException.ThrowIfNull(policy); + ArgumentNullException.ThrowIfNull(snapshot); + if (runIdentity is not null && (runIdentity.RepositoryId <= 0 + || runIdentity.HeadRepositoryId <= 0 + || runIdentity.PullRequestNumber <= 0 + || string.IsNullOrWhiteSpace(runIdentity.TargetBranch) + || runIdentity.TargetBranch.Length > 128 + || runIdentity.WorkflowRunId <= 0 + || runIdentity.WorkflowRunAttempt <= 0)) + { + throw new EvidencePlanningException( + "ASEVD140", + "The controller PR/run identity is incomplete or malformed.", + "Capture numeric repository, PR, run, and attempt IDs and a bounded target branch from the trusted event."); + } + + var local = planner.ResolveForGate(policy, snapshot.ChangedPaths); + if (local.Profile.Scope == EvidenceProfileScope.Release) + { + throw new EvidencePlanningException( + "ASEVD138", + "A pull-request event selected a release-only evidence profile.", + "Use a targeted profile for PR changes; run release evidence only from a protected release event."); + } + + var draft = local with + { + ContractVersion = "2.0", + BaseRevision = snapshot.BaseRevision, + HeadRevision = snapshot.HeadRevision, + SourceDiffDigest = snapshot.SourceDiffDigest, + NameStatusDigest = snapshot.NameStatusDigest, + PullRequestRunIdentity = runIdentity, + PlanDigest = string.Empty, + }; + return draft with { PlanDigest = EvidenceDigest.CanonicalSha256(draft) }; + } + + /// + /// Recreates a v2 pull-request plan using a trusted policy and exact Git objects, rejecting + /// a modified policy, revision pair, diff, status inventory, profile, or canonical plan digest. + /// This method does not authenticate the external PR event or job that supplied the plan. + /// + /// The policy resolver. + /// Policy read from the trusted base revision. + /// Trusted Git object store containing both commits. + /// Untrusted plan to compare with the independently resolved one. + /// Cancellation for bounded Git operations. + /// Separately trusted PR/run identity for a CI gate; omit only for local rehearsal. + /// A task that completes only when the plan matches the trusted inputs. + public static async Task VerifyAsync( + EvidencePlanner planner, + EvidencePolicy trustedPolicy, + string repositoryPath, + EvidencePlan plan, + CancellationToken cancellationToken = default, + EvidencePullRequestRunIdentity? expectedRunIdentity = null) + { + ArgumentNullException.ThrowIfNull(planner); + ArgumentNullException.ThrowIfNull(trustedPolicy); + ArgumentNullException.ThrowIfNull(plan); + if (!string.Equals(plan.ContractVersion, "2.0", StringComparison.Ordinal) + || plan.BaseRevision is null + || plan.HeadRevision is null) + { + throw new EvidencePlanningException( + "ASEVD139", + "The supplied plan is not revision-bound v2 evidence.", + "Regenerate the plan from complete base/head commit IDs and a trusted base-owned policy."); + } + + if (expectedRunIdentity is not null && !Equals(plan.PullRequestRunIdentity, expectedRunIdentity)) + { + throw new EvidencePlanningException( + "ASEVD139", + "The plan PR/run identity differs from the trusted controller identity.", + "Discard the supplied plan and capture a new one for the authoritative PR, run, and attempt."); + } + + var snapshot = await EvidenceGitChangeCapture.CaptureAsync( + repositoryPath, plan.BaseRevision, plan.HeadRevision, cancellationToken).ConfigureAwait(false); + var expected = ResolveForPullRequest(planner, trustedPolicy, snapshot, expectedRunIdentity ?? plan.PullRequestRunIdentity); + if (!EvidenceCanonicalJson.Serialize(expected).AsSpan().SequenceEqual(EvidenceCanonicalJson.Serialize(plan))) + { + throw new EvidencePlanningException( + "ASEVD139", + "The revision-bound plan does not match the trusted policy or exact Git change.", + "Discard the supplied plan and rerun planning from the base-owned policy and fetched commit objects."); + } + } +} diff --git a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md index 1d11cd206..8b288c489 100644 --- a/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md +++ b/Evidence/ForgeTrust.AppSurface.Evidence.Planner/README.md @@ -2,7 +2,7 @@ `ForgeTrust.AppSurface.Evidence.Planner` turns an explicit diff and a checked-in `EvidencePolicy` into one deterministic `EvidencePlan`. It is the boundary that makes a coverage or E2E gate explainable before work begins. -Begin with the [EvidenceHost guide](https://github.com/forge-trust/AppSurface/blob/main/start-here/evidencehost.md). This package owns planning only: it does not invoke Git, start Aspire, run tests, create containers, or decide that missing evidence is acceptable. +Begin with the [EvidenceHost guide](https://github.com/forge-trust/AppSurface/blob/main/start-here/evidencehost.md). The policy resolver owns planning only: it does not invoke Git, start Aspire, run tests, create containers, or decide that missing evidence is acceptable. The separate `EvidenceGitChangeCapture` API does invoke Git to capture and verify exact commit-pair changes. ## Release Guidance @@ -24,6 +24,55 @@ var plan = planner.Resolve(policy, [new NormalizedDiffPath("src/Orders/SubmitOrd `Resolve` normalizes and sorts paths, applies the most-specific matching rules, and falls back to `ConservativeProfileId` for a path that has no rule. If equally specific rules choose different profiles, it throws `EvidencePlanningException` instead of silently taking a lower-risk route. `EvidenceUnifiedDiffReader.Read(...)` accepts a CI-provided Git-formatted unified diff when callers do not want to depend on a local Git checkout. Hunked diffs must include `diff --git` file headers; use explicit paths when only a non-Git diff is available. +## Pull-request gate planning + +Use `ResolveForGate` to build a plan for a PR gate. It opts into stricter validation before selecting paths: + +```csharp +var plan = new EvidencePlanner().ResolveForGate(policy, changedPaths); +``` + +In addition to the ordinary v1 policy checks, the gate path checks that the conservative profile includes every requirement from every rule-selected targeted profile that could be combined in one diff. It preserves resource declarations and producer resource dependencies; producer kind, version, assertions, and coverage requirements; artifact-slot roots, media types, required status, and byte bounds; and obligation identity, risk class, rationale, required assertion, and required producers. The conservative profile may add resources, producers, assertions, artifact slots, and obligations. Resource readiness modes must match, and resource or producer deadlines may be shortened. Coverage thresholds may be strengthened. A required artifact slot cannot become optional, and its byte limit may stay the same or become smaller. + +An empty targeted profile is valid for an explicit docs-only rule: it contributes no requirements to the superset check and can still resolve to `NoEvidenceRequired`. PR rules and their conservative profile must use `Targeted` scope. Release profiles require separate validation in their trusted release context. + +`ValidateGatePolicy(policy)` exposes the same check for policy preflight. `Resolve` and `ValidatePolicy` deliberately retain local v1 behavior and do not perform cross-profile validation. Local planning therefore remains compatible, but its result alone does not prove that a policy is safe for a PR gate. Gate callers should use `ResolveForGate` with the same base-owned policy snapshot used for the run. A failed superset check reports `ASEVD129` before a plan is produced. + +## Revision-bound Git change capture + +For a revision-bound gate, [EvidenceGitChangeCapture](EvidenceGitChangeCapture.cs) captures the source diff and the path-selection stream from an explicit commit pair: + +```csharp +var snapshot = await EvidenceGitChangeCapture.CaptureAsync( + trustedObjectStorePath, + baseCommitId, + headCommitId, + cancellationToken); +var plan = EvidenceRevisionPlanBuilder.ResolveForPullRequest(new EvidencePlanner(), policy, snapshot); +// Run the evidence producers for `plan` here. +await EvidenceRevisionPlanBuilder.VerifyAsync( + new EvidencePlanner(), trustedBaseOwnedPolicy, trustedObjectStorePath, plan, cancellationToken); +// Separately recheck the PR's live base/head before issuing the verdict. +``` + +`baseCommitId` and `headCommitId` must be complete lower-case commit object IDs, either 40 or 64 hexadecimal characters, in the same object format. They must resolve to commit objects in a trusted bare or object-only Git checkout. The capture implementation invokes Git with fixed diff options and neutralized ambient Git configuration; the gate runner remains responsible for supplying that trusted object store, pinning the Git version, fetching the exact commits, and checking its trust boundary. + +The snapshot keeps two representations for different purposes. `SourceDiff` contains the exact bounded `git diff --binary` bytes and `SourceDiffDigest` binds those bytes. `NameStatus` contains the separate `git diff --name-status -z` byte stream; its NUL-delimited records are parsed into `ChangedPaths`, including both old and new paths for renames and copies. Policy selection uses those parsed status paths, so binary, mode, symlink, and submodule changes are not lost just because they have no text hunk. `NameStatusDigest` binds the exact status bytes. Do not parse paths from source-diff text as a substitute for the status stream. + +The initial gate bounds are a 20 MiB source diff, 10,000 changed records, 4 KiB of UTF-8 bytes per path, and 120 seconds for the complete capture operation (`MaximumCaptureSeconds`). A separate bounded read protects the status stream before parsing. Exceeding a bound or receiving malformed, truncated, unsafe, or invalid-UTF-8 status data fails closed; callers must not fall back to an empty or text-hunk-only path list. + +`EvidenceRevisionPlanBuilder.ResolveForPullRequest` emits contract version `2.0` and binds both revisions plus source/status digests to the normalized path selection and policy. Its `VerifyAsync` independently regenerates both Git representations and resolves the plan from a separately trusted policy. It rejects a substituted policy or plan but does not query GitHub or prove current-base/head freshness. The trusted controller must independently recheck the remote PR's current base and head immediately before issuing a gate verdict, as described in the [issue #777 gate design](../../docs/designs/issue-777-policy-driven-ci-evidence-gate.md). + +## Trusted PR verdict boundary + +For a nonempty profile, the manifest must declare `ValidatedNotAttested`, and the fresh authority snapshot must separately set `SubjectEnvelopeAttested` only after trusted isolation inspection. The manifest's enum is a structural claim, not proof of the runner envelope; a missing independent attestation returns `ASEVG007`. An empty profile instead requires `NotRequired`. + +[`EvidencePullRequestGateVerifier.VerifyAsync`](EvidencePullRequestGateVerifier.cs) is the final library seam for a PR verdict. Supply the base-owned policy and trusted Git object store separately from the candidate v2 plan and manifest. `EvidencePullRequestGateExpectedIdentity` must come from controller-owned workflow context: repository, event, workflow and subject-job IDs, plus numeric repository, head-repository, PR, run and attempt IDs and target branch in `EvidencePullRequestRunIdentity`. Do not copy expected identity from the plan itself. The verifier recreates the plan from Git, checks the manifest and every selected obligation, then calls an `IEvidencePullRequestGateAuthorityProvider` to reread current PR base/head and subject-job provenance immediately before it returns. A missing, stale, fork, wrong-job, or observational result is ineligible. + +For a nonempty profile, also pass a controller-owned extracted-artifact handoff root and an `IEvidencePullRequestGateArtifactVerifier`. The supplied [`EvidencePullRequestGateNoFollowArtifactVerifier`](EvidencePullRequestGateVerifier.cs) requires Linux x64 or arm64 with `openat2` and `statx`; it opens each declared file beneath that root without following links and verifies type, single-link identity, length, slot, and SHA-256 from the bytes read. It rejects missing, moved, duplicate or forged artifacts. A missing verifier or root returns `ASEVG009`; a byte mismatch returns `ASEVG010`. An explicit empty targeted profile has no artifact handoff to verify and may yield `NoEvidenceRequired` after the same revision and authority checks. The host's own success is not a substitute for this final verification. + +`EvidencePullRequestGateVerificationResult` exposes a fixed diagnostic code and bounded `Summary` for terminal, GitHub summary, and machine rendering. The summary carries profile/rule rationale, short revisions, and selected, closed, and missing obligation IDs; it does not carry producer logs or arbitrary artifact contents. A calling CI command may issue a passing check only for `IsEligible == true` (`ASEVG000`). `ASEVG001`–`ASEVG008` cover invalid trusted identity, v2 plan or manifest mismatch, out-of-scope claim, unavailable or mismatched fresh authority, and cancellation. A verifier implementation alone does not provide a GitHub API authority provider or isolate the subject job; those remain requirements of the [AppSurface rollout](../../docs/evidence-gate-rollout.md). + ## Policy design Keep the policy small and explicit: @@ -45,5 +94,10 @@ The planner does not classify C# semantics or infer that a getter, constructor, | `ASEVD121` | An identifier is empty or exceeds 128 characters. | Use a stable identifier up to 128 characters. | | `ASEVD111`, `ASEVD124` | A producer or resource requires an undeclared resource. | Declare every required resource in the same profile. | | `ASEVD128` | A hunked unified diff does not include Git file headers. | Supply a Git-formatted diff or explicit changed paths. | +| `ASEVD129` | A PR gate's conservative profile does not preserve a targeted profile requirement. | Add the required declaration to the conservative profile or use an explicit combined profile. | +| `ASEVD130`–`ASEVD136` | Exact Git revisions, object-store reads, bounded status parsing, or capture verification failed. | Fetch full commit objects into the trusted object store and recapture with the pinned Git runner; do not downgrade to path-only selection. | +| `ASEVD137` | Exact Git change capture exceeded its 120-second deadline. | Retry in the pinned runner or reduce the change before a reviewed deadline increase. | +| `ASEVD138` | A pull-request plan selected a release-only profile. | Map PR paths to a targeted profile and reserve release selection for the protected release event. | +| `ASEVD139` | A v2 plan did not match the trusted policy and exact Git commit pair. | Discard it and replan from the trusted base-owned policy and fetched objects. | Read next: [contracts](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Contracts/README.md), [CLI workflow](https://github.com/forge-trust/AppSurface/blob/main/Evidence/ForgeTrust.AppSurface.Evidence.Cli/README.md), and the [policy cookbook](https://github.com/forge-trust/AppSurface/blob/main/guides/evidencehost-cookbook.md). diff --git a/ForgeTrust.AppSurface.slnx b/ForgeTrust.AppSurface.slnx index cad4fc4aa..9656544f5 100644 --- a/ForgeTrust.AppSurface.slnx +++ b/ForgeTrust.AppSurface.slnx @@ -151,6 +151,8 @@ + + diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs b/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs index cc62da48b..3a81cb4d0 100644 --- a/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs +++ b/Web/ForgeTrust.RazorWire.IntegrationTests/AppSurfaceDocsWayfindingPlaywrightTests.cs @@ -667,7 +667,7 @@ await page.WaitForFunctionAsync( null, new PageWaitForFunctionOptions { Timeout = 15_000 }); - await page.EvaluateAsync(ScrollMainContentToBottomScript); + await ScrollMainContentToBottomAsync(page); var scrollState = await page.EvaluateAsync( """ () => { @@ -720,7 +720,7 @@ await AppSurfaceDocsRouteHelper.GotoFirstAvailableAsync( "() => getComputedStyle(document.getElementById('main-content')).overflowAnchor"); Assert.Equal("none", overflowAnchor); - await page.EvaluateAsync(ScrollMainContentToBottomScript); + await ScrollMainContentToBottomAsync(page); await page.EvaluateAsync( """ () => { @@ -762,7 +762,7 @@ await page.WaitForFunctionAsync( null, new PageWaitForFunctionOptions { Timeout = 15_000 }); - await page.EvaluateAsync(ScrollMainContentToBottomScript); + await ScrollMainContentToBottomAsync(page); var scrollState = await page.EvaluateAsync( """ () => { @@ -1696,6 +1696,20 @@ private static async Task AssertSectionCopyPreservedNavigationAsync(IPage page, await AssertSectionCopyDidNotMutateHistoryAsync(page); } + private static async Task ScrollMainContentToBottomAsync(IPage page) + { + await page.EvaluateAsync(ScrollMainContentToBottomScript); + await page.WaitForFunctionAsync( + """ + () => { + const main = document.getElementById('main-content'); + return main && Math.max(0, main.scrollHeight - main.clientHeight) - main.scrollTop <= 8; + } + """, + null, + new PageWaitForFunctionOptions { Timeout = 15_000 }); + } + private const string ScrollMainContentToBottomScript = """ () => { @@ -1705,7 +1719,8 @@ private static async Task AssertSectionCopyPreservedNavigationAsync(IPage page, } main.dispatchEvent(new WheelEvent('wheel', { bubbles: true, cancelable: true })); - main.scrollTo(0, main.scrollHeight); + // Cancel any in-flight smooth outline navigation before checking the bottom. + main.scrollTo({ top: main.scrollHeight, behavior: 'instant' }); } """; } diff --git a/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-dark-1440x1000.png b/Web/ForgeTrust.RazorWire.IntegrationTests/VisualBaselines/AppSurfaceDocsGraphite/release-preference-dark-1440x1000.png index 57ca8e19713632617d73d0d2aacac0f5c4c1e7f5..444f20a6e468da9a8381043b4ebe276a275db570 100644 GIT binary patch delta 154823 zcmZ6SRa{h2zxQbn1O!Qu?(XjH?rso}?%Yz+-I5a0Lw89xNOyO44Rz)@?|E+CtGS!c zjl7vKGBnxO22;715_2uuiUJzQHnfcBRrlIev?Fi=Dcz2jlM?RK4?1}0LcIuMnB zOQYJA$(*anQlI0_cQJ8&Gc2%~fox${ zuMMv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