From de88d4ba29edb7ab1614d4899f4d157a8de428bb Mon Sep 17 00:00:00 2001 From: kapolos Date: Thu, 3 Dec 2026 21:05:24 +0200 Subject: [PATCH] feat: inspect commit-pinned review evidence against local Git Verify recorded source digests against immutable Git blobs and compare cited source content with a fixed local HEAD revision. Bind inspection to the reviewed repository, distinguish integrity from source changes, and report unavailable evidence explicitly. Keep Git inspection bounded and local-only, reuse shared source eligibility rules, and support human-readable and JSON output. Validate against a genuine hosted Proofline review and cover security, eligibility, resource limits, and failure paths with regression tests. --- README.md | 2 + src/evidence.rs | 152 ++++++++ src/evidence/inspect.rs | 265 ++++++++++++++ src/evidence/render.rs | 153 ++++++++ src/evidence/report.rs | 285 +++++++++++++++ src/evidence/tests.rs | 218 ++++++++++++ src/git.rs | 14 + src/git/inspection.rs | 760 ++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 13 +- src/sarif.rs | 43 +-- src/source_evidence.rs | 59 ++++ tests/evidence.rs | 737 ++++++++++++++++++++++++++++++++++++++ 12 files changed, 2667 insertions(+), 34 deletions(-) create mode 100644 src/evidence.rs create mode 100644 src/evidence/inspect.rs create mode 100644 src/evidence/render.rs create mode 100644 src/evidence/report.rs create mode 100644 src/evidence/tests.rs create mode 100644 src/git/inspection.rs create mode 100644 src/source_evidence.rs create mode 100644 tests/evidence.rs diff --git a/README.md b/README.md index ddb19ee..4c6937e 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,8 @@ Native knowledge, plan, fix and configuration commands send the selected organiz `proofline rerun REVIEW_ID` requests the original immutable subject and waits, while `--no-wait` returns its link. Reruns require `reviews:rerun`. `proofline guidance --repo owner/name` requires `guidance:read`, and `proofline fix-prompt FINDING_ID` requires `findings:read`. History, guidance, and fix prompts print JSON; prompt text remains untrusted. +`proofline evidence inspect REVIEW_ID` inspects commit-pinned primary-repository source evidence from a pull-request review against the local Git checkout (pass `--json` for the typed `proofline.evidence-inspection.v1` projection, or `--remote` / `--source-provider` to select the checkout's remote). It validates the checkout's actual Git remote against the review's recorded repository ID (with no `--repo` override), pins local `HEAD` once, and reports two independent observations per reference: whether the raw immutable Git blob bytes at the reviewed commit match Proofline's recorded `file_sha256` (`matched`, `mismatch`, `not_recorded`, `unavailable`, or `outside_scope`), and whether the cited path's Git blob object identity at local `HEAD` equals or differs from a known regular-file blob at the reviewed commit (`unchanged`, `changed`, `absent`, `unavailable`, or `outside_scope`) without independently reading both blobs' bytes or assuming branch ancestry. Inspection is strictly local-only and diagnostic (exit 0 when a report is produced, exit 1 on usage, authentication, repository-identity, or unsupported-review errors): it ignores replacement objects and uncommitted changes, does not invoke smudge or Git LFS filters (so LFS pointer blobs compare pointer bytes rather than materialized objects), supports ordinary and shallow clones (reporting missing commits or original entries as `unavailable`), and refuses partial or promisor clones where local-only object access cannot be guaranteed across Git versions. It does not verify AI reasoning, reassess findings, or establish whether a finding is resolved. + Repository commands use the checkout’s `origin` by default. Use `--remote NAME` to select another remote or `--repo URL` to supply a clone URL. The CLI sends the host and full project path to Proofline, including subgroup names. The CLI recognizes gitlab.com and otherwise looks for a GitHub repository on the exact remote host, including GitHub Enterprise Server. Use `--source-provider gitlab` for private GitLab hosts or `--source-provider git` for other Git servers. Hooks can read the same choice from `PROOFLINE_SOURCE_PROVIDER`. A connected private Git repository can use `proofline review --source-provider git --range BASE..HEAD` to request a review of two pushed commits. `proofline review --range BASE..HEAD --fail-on serious` exits 3 when a complete review has an unresolved finding at or above the threshold. PR reviews use the server’s effective open-item counts; other reviews count unresolved findings, including those a partial code assessment recorded. Incomplete and unavailable results retain their nonzero exits. `--fail-on` cannot be combined with `--no-wait`. diff --git a/src/evidence.rs b/src/evidence.rs new file mode 100644 index 0000000..c3374d9 --- /dev/null +++ b/src/evidence.rs @@ -0,0 +1,152 @@ +//! Read-only inspection of commit-pinned pull-request source evidence against +//! the local Git checkout. +//! +//! Two independent questions are answered for each eligible primary-repository +//! file reference: +//! 1. Whether the raw immutable Git blob bytes at the reviewed commit match +//! Proofline's recorded `file_sha256`. +//! 2. Whether the cited path's Git blob object identity at a single immutable +//! snapshot of local `HEAD` equals or differs from a known regular-file blob +//! at the reviewed commit (without independently reading both blobs' bytes +//! or assuming branch ancestry). +//! +//! Neither observation establishes AI reasoning correctness, finding validity, +//! or whether a finding has been resolved. + +mod inspect; +mod render; +mod report; + +#[cfg(test)] +mod tests; + +use std::io::Write as _; +use std::path::Path; + +use anyhow::bail; +use clap::{Args, Subcommand}; +use uuid::Uuid; + +use crate::api::Api; +use crate::git::inspection::{self, InspectionLimits}; +use crate::git::{self, GitError}; +use crate::outcome; +use crate::text::one_line; +use crate::{RepositoryRead, SourceProvider, Verdict}; + +use self::report::InspectionReport; + +#[derive(Debug, Subcommand)] +pub(crate) enum EvidenceCommand { + /// Inspect commit-pinned source evidence of a pull-request review against + /// the local Git checkout. + Inspect(InspectArgs), +} + +#[derive(Debug, Args)] +pub(crate) struct InspectArgs { + /// Review ID to inspect. + review_id: Uuid, + /// Print JSON instead of text. + #[arg(long)] + json: bool, + /// Git remote that names this checkout's repository. + #[arg(long, default_value = "origin")] + remote: String, + /// Source provider. Defaults to GitLab on gitlab.com and GitHub on other hosts. + #[arg(long, env = "PROOFLINE_SOURCE_PROVIDER")] + source_provider: Option, +} + +pub(crate) async fn run(api: &Api, args: &InspectArgs) -> anyhow::Result { + let report = inspect_checkout(api, Path::new("."), args, InspectionLimits::default()).await?; + let mut stdout = std::io::stdout().lock(); + if args.json { + writeln!(stdout, "{}", serde_json::to_string_pretty(&report)?)?; + } else { + write!(stdout, "{}", render::render(&report))?; + } + Ok(Verdict::Done) +} + +async fn inspect_checkout( + api: &Api, + dir: &Path, + args: &InspectArgs, + limits: InspectionLimits, +) -> anyhow::Result { + let remote = inspection::remote_repository_in(dir, &args.remote, limits) + .await + .map_err(|error| match error { + GitError::UnknownRemote => anyhow::anyhow!( + "the Git remote {:?} does not name a hosted repository; configure a hosted remote or select one with --remote", + one_line(&args.remote) + ), + other => other.into(), + })?; + let provider = match (args.source_provider, remote.host.as_str()) { + (Some(provider), _) => provider, + (None, "gitlab.com") => SourceProvider::Gitlab, + (None, _) => SourceProvider::Github, + }; + let (local_repo_name, local_repo_id) = api + .resolve_source(provider.as_str(), &remote, RepositoryRead::History) + .await?; + let (_raw, detail) = api.review(args.review_id).await?; + outcome::same_review(&detail, args.review_id)?; + + let Some(review_repo_id) = detail.repository_id else { + bail!( + "review {} records no repository identity; evidence inspection requires a repository-bound review", + detail.id + ); + }; + if review_repo_id != local_repo_id { + let review_repo = detail + .repository_full_name + .as_deref() + .map_or_else(|| review_repo_id.to_string(), one_line); + bail!( + "review {} belongs to repository {} ({review_repo_id}), not the local checkout's repository {} ({local_repo_id})", + detail.id, + review_repo, + one_line(&local_repo_name) + ); + } + if detail.kind != "PULL_REQUEST" { + bail!( + "review {} has kind {}; evidence inspection supports only commit-pinned pull-request reviews", + detail.id, + one_line(&detail.kind) + ); + } + let Some(reviewed_head_sha) = detail + .head_commit_sha + .as_deref() + .and_then(|raw| git::commit_sha(raw).ok()) + else { + bail!( + "review {} does not record a full head commit SHA; evidence inspection requires a commit-pinned pull-request head", + detail.id + ); + }; + + inspection::ensure_no_partial_clone(dir, limits).await?; + let local_head_sha = inspection::head_in(dir, limits).await?; + let repo_name = detail + .repository_full_name + .as_deref() + .filter(|name| !name.trim().is_empty()) + .map_or(local_repo_name, str::to_owned); + + Ok(inspect::inspect_review( + dir, + &detail, + review_repo_id, + repo_name, + reviewed_head_sha, + local_head_sha, + limits, + ) + .await) +} diff --git a/src/evidence/inspect.rs b/src/evidence/inspect.rs new file mode 100644 index 0000000..5b31426 --- /dev/null +++ b/src/evidence/inspect.rs @@ -0,0 +1,265 @@ +//! Local Git evidence inspection engine and per-run immutable object cache. + +use std::collections::BTreeMap; +use std::path::Path; + +use uuid::Uuid; + +use crate::git::GitError; +use crate::git::inspection::{self, InspectionLimits, TreeObject}; +use crate::model::{EvidenceRef, Finding, ReviewDetail}; +use crate::outcome; +use crate::source_evidence; + +use super::report::{ + InspectedReference, InspectionReport, InspectionWarning, IntegrityObservation, Lane, + LocalHeadObservation, Reason, SCHEMA, summarize, +}; + +#[derive(Clone, Copy)] +enum LaneRef<'a> { + Code, + Env(&'a str), +} + +impl LaneRef<'_> { + fn to_owned(self) -> Lane { + match self { + Self::Code => Lane::Code, + Self::Env(env) => Lane::Env(env.to_owned()), + } + } +} + +struct AssessmentLane<'a> { + assessment_id: Uuid, + lane: LaneRef<'a>, + findings: &'a [Finding], +} + +const fn git_error_reason(error: &GitError) -> Reason { + match error { + GitError::BlobTooLarge { .. } => Reason::BlobTooLarge, + GitError::TimedOut { .. } => Reason::GitTimeout, + GitError::OutputTooLarge { .. } => Reason::GitOutputLimitExceeded, + _ => Reason::GitError, + } +} + +fn reviewed_blob_oid(object: &Result) -> Result<&str, Reason> { + match object { + Ok(TreeObject::RegularBlob { oid }) => Ok(oid.as_str()), + Ok(TreeObject::Absent) => Err(Reason::ReviewedPathAbsent), + Ok(TreeObject::Unsupported { .. }) => Err(Reason::UnsupportedObjectType), + Err(reason) => Err(*reason), + } +} + +struct Inspector<'a> { + dir: &'a Path, + limits: InspectionLimits, + reviewed_head_sha: &'a str, + local_head_sha: &'a str, + reviewed_present: Result, + trees: BTreeMap<(String, String), Result>, + digests: BTreeMap>, +} + +impl Inspector<'_> { + async fn tree_object(&mut self, commit: &str, path: &str) -> Result { + let key = (commit.to_owned(), path.to_owned()); + if let Some(cached) = self.trees.get(&key) { + return cached.clone(); + } + let res = inspection::tree_object(self.dir, commit, path, self.limits) + .await + .map_err(|error| git_error_reason(&error)); + self.trees.insert(key, res.clone()); + res + } + + async fn blob_sha256(&mut self, oid: &str) -> Result { + if let Some(cached) = self.digests.get(oid) { + return cached.clone(); + } + let res = inspection::blob_sha256(self.dir, oid, self.limits) + .await + .map_err(|error| git_error_reason(&error)); + self.digests.insert(oid.to_owned(), res.clone()); + res + } + + async fn classify_integrity( + &mut self, + recorded: Option<&str>, + reviewed_obj: &Result, + ) -> IntegrityObservation { + let Some(raw) = recorded else { + return IntegrityObservation::NotRecorded; + }; + if raw.len() != 64 || !raw.bytes().all(|b| b.is_ascii_hexdigit()) { + return IntegrityObservation::Unavailable(Reason::MalformedRecordedDigest); + } + let expected = raw.to_ascii_lowercase(); + match reviewed_blob_oid(reviewed_obj) { + Ok(oid) => match self.blob_sha256(oid).await { + Ok(actual) if actual == expected => IntegrityObservation::Matched, + Ok(_) => IntegrityObservation::Mismatch, + Err(reason) => IntegrityObservation::Unavailable(reason), + }, + Err(reason) => IntegrityObservation::Unavailable(reason), + } + } + + /// Compares Git blob object identity at `local_head_sha` against a known + /// regular-file blob at `reviewed_head_sha`. Requires an available original + /// regular-file entry before reporting `unchanged`, `changed`, or `absent`; + /// establishes blob identity equality/inequality without reading both blobs' bytes. + async fn classify_local_head( + &mut self, + path: &str, + reviewed_obj: &Result, + ) -> LocalHeadObservation { + let reviewed_oid = match reviewed_blob_oid(reviewed_obj) { + Ok(oid) => oid, + Err(reason) => return LocalHeadObservation::Unavailable(reason), + }; + match self.tree_object(self.local_head_sha, path).await { + Ok(TreeObject::RegularBlob { oid }) if oid == reviewed_oid => { + LocalHeadObservation::Unchanged + } + Ok(TreeObject::RegularBlob { .. }) => LocalHeadObservation::Changed, + Ok(TreeObject::Absent) => LocalHeadObservation::Absent, + Ok(TreeObject::Unsupported { .. }) => { + LocalHeadObservation::Unavailable(Reason::UnsupportedObjectType) + } + Err(reason) => LocalHeadObservation::Unavailable(reason), + } + } + + async fn inspect_reference( + &mut self, + finding_id: Uuid, + assessment_id: Uuid, + lane: LaneRef<'_>, + reference: &EvidenceRef, + ) -> InspectedReference { + let (path, integrity, local_head) = + match source_evidence::primary_source_path(reference, self.reviewed_head_sha) { + Err(excl) => { + let reason = Reason::from(excl); + ( + reference.repository_path.clone(), + IntegrityObservation::OutsideScope(reason), + LocalHeadObservation::OutsideScope(reason), + ) + } + Ok(path) => { + let rev_obj = match self.reviewed_present { + Ok(true) => self.tree_object(self.reviewed_head_sha, path).await, + Ok(false) => Err(Reason::ReviewedCommitMissing), + Err(reason) => Err(reason), + }; + let integrity = self + .classify_integrity(reference.file_sha256.as_deref(), &rev_obj) + .await; + let local_head = self.classify_local_head(path, &rev_obj).await; + (Some(path.to_owned()), integrity, local_head) + } + }; + InspectedReference { + finding_id, + assessment_id, + lane: lane.to_owned(), + kind: reference.kind.clone(), + label: reference.label.clone(), + repository_path: path, + start_line: reference.start_line, + end_line: reference.end_line, + integrity, + local_head, + } + } +} + +pub(super) async fn inspect_review( + dir: &Path, + detail: &ReviewDetail, + repository_id: Uuid, + repository_full_name: String, + reviewed_head_sha: String, + local_head_sha: String, + limits: InspectionLimits, +) -> InspectionReport { + let (mut warnings, mut lanes) = (Vec::new(), Vec::new()); + if let Some(code) = outcome::code_assessment(detail) { + lanes.push(AssessmentLane { + assessment_id: code.id, + lane: LaneRef::Code, + findings: code.findings.as_slice(), + }); + } else if outcome::code_unavailable(detail) { + warnings.push(InspectionWarning { + code: "CODE_ASSESSMENT_UNAVAILABLE", + message: "CODE assessment is unavailable or does not match the review's pinned commits; its findings were not inspected.".to_owned(), + }); + } + for assessment in &detail.assessments { + lanes.push(AssessmentLane { + assessment_id: assessment.id, + lane: LaneRef::Env(assessment.environment_display_name.as_str()), + findings: assessment.findings.as_slice(), + }); + } + if let Some(reason) = outcome::review_gap(detail) { + warnings.push(InspectionWarning { + code: reason, + message: format!("Review assessment record is incomplete ({reason})."), + }); + } + + let has_refs = lanes + .iter() + .any(|lane| lane.findings.iter().any(|f| !f.evidence_refs.is_empty())); + let reviewed_present = if has_refs { + inspection::commit_exists(dir, &reviewed_head_sha, limits) + .await + .map_err(|error| git_error_reason(&error)) + } else { + Ok(true) + }; + + let mut inspector = Inspector { + dir, + limits, + reviewed_head_sha: &reviewed_head_sha, + local_head_sha: &local_head_sha, + reviewed_present, + trees: BTreeMap::new(), + digests: BTreeMap::new(), + }; + let mut references = Vec::new(); + for lane in lanes { + for finding in lane.findings { + for reference in &finding.evidence_refs { + references.push( + inspector + .inspect_reference(finding.id, lane.assessment_id, lane.lane, reference) + .await, + ); + } + } + } + + InspectionReport { + schema: SCHEMA, + review_id: detail.id, + repository_id, + repository_full_name, + reviewed_head_sha, + local_head_sha, + warnings, + summary: summarize(&references), + references, + } +} diff --git a/src/evidence/render.rs b/src/evidence/render.rs new file mode 100644 index 0000000..703de22 --- /dev/null +++ b/src/evidence/render.rs @@ -0,0 +1,153 @@ +//! Terminal-safe human-readable renderer for source evidence inspection reports. + +use std::fmt::Write as _; + +use crate::text::one_line; + +use super::report::{InspectedReference, InspectionReport, Lane, Reason}; + +fn format_location(item: &InspectedReference) -> String { + if let Some(path) = &item.repository_path { + let path = one_line(path); + return match (item.start_line, item.end_line) { + (Some(s), Some(e)) if e > s => format!("{path}:{s}-{e}"), + (Some(s), _) => format!("{path}:{s}"), + (None, _) => path, + }; + } + let label = one_line(&item.label); + if label.is_empty() { + one_line(&item.kind) + } else { + label + } +} + +fn count(n: usize, unit: &str) -> String { + format!("{n} {unit}{}", if n == 1 { "" } else { "s" }) +} + +fn join_counts(items: &[(&str, usize)]) -> Option { + let parts: Vec = items + .iter() + .filter(|(_, n)| *n > 0) + .map(|(label, n)| format!("{n} {label}")) + .collect(); + (!parts.is_empty()).then(|| parts.join(", ")) +} + +fn write_status(out: &mut String, heading: &str, status: &str, reason: Option) { + let _ = match reason { + Some(r) => writeln!(out, " {heading:<11} {status} ({})", r.description()), + None => writeln!(out, " {heading:<11} {status}"), + }; +} + +pub(super) fn render(report: &InspectionReport) -> String { + let mut out = String::new(); + let _ = writeln!(out, "Source evidence inspection"); + let _ = writeln!(out, "Review: {}", report.review_id); + let _ = writeln!( + out, + "Repository: {}", + one_line(&report.repository_full_name) + ); + let _ = writeln!(out, "Reviewed head: {}", report.reviewed_head_sha); + let _ = writeln!(out, "Local HEAD: {}", report.local_head_sha); + for w in &report.warnings { + let _ = writeln!(out, "Warning: {}", one_line(&w.message)); + } + if report.references.is_empty() { + let _ = writeln!( + out, + "\nNo source evidence references were recorded on eligible assessments." + ); + } + for item in &report.references { + let lane = match &item.lane { + Lane::Code => "CODE".to_owned(), + Lane::Env(env) => format!("ENV: {}", one_line(env)), + }; + let _ = writeln!( + out, + "\n{} ({lane}, finding {})", + format_location(item), + item.finding_id + ); + write_status( + &mut out, + "Integrity:", + item.integrity.as_str(), + item.integrity.reason(), + ); + write_status( + &mut out, + "Local HEAD:", + item.local_head.as_str(), + item.local_head.reason(), + ); + } + + let _ = writeln!(out, "\nSummary:"); + let s = &report.summary; + if s.eligible_references == 0 { + let extra = if s.outside_scope_references > 0 { + format!(" ({} outside scope)", s.outside_scope_references) + } else { + String::new() + }; + let _ = writeln!(out, " 0 eligible source references inspected{extra}"); + } else { + let el = count(s.eligible_references, "eligible reference"); + let uf = count(s.unique_files, "unique source file"); + let _ = writeln!(out, " {el} inspected ({uf})"); + if s.outside_scope_references > 0 { + let _ = writeln!( + out, + " {} outside scope", + count(s.outside_scope_references, "reference") + ); + } + let i_counts = [ + ("matched", s.integrity.matched), + ("mismatch", s.integrity.mismatch), + ("not recorded", s.integrity.not_recorded), + ("unavailable", s.integrity.unavailable), + ]; + if let Some(parts) = join_counts(&i_counts) { + let _ = writeln!(out, " Integrity: {parts}"); + } + let h_counts = [ + ("unchanged", s.local_head.unchanged), + ("changed", s.local_head.changed), + ("absent", s.local_head.absent), + ("unavailable", s.local_head.unavailable), + ]; + if let Some(parts) = join_counts(&h_counts) { + let _ = writeln!(out, " Local HEAD: {parts}"); + } + let ch = s.unique_files_changed_at_local_head; + if ch > 0 { + let verb = if ch == 1 { "differs" } else { "differ" }; + let _ = writeln!( + out, + " {} {verb} at local HEAD", + count(ch, "unique source file") + ); + } + let ab = s.unique_files_absent_at_local_head; + if ab > 0 { + let _ = writeln!( + out, + " {} absent at local HEAD", + count(ab, "unique source file") + ); + } + } + let _ = writeln!(out, "\nUncommitted changes are not inspected."); + let _ = writeln!( + out, + "Source integrity and local HEAD comparison do not establish finding validity." + ); + out +} diff --git a/src/evidence/report.rs b/src/evidence/report.rs new file mode 100644 index 0000000..7646c72 --- /dev/null +++ b/src/evidence/report.rs @@ -0,0 +1,285 @@ +//! Typed domain and JSON report models for source evidence inspection. + +use std::collections::BTreeSet; + +use serde::{Serialize, Serializer}; +use uuid::Uuid; + +use crate::source_evidence::PrimarySourceExclusion; + +pub(super) const SCHEMA: &str = "proofline.evidence-inspection.v1"; + +#[derive(Debug, Serialize)] +pub(super) struct InspectionReport { + pub(super) schema: &'static str, + pub(super) review_id: Uuid, + pub(super) repository_id: Uuid, + pub(super) repository_full_name: String, + pub(super) reviewed_head_sha: String, + pub(super) local_head_sha: String, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub(super) warnings: Vec, + pub(super) summary: InspectionSummary, + pub(super) references: Vec, +} + +#[derive(Debug, Serialize)] +pub(super) struct InspectionWarning { + pub(super) code: &'static str, + pub(super) message: String, +} + +#[derive(Debug, Default, Serialize)] +pub(super) struct InspectionSummary { + pub(super) total_references: usize, + pub(super) eligible_references: usize, + pub(super) outside_scope_references: usize, + pub(super) unique_files: usize, + pub(super) integrity: IntegrityCounts, + pub(super) local_head: LocalHeadCounts, + pub(super) unique_files_changed_at_local_head: usize, + pub(super) unique_files_absent_at_local_head: usize, +} + +#[derive(Debug, Default, Serialize)] +pub(super) struct IntegrityCounts { + pub(super) matched: usize, + pub(super) mismatch: usize, + pub(super) not_recorded: usize, + pub(super) unavailable: usize, + pub(super) outside_scope: usize, +} + +#[derive(Debug, Default, Serialize)] +pub(super) struct LocalHeadCounts { + pub(super) unchanged: usize, + pub(super) changed: usize, + pub(super) absent: usize, + pub(super) unavailable: usize, + pub(super) outside_scope: usize, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub(super) enum Lane { + Code, + Env(String), +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum IntegrityObservation { + Matched, + Mismatch, + NotRecorded, + Unavailable(Reason), + OutsideScope(Reason), +} + +impl IntegrityObservation { + pub(super) const fn as_str(self) -> &'static str { + match self { + Self::Matched => "matched", + Self::Mismatch => "mismatch", + Self::NotRecorded => "not_recorded", + Self::Unavailable(_) => "unavailable", + Self::OutsideScope(_) => "outside_scope", + } + } + + pub(super) const fn reason(self) -> Option { + match self { + Self::Unavailable(reason) | Self::OutsideScope(reason) => Some(reason), + Self::Matched | Self::Mismatch | Self::NotRecorded => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) enum LocalHeadObservation { + Unchanged, + Changed, + Absent, + Unavailable(Reason), + OutsideScope(Reason), +} + +impl LocalHeadObservation { + pub(super) const fn as_str(self) -> &'static str { + match self { + Self::Unchanged => "unchanged", + Self::Changed => "changed", + Self::Absent => "absent", + Self::Unavailable(_) => "unavailable", + Self::OutsideScope(_) => "outside_scope", + } + } + + pub(super) const fn reason(self) -> Option { + match self { + Self::Unavailable(reason) | Self::OutsideScope(reason) => Some(reason), + Self::Unchanged | Self::Changed | Self::Absent => None, + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(super) enum Reason { + CompanionRepository, + NonRepositoryFile, + UnverifiedProvenance, + CommitUnavailable, + InvalidCommit, + DifferentCommit, + InvalidPath, + MalformedRecordedDigest, + ReviewedCommitMissing, + ReviewedPathAbsent, + UnsupportedObjectType, + BlobTooLarge, + GitTimeout, + GitOutputLimitExceeded, + GitError, +} + +impl Reason { + pub(super) const fn description(self) -> &'static str { + match self { + Self::CompanionRepository => "companion-repository reference is outside scope", + Self::NonRepositoryFile => "non-repository-file reference is outside scope", + Self::UnverifiedProvenance => "evidence provenance is not VERIFIED_REPOSITORY_READ", + Self::CommitUnavailable => "reference records no commit SHA", + Self::InvalidCommit => "reference commit SHA is invalid", + Self::DifferentCommit => "reference commit SHA does not match reviewed head", + Self::InvalidPath => "reference path is not a valid repository-relative path", + Self::MalformedRecordedDigest => "recorded file_sha256 is not a valid SHA-256 digest", + Self::ReviewedCommitMissing => { + "reviewed commit is not present in the local Git repository" + } + Self::ReviewedPathAbsent => "cited path is absent at the reviewed commit", + Self::UnsupportedObjectType => "Git entry is not a regular file blob", + Self::BlobTooLarge => "Git blob exceeds the inspection size limit", + Self::GitTimeout => "local Git inspection command timed out", + Self::GitOutputLimitExceeded => "local Git command exceeded the output limit", + Self::GitError => "local Git object inspection failed", + } + } +} + +impl From for Reason { + fn from(value: PrimarySourceExclusion) -> Self { + match value { + PrimarySourceExclusion::CompanionRepository => Self::CompanionRepository, + PrimarySourceExclusion::NonCodeReference => Self::NonRepositoryFile, + PrimarySourceExclusion::UnverifiedProvenance => Self::UnverifiedProvenance, + PrimarySourceExclusion::CommitUnavailable => Self::CommitUnavailable, + PrimarySourceExclusion::InvalidCommit => Self::InvalidCommit, + PrimarySourceExclusion::DifferentCommit => Self::DifferentCommit, + PrimarySourceExclusion::InvalidPath => Self::InvalidPath, + } + } +} + +#[derive(Debug)] +pub(super) struct InspectedReference { + pub(super) finding_id: Uuid, + pub(super) assessment_id: Uuid, + pub(super) lane: Lane, + pub(super) kind: String, + pub(super) label: String, + pub(super) repository_path: Option, + pub(super) start_line: Option, + pub(super) end_line: Option, + pub(super) integrity: IntegrityObservation, + pub(super) local_head: LocalHeadObservation, +} + +impl Serialize for InspectedReference { + fn serialize(&self, serializer: S) -> Result { + #[derive(Serialize)] + struct Wire<'a> { + finding_id: Uuid, + assessment_id: Uuid, + lane: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + environment: Option<&'a str>, + kind: &'a str, + label: &'a str, + #[serde(skip_serializing_if = "Option::is_none")] + repository_path: Option<&'a str>, + #[serde(skip_serializing_if = "Option::is_none")] + start_line: Option, + #[serde(skip_serializing_if = "Option::is_none")] + end_line: Option, + integrity: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + integrity_reason: Option, + local_head: &'static str, + #[serde(skip_serializing_if = "Option::is_none")] + local_head_reason: Option, + } + + let (lane, environment) = match &self.lane { + Lane::Code => ("CODE", None), + Lane::Env(env) => ("ENV", Some(env.as_str())), + }; + Wire { + finding_id: self.finding_id, + assessment_id: self.assessment_id, + lane, + environment, + kind: &self.kind, + label: &self.label, + repository_path: self.repository_path.as_deref(), + start_line: self.start_line, + end_line: self.end_line, + integrity: self.integrity.as_str(), + integrity_reason: self.integrity.reason(), + local_head: self.local_head.as_str(), + local_head_reason: self.local_head.reason(), + } + .serialize(serializer) + } +} + +pub(super) fn summarize(references: &[InspectedReference]) -> InspectionSummary { + let mut summary = InspectionSummary::default(); + let (mut files, mut changed, mut absent) = (BTreeSet::new(), BTreeSet::new(), BTreeSet::new()); + for item in references { + summary.total_references += 1; + match item.integrity { + IntegrityObservation::Matched => summary.integrity.matched += 1, + IntegrityObservation::Mismatch => summary.integrity.mismatch += 1, + IntegrityObservation::NotRecorded => summary.integrity.not_recorded += 1, + IntegrityObservation::Unavailable(_) => summary.integrity.unavailable += 1, + IntegrityObservation::OutsideScope(_) => summary.integrity.outside_scope += 1, + } + match item.local_head { + LocalHeadObservation::Unchanged => summary.local_head.unchanged += 1, + LocalHeadObservation::Changed => summary.local_head.changed += 1, + LocalHeadObservation::Absent => summary.local_head.absent += 1, + LocalHeadObservation::Unavailable(_) => summary.local_head.unavailable += 1, + LocalHeadObservation::OutsideScope(_) => summary.local_head.outside_scope += 1, + } + if matches!(item.integrity, IntegrityObservation::OutsideScope(_)) { + summary.outside_scope_references += 1; + } else { + summary.eligible_references += 1; + if let Some(path) = item.repository_path.as_deref() { + files.insert(path); + match item.local_head { + LocalHeadObservation::Changed => { + changed.insert(path); + } + LocalHeadObservation::Absent => { + absent.insert(path); + } + _ => {} + } + } + } + } + summary.unique_files = files.len(); + summary.unique_files_changed_at_local_head = changed.len(); + summary.unique_files_absent_at_local_head = absent.len(); + summary +} diff --git a/src/evidence/tests.rs b/src/evidence/tests.rs new file mode 100644 index 0000000..34c08d6 --- /dev/null +++ b/src/evidence/tests.rs @@ -0,0 +1,218 @@ +use std::path::Path; + +use sha2::{Digest as _, Sha256}; +use uuid::Uuid; + +use crate::git::inspection::InspectionLimits; +use crate::model::{ + CodeAssessment, CodeAssessmentRead, CodeAssessmentStatus, EvidenceRef, Finding, ReviewDetail, +}; + +use super::inspect::inspect_review; +use super::render::render; +use super::report::{InspectionReport, IntegrityObservation, LocalHeadObservation, Reason}; + +fn run_git(dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "git {args:?}: {out:?}"); + String::from_utf8(out.stdout).unwrap() +} + +fn init_repo(dir: &Path) { + run_git(dir, &["init", "-q", "-b", "main"]); + for (k, v) in [ + ("user.email", "dev@example.com"), + ("user.name", "dev"), + ("core.autocrlf", "false"), + ] { + run_git(dir, &["config", k, v]); + } +} + +fn commit_file(dir: &Path, path: &str, bytes: &[u8], msg: &str) -> String { + std::fs::write(dir.join(path), bytes).unwrap(); + run_git(dir, &["add", "--", path]); + run_git(dir, &["commit", "-qm", msg]); + run_git(dir, &["rev-parse", "HEAD"]).trim().to_owned() +} + +fn ref_file(path: &str, commit: &str, digest: Option, start: u32) -> EvidenceRef { + EvidenceRef { + kind: "repository_file".to_owned(), + label: format!("{path}:{start}"), + provenance_status: Some("VERIFIED_REPOSITORY_READ".to_owned()), + repository_path: Some(path.to_owned()), + start_line: Some(start), + end_line: Some(start + 2), + file_sha256: digest, + commit_sha: Some(commit.to_owned()), + companion_repository: None, + } +} + +fn code_review(head: &str, refs: Vec) -> ReviewDetail { + ReviewDetail { + id: Uuid::from_u128(1), + kind: "PULL_REQUEST".to_owned(), + status: "COMPLETED".to_owned(), + assessment_count: 0, + assessments: Vec::new(), + code_assessment: Some(CodeAssessmentRead::Recorded(CodeAssessment { + id: Uuid::from_u128(2), + status: CodeAssessmentStatus::Completed, + base_commit_sha: "0".repeat(40), + head_commit_sha: head.to_owned(), + findings: vec![Finding { + id: Uuid::from_u128(10), + finding_fingerprint: None, + severity: "WARNING".to_owned(), + risk_domain: "authorization".to_owned(), + claim: "missing tenant filter".to_owned(), + impact: "cross-tenant read".to_owned(), + lifecycle_state: "NEW".to_owned(), + remediation: None, + evidence_refs: refs, + }], + incompleteness_kind: None, + reason_codes: None, + })), + base_commit_sha: Some("0".repeat(40)), + head_commit_sha: Some(head.to_owned()), + open_items: None, + pull_request_number: Some(1), + repository_id: Some(Uuid::from_u128(3)), + repository_full_name: Some("acme/service".to_owned()), + run_number: Some(1), + subjects: Vec::new(), + local_reverifications: Vec::new(), + } +} + +async fn run_inspect( + dir: &Path, + detail: &ReviewDetail, + reviewed: &str, + head: &str, + limits: InspectionLimits, +) -> InspectionReport { + inspect_review( + dir, + detail, + detail.repository_id.unwrap(), + "acme/service".to_owned(), + reviewed.to_owned(), + head.to_owned(), + limits, + ) + .await +} + +#[tokio::test] +async fn deduplication_preserves_contradictory_digests_and_requires_original_entry() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir); + let original = b"def query():\n return 1\n"; + let reviewed = commit_file(dir, "service.py", original, "reviewed"); + let head = commit_file(dir, "service.py", b"def query():\n return 2\n", "upd"); + + let sha = format!("{:x}", Sha256::digest(original)); + let detail = code_review( + &reviewed, + vec![ + ref_file("service.py", &reviewed, Some(sha), 1), + ref_file("service.py", &reviewed, Some("f".repeat(64)), 2), + ref_file("service.py", &reviewed, None, 3), + ref_file("service.py", &reviewed, Some("bad".to_owned()), 4), + ref_file("never_existed.py", &reviewed, None, 1), + ], + ); + let r = run_inspect(dir, &detail, &reviewed, &head, InspectionLimits::default()).await; + let s = &r.summary; + assert_eq!((s.eligible_references, s.unique_files), (5, 2)); + assert_eq!(s.unique_files_changed_at_local_head, 1); + assert_eq!(s.unique_files_absent_at_local_head, 0); + assert_eq!(r.references[0].integrity, IntegrityObservation::Matched); + assert_eq!(r.references[1].integrity, IntegrityObservation::Mismatch); + assert_eq!(r.references[2].integrity, IntegrityObservation::NotRecorded); + assert_eq!( + r.references[3].integrity, + IntegrityObservation::Unavailable(Reason::MalformedRecordedDigest) + ); + for item in &r.references[..4] { + assert_eq!(item.local_head, LocalHeadObservation::Changed); + } + assert_eq!(r.references[4].integrity, IntegrityObservation::NotRecorded); + assert_eq!( + r.references[4].local_head, + LocalHeadObservation::Unavailable(Reason::ReviewedPathAbsent) + ); +} + +#[tokio::test] +async fn independent_reasons_preserved_for_oversized_blob_and_head_symlink() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir); + let big = vec![b'a'; 128]; + let reviewed = commit_file(dir, "big.txt", &big, "reviewed"); + #[cfg(unix)] + { + std::fs::remove_file(dir.join("big.txt")).unwrap(); + std::os::unix::fs::symlink("other.txt", dir.join("big.txt")).unwrap(); + run_git(dir, &["add", "big.txt"]); + run_git(dir, &["commit", "-qm", "symlink"]); + } + let head = run_git(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + let sha = format!("{:x}", Sha256::digest(&big)); + let detail = code_review( + &reviewed, + vec![ref_file("big.txt", &reviewed, Some(sha), 1)], + ); + let limits = InspectionLimits { + max_blob_bytes: 32, + ..InspectionLimits::default() + }; + let r = run_inspect(dir, &detail, &reviewed, &head, limits).await; + let item = &r.references[0]; + assert_eq!( + item.integrity, + IntegrityObservation::Unavailable(Reason::BlobTooLarge) + ); + #[cfg(unix)] + assert_eq!( + item.local_head, + LocalHeadObservation::Unavailable(Reason::UnsupportedObjectType) + ); + #[cfg(not(unix))] + assert_eq!(item.local_head, LocalHeadObservation::Unchanged); +} + +#[tokio::test] +async fn immutable_head_snapshot_and_older_local_head_stay_neutral_and_consistent() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir); + let older = commit_file(dir, "app.py", b"v1\n", "older"); + let reviewed_bytes = b"v2\n"; + let reviewed = commit_file(dir, "app.py", reviewed_bytes, "reviewed"); + commit_file(dir, "app.py", b"v3\n", "concurrent"); + + let sha = format!("{:x}", Sha256::digest(reviewed_bytes)); + let detail = code_review(&reviewed, vec![ref_file("app.py", &reviewed, Some(sha), 1)]); + let r = run_inspect(dir, &detail, &reviewed, &older, InspectionLimits::default()).await; + assert_eq!(r.local_head_sha, older); + assert_eq!(r.reviewed_head_sha, reviewed); + assert_eq!(r.references[0].integrity, IntegrityObservation::Matched); + assert_eq!(r.references[0].local_head, LocalHeadObservation::Changed); + let text = render(&r); + assert!(text.contains("differs at local HEAD"), "{text}"); + for forbidden in ["after the review", "since the review", "resolved"] { + assert!(!text.contains(forbidden), "{text}"); + } +} diff --git a/src/git.rs b/src/git.rs index c88f567..1f9b7a4 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,6 +1,8 @@ //! What the current checkout names: its source repository, its commit and its //! local changes. +pub(crate) mod inspection; + use std::path::{Path, PathBuf}; use tokio::process::Command; @@ -51,6 +53,18 @@ pub enum GitError { InvalidLocalPath(String), #[error("{0:?} is not a regular tracked file at commit {1}; no review was requested")] NotTrackedFile(String, String), + #[error( + "partial or promisor Git clones are not supported for evidence inspection because local-only object access without fetching cannot be guaranteed" + )] + PartialClone, + #[error("git {command} timed out")] + TimedOut { command: String }, + #[error("git {command} exceeded the {limit}-byte output limit")] + OutputTooLarge { command: String, limit: usize }, + #[error("Git blob exceeded the {limit}-byte inspection limit")] + BlobTooLarge { limit: u64 }, + #[error("could not parse Git tree metadata")] + InvalidTreeEntry, } /// Two exact commits of a pushed change: the head, and the base it is diff --git a/src/git/inspection.rs b/src/git/inspection.rs new file mode 100644 index 0000000..41e5207 --- /dev/null +++ b/src/git/inspection.rs @@ -0,0 +1,760 @@ +//! Read-only, resource-bounded inspection of immutable local Git commits and +//! blobs. +//! +//! Every subprocess runs with network protocols disabled +//! (`-c protocol.allow=never`, `GIT_ALLOW_PROTOCOL=""`, `GIT_NO_LAZY_FETCH=1`, +//! `GIT_TERMINAL_PROMPT=0`), replacement objects ignored +//! (`--no-replace-objects`), bounded stdout/stderr streaming, a single +//! per-command timeout, and explicit child termination and reaping. + +use std::path::Path; +use std::process::{ExitStatus, Stdio}; +use std::time::Duration; + +use sha2::{Digest as _, Sha256}; +use tokio::io::{AsyncRead, AsyncReadExt as _}; +use tokio::process::{Child, Command}; + +use super::{GitError, RemoteRepository, commit_sha}; +use crate::text::one_line; + +const DEFAULT_INSPECTION_TIMEOUT: Duration = Duration::from_secs(10); +const MAX_TREE_OUTPUT_BYTES: usize = 64 * 1024; +const MAX_BLOB_BYTES: u64 = 16 * 1024 * 1024; +const MAX_STDERR_BYTES: usize = 16 * 1024; +const MAX_STDERR_DRAIN_BYTES: usize = 1024 * 1024; + +/// Resource bounds for read-only local Git object inspection. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct InspectionLimits { + pub(crate) timeout: Duration, + pub(crate) max_tree_output_bytes: usize, + pub(crate) max_blob_bytes: u64, +} + +impl Default for InspectionLimits { + fn default() -> Self { + Self { + timeout: DEFAULT_INSPECTION_TIMEOUT, + max_tree_output_bytes: MAX_TREE_OUTPUT_BYTES, + max_blob_bytes: MAX_BLOB_BYTES, + } + } +} + +/// A single literal tree entry resolved from an immutable Git commit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum TreeObject { + RegularBlob { oid: String }, + Absent, + Unsupported { mode: String, kind: String }, +} + +fn local_inspection_command(dir: &Path, args: &[&str]) -> Command { + let mut command = Command::new("git"); + command + .arg("-C") + .arg(dir) + .args(["-c", "protocol.allow=never", "--no-replace-objects"]) + .args(args) + .env("GIT_NO_LAZY_FETCH", "1") + .env("GIT_TERMINAL_PROMPT", "0") + .env("GIT_ALLOW_PROTOCOL", "") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + command +} + +async fn terminate_and_reap(child: &mut Child) { + let _ = child.start_kill(); + let _ = child.wait().await; +} + +async fn read_bounded( + mut reader: impl AsyncRead + Unpin, + limit: u64, + on_limit: impl FnOnce() -> GitError, + mut on_chunk: impl FnMut(&[u8]), +) -> Result<(), GitError> { + let (mut total, mut buf) = (0_u64, [0_u8; 8_192]); + loop { + let read = reader + .read(&mut buf) + .await + .map_err(|error| GitError::Unavailable(one_line(&error.to_string())))?; + if read == 0 { + return Ok(()); + } + total = total.saturating_add(u64::try_from(read).unwrap_or(u64::MAX)); + if total > limit { + return Err(on_limit()); + } + if let Some(slice) = buf.get(..read) { + on_chunk(slice); + } + } +} + +async fn run_bounded( + mut command: Command, + label: &str, + timeout: Duration, + stdout_limit: u64, + on_stdout_limit: impl FnOnce() -> GitError, + on_stdout: impl FnMut(&[u8]), +) -> Result<(ExitStatus, String), GitError> { + let mut child = command + .spawn() + .map_err(|error| GitError::Unavailable(one_line(&error.to_string())))?; + let (Some(stdout), Some(stderr)) = (child.stdout.take(), child.stderr.take()) else { + terminate_and_reap(&mut child).await; + return Err(GitError::Unavailable("missing subprocess pipe".to_owned())); + }; + let mut stderr_bytes = Vec::new(); + let stderr_limit = u64::try_from(MAX_STDERR_DRAIN_BYTES).unwrap_or(u64::MAX); + let run = async { + let out = read_bounded(stdout, stdout_limit, on_stdout_limit, on_stdout); + let err = read_bounded( + stderr, + stderr_limit, + || GitError::OutputTooLarge { + command: one_line(label), + limit: MAX_STDERR_DRAIN_BYTES, + }, + |chunk| { + let take = chunk + .len() + .min(MAX_STDERR_BYTES.saturating_sub(stderr_bytes.len())); + if let Some(slice) = chunk.get(..take) { + stderr_bytes.extend_from_slice(slice); + } + }, + ); + tokio::try_join!(out, err)?; + child + .wait() + .await + .map_err(|error| GitError::Unavailable(one_line(&error.to_string()))) + }; + match tokio::time::timeout(timeout, run).await { + Ok(Ok(status)) => Ok(( + status, + one_line(String::from_utf8_lossy(&stderr_bytes).trim()), + )), + Ok(Err(error)) => { + terminate_and_reap(&mut child).await; + Err(error) + } + Err(_) => { + terminate_and_reap(&mut child).await; + Err(GitError::TimedOut { + command: one_line(label), + }) + } + } +} + +async fn run_local_bytes( + dir: &Path, + args: &[&str], + limits: InspectionLimits, +) -> Result<(ExitStatus, Vec, String), GitError> { + let (mut stdout, label, max_bytes) = (Vec::new(), args.join(" "), limits.max_tree_output_bytes); + let limit = u64::try_from(max_bytes).unwrap_or(u64::MAX); + let (status, stderr) = run_bounded( + local_inspection_command(dir, args), + &label, + limits.timeout, + limit, + || GitError::OutputTooLarge { + command: one_line(&label), + limit: max_bytes, + }, + |chunk| stdout.extend_from_slice(chunk), + ) + .await?; + Ok((status, stdout, stderr)) +} + +async fn run_local_line( + dir: &Path, + args: &[&str], + limits: InspectionLimits, +) -> Result { + let (status, stdout, stderr) = run_local_bytes(dir, args, limits).await?; + if !status.success() { + return Err(GitError::Failed { + command: one_line(&args.join(" ")), + stderr, + }); + } + Ok(String::from_utf8_lossy(&stdout).trim().to_owned()) +} + +/// Resolves a hosted remote URL in `dir` under bounded inspection limits. +pub(crate) async fn remote_repository_in( + dir: &Path, + remote: &str, + limits: InspectionLimits, +) -> Result { + let url = run_local_line(dir, &["remote", "get-url", "--", remote], limits).await?; + RemoteRepository::parse(&url).ok_or(GitError::UnknownRemote) +} + +fn has_partial_clone_config(raw: &[u8]) -> bool { + raw.split(|&byte| byte == 0) + .filter(|entry| !entry.is_empty()) + .any(|entry| { + let text = String::from_utf8_lossy(entry); + let (key, value) = text + .split_once('\n') + .map_or_else(|| (text.as_ref(), None), |(key, value)| (key, Some(value))); + let key = key.to_ascii_lowercase(); + if key == "extensions.partialclone" + || (key.starts_with("remote.") && key.ends_with(".partialclonefilter")) + { + return value.is_some_and(|val| !val.trim().is_empty()); + } + key.starts_with("remote.") + && key.ends_with(".promisor") + && value.is_none_or(|val| { + !matches!( + val.trim().to_ascii_lowercase().as_str(), + "false" | "no" | "off" | "0" | "" + ) + }) + }) +} + +async fn has_promisor_pack(pack_dir: &Path) -> Result { + let pack_err = |error: std::io::Error| { + GitError::Unavailable(one_line(&format!( + "could not read Git pack directory: {error}" + ))) + }; + let mut entries = match tokio::fs::read_dir(pack_dir).await { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false), + Err(error) => return Err(pack_err(error)), + }; + while let Some(entry) = entries.next_entry().await.map_err(pack_err)? { + if entry + .path() + .extension() + .is_some_and(|ext| ext.eq_ignore_ascii_case("promisor")) + { + return Ok(true); + } + } + Ok(false) +} + +/// Refuses partial or promisor clones where local-only object access cannot be +/// guaranteed across Git versions. Shallow clones remain allowed. +pub(crate) async fn ensure_no_partial_clone( + dir: &Path, + limits: InspectionLimits, +) -> Result<(), GitError> { + let config_args = [ + "config", + "--null", + "--get-regexp", + r"^(extensions\.partialclone|remote\..*\.(promisor|partialclonefilter))$", + ]; + let (status, stdout, stderr) = run_local_bytes(dir, &config_args, limits).await?; + match status.code() { + Some(0) if has_partial_clone_config(&stdout) => return Err(GitError::PartialClone), + Some(0 | 1) => {} + _ => { + return Err(GitError::Failed { + command: "config --null --get-regexp".to_owned(), + stderr, + }); + } + } + let pack_args = [ + "rev-parse", + "--path-format=absolute", + "--git-path", + "objects/pack", + ]; + let pack_dir = run_local_line(dir, &pack_args, limits).await?; + if has_promisor_pack(Path::new(&pack_dir)).await? { + return Err(GitError::PartialClone); + } + Ok(()) +} + +/// Resolves `HEAD` once in `dir` without consulting replacement objects. +pub(crate) async fn head_in(dir: &Path, limits: InspectionLimits) -> Result { + let args = ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]; + commit_sha(&run_local_line(dir, &args, limits).await?) +} + +/// Returns whether immutable commit `commit` is locally present in `dir`. +pub(crate) async fn commit_exists( + dir: &Path, + commit: &str, + limits: InspectionLimits, +) -> Result { + let sha = commit_sha(commit)?; + let spec = format!("{sha}^{{commit}}"); + let (status, stdout, stderr) = + run_local_bytes(dir, &["rev-parse", "--verify", "--quiet", &spec], limits).await?; + match status.code() { + Some(0) => Ok(commit_sha(String::from_utf8_lossy(&stdout).trim())? == sha), + Some(1) => Ok(false), + _ => Err(GitError::Failed { + command: format!("rev-parse --verify --quiet {spec}"), + stderr, + }), + } +} + +/// Resolves one literal repository-relative `path` in immutable `commit`'s tree. +pub(crate) async fn tree_object( + dir: &Path, + commit: &str, + path: &str, + limits: InspectionLimits, +) -> Result { + let sha = commit_sha(commit)?; + let args = [ + "--literal-pathspecs", + "ls-tree", + "-z", + "--full-tree", + &sha, + "--", + path, + ]; + let (status, stdout, stderr) = run_local_bytes(dir, &args, limits).await?; + if !status.success() { + return Err(GitError::Failed { + command: "ls-tree".to_owned(), + stderr, + }); + } + parse_tree_object(&stdout, path) +} + +fn parse_tree_object(output: &[u8], path: &str) -> Result { + for entry in output.split(|&byte| byte == 0).filter(|e| !e.is_empty()) { + let Some(sep) = entry.iter().position(|&byte| byte == b'\t') else { + return Err(GitError::InvalidTreeEntry); + }; + let (meta, rest) = entry.split_at(sep); + if rest.get(1..).ok_or(GitError::InvalidTreeEntry)? != path.as_bytes() { + continue; + } + let meta = std::str::from_utf8(meta).map_err(|_| GitError::InvalidTreeEntry)?; + let mut parts = meta.split(' '); + let (Some(mode), Some(kind), Some(raw_oid), None) = + (parts.next(), parts.next(), parts.next(), parts.next()) + else { + return Err(GitError::InvalidTreeEntry); + }; + let oid = commit_sha(raw_oid)?; + return Ok(match (mode, kind) { + ("100644" | "100755", "blob") => TreeObject::RegularBlob { oid }, + _ => TreeObject::Unsupported { + mode: mode.to_owned(), + kind: kind.to_owned(), + }, + }); + } + Ok(TreeObject::Absent) +} + +/// Computes the lowercase SHA-256 digest of raw immutable Git blob `oid`, +/// enforcing both a size pre-check and a streaming byte cap. +pub(crate) async fn blob_sha256( + dir: &Path, + oid: &str, + limits: InspectionLimits, +) -> Result { + let oid = commit_sha(oid)?; + let size_text = run_local_line(dir, &["cat-file", "-s", &oid], limits).await?; + let size = size_text.parse::().map_err(|_| GitError::Failed { + command: "cat-file -s".to_owned(), + stderr: one_line(&format!("unreadable blob size: {size_text}")), + })?; + if size > limits.max_blob_bytes { + return Err(GitError::BlobTooLarge { + limit: limits.max_blob_bytes, + }); + } + blob_sha256_streaming(dir, &oid, limits).await +} + +async fn blob_sha256_streaming( + dir: &Path, + oid: &str, + limits: InspectionLimits, +) -> Result { + let (mut hasher, max_bytes) = (Sha256::new(), limits.max_blob_bytes); + let (status, stderr) = run_bounded( + local_inspection_command(dir, &["cat-file", "blob", oid]), + "cat-file blob", + limits.timeout, + max_bytes, + || GitError::BlobTooLarge { limit: max_bytes }, + |chunk| hasher.update(chunk), + ) + .await?; + if !status.success() { + return Err(GitError::Failed { + command: "cat-file blob".to_owned(), + stderr, + }); + } + Ok(format!("{:x}", hasher.finalize())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn run(dir: &Path, args: &[&str]) -> String { + let output = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .unwrap(); + assert!(output.status.success(), "git {args:?}: {output:?}"); + String::from_utf8(output.stdout).unwrap() + } + + fn init_repo(dir: &Path) { + run(dir, &["init", "-q", "-b", "main"]); + run(dir, &["config", "user.email", "dev@example.com"]); + run(dir, &["config", "user.name", "dev"]); + } + + fn hash_object(dir: &Path, bytes: &[u8]) -> String { + let mut child = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(["hash-object", "-w", "--stdin"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + std::io::Write::write_all(child.stdin.as_mut().unwrap(), bytes).unwrap(); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + String::from_utf8(out.stdout).unwrap().trim().to_owned() + } + + fn clone_repo(origin: &Path, dest: &Path, flag: &str) { + let url = url::Url::from_file_path(origin).unwrap().to_string(); + let out = std::process::Command::new("git") + .args(["clone", "--quiet", flag, &url]) + .arg(dest) + .output() + .unwrap(); + assert!(out.status.success(), "{out:?}"); + } + + fn commit_file(dir: &Path, path: &str, bytes: &[u8], msg: &str) -> String { + if let Some(parent) = Path::new(path).parent() + && !parent.as_os_str().is_empty() + { + std::fs::create_dir_all(dir.join(parent)).unwrap(); + } + std::fs::write(dir.join(path), bytes).unwrap(); + run(dir, &["add", "--", path]); + run(dir, &["commit", "-qm", msg]); + run(dir, &["rev-parse", "HEAD"]).trim().to_owned() + } + + #[tokio::test] + async fn local_inspection_handles_literal_paths_crlf_filters_and_non_regular_entries() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir); + for (k, v) in [ + ("core.autocrlf", "true"), + ("core.quotePath", "true"), + ("filter.poison.smudge", "exit 1"), + ] { + run(dir, &["config", k, v]); + } + std::fs::write(dir.join(".gitattributes"), "*.txt filter=poison\n").unwrap(); + + // Use NTFS-valid glob characters on Windows so Git's default + // `core.protectNTFS` `verify_path()` remains enabled while still + // exercising `--literal-pathspecs` against a decoy glob match. + #[cfg(windows)] + let weird_path = "dir/file [1].txt"; + #[cfg(not(windows))] + let weird_path = "dir/file [1] *?.txt"; + + let crlf_bytes = b"line one\r\nline two\r\n"; + let raw_oid = hash_object(dir, crlf_bytes); + run( + dir, + &[ + "update-index", + "--add", + "--cacheinfo", + &format!("100644,{raw_oid},{weird_path}"), + ], + ); + let (decoy_path, dash_path, unicode_path) = + ("dir/file 1.txt", "-leading-dash.txt", "dir/caf\u{00e9}.txt"); + std::fs::create_dir_all(dir.join("dir")).unwrap(); + std::fs::write(dir.join(decoy_path), b"decoy\n").unwrap(); + std::fs::write(dir.join(dash_path), b"dash\n").unwrap(); + std::fs::write(dir.join(unicode_path), b"utf8\n").unwrap(); + + let sub = dir.join("sub"); + std::fs::create_dir_all(&sub).unwrap(); + init_repo(&sub); + commit_file(&sub, "inner.txt", b"sub\n", "sub"); + run( + dir, + &[ + "add", + "--", + ".gitattributes", + decoy_path, + dash_path, + unicode_path, + "sub", + ], + ); + #[cfg(unix)] + { + std::os::unix::fs::symlink(dash_path, dir.join("link.txt")).unwrap(); + run(dir, &["add", "link.txt"]); + } + run(dir, &["commit", "-qm", "initial"]); + + let limits = InspectionLimits::default(); + let commit = head_in(dir, limits).await.unwrap(); + assert!(commit_exists(dir, &commit, limits).await.unwrap()); + assert_eq!( + tree_object(dir, &commit, weird_path, limits).await.unwrap(), + TreeObject::RegularBlob { + oid: raw_oid.clone() + } + ); + assert_eq!( + blob_sha256(dir, &raw_oid, limits).await.unwrap(), + format!("{:x}", Sha256::digest(crlf_bytes)) + ); + for regular in [decoy_path, dash_path, unicode_path] { + assert!(matches!( + tree_object(dir, &commit, regular, limits).await.unwrap(), + TreeObject::RegularBlob { .. } + )); + } + for absent in ["missing.txt", "sub/inner.txt"] { + assert_eq!( + tree_object(dir, &commit, absent, limits).await.unwrap(), + TreeObject::Absent + ); + } + for (path, mode, kind) in [("dir", "040000", "tree"), ("sub", "160000", "commit")] { + assert_eq!( + tree_object(dir, &commit, path, limits).await.unwrap(), + TreeObject::Unsupported { + mode: mode.to_owned(), + kind: kind.to_owned(), + } + ); + } + #[cfg(unix)] + assert_eq!( + tree_object(dir, &commit, "link.txt", limits).await.unwrap(), + TreeObject::Unsupported { + mode: "120000".to_owned(), + kind: "blob".to_owned(), + } + ); + } + + #[tokio::test] + async fn local_inspection_defeats_git_replace_objects() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir); + let original = b"authentic source bytes\n"; + let commit = commit_file(dir, "app.py", original, "initial"); + let limits = InspectionLimits::default(); + let TreeObject::RegularBlob { oid } = + tree_object(dir, &commit, "app.py", limits).await.unwrap() + else { + panic!("expected regular blob"); + }; + let spoof_oid = hash_object(dir, b"spoofed bytes\n"); + run(dir, &["replace", &oid, &spoof_oid]); + assert_eq!(run(dir, &["cat-file", "blob", &oid]), "spoofed bytes\n"); + assert_eq!( + blob_sha256(dir, &oid, limits).await.unwrap(), + format!("{:x}", Sha256::digest(original)) + ); + } + + #[tokio::test] + async fn partial_clone_detection_refuses_promisor_repos_and_allows_shallow_clones() { + let root = tempfile::tempdir().unwrap(); + let origin = root.path().join("origin"); + std::fs::create_dir_all(&origin).unwrap(); + init_repo(&origin); + run(&origin, &["config", "uploadpack.allowFilter", "true"]); + let first_commit = commit_file(&origin, "a.txt", b"v1\n", "c1"); + commit_file(&origin, "a.txt", b"v2\n", "c2"); + let limits = InspectionLimits::default(); + + let partial = root.path().join("partial"); + clone_repo(&origin, &partial, "--filter=blob:none"); + assert!(matches!( + ensure_no_partial_clone(&partial, limits).await, + Err(GitError::PartialClone) + )); + + for (name, setup) in [ + ( + "multi", + vec![ + ("remote.origin.promisor", "false"), + ("remote.backup.promisor", "true"), + ], + ), + ( + "legacy", + vec![ + ("core.repositoryformatversion", "1"), + ("extensions.partialClone", "origin"), + ], + ), + ] { + let sub = root.path().join(name); + std::fs::create_dir_all(&sub).unwrap(); + init_repo(&sub); + if name == "multi" { + run(&sub, &["config", "remote.origin.promisor", "false"]); + assert!(ensure_no_partial_clone(&sub, limits).await.is_ok()); + } + for (k, v) in setup { + run(&sub, &["config", k, v]); + } + assert!(matches!( + ensure_no_partial_clone(&sub, limits).await, + Err(GitError::PartialClone) + )); + } + + let pack_only = root.path().join("pack-only"); + let pack_dir = pack_only.join(".git").join("objects").join("pack"); + std::fs::create_dir_all(&pack_dir).unwrap(); + init_repo(&pack_only); + std::fs::write(pack_dir.join("pack-dummy.promisor"), b"").unwrap(); + assert!(matches!( + ensure_no_partial_clone(&pack_only, limits).await, + Err(GitError::PartialClone) + )); + + let shallow = root.path().join("shallow"); + clone_repo(&origin, &shallow, "--depth=1"); + assert!(ensure_no_partial_clone(&shallow, limits).await.is_ok()); + assert!( + !commit_exists(&shallow, &first_commit, limits) + .await + .unwrap() + ); + } + + #[tokio::test] + async fn blob_sha256_enforces_precheck_and_streaming_limits() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir); + let commit = commit_file(dir, "big.bin", &vec![b'x'; 256], "big"); + let limits = InspectionLimits::default(); + let TreeObject::RegularBlob { oid } = + tree_object(dir, &commit, "big.bin", limits).await.unwrap() + else { + panic!("expected blob"); + }; + let tight = InspectionLimits { + max_blob_bytes: 64, + ..limits + }; + assert!(matches!( + blob_sha256(dir, &oid, tight).await, + Err(GitError::BlobTooLarge { limit: 64 }) + )); + assert!(matches!( + blob_sha256_streaming(dir, &oid, tight).await, + Err(GitError::BlobTooLarge { limit: 64 }) + )); + } + + #[cfg(unix)] + #[tokio::test] + async fn bounded_subprocess_terminates_reaps_and_sanitizes_errors() { + let mut command = Command::new("sh"); + command + .args(["-c", "echo $$; exec sleep 30"]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + let mut captured = Vec::new(); + let Err(GitError::TimedOut { command }) = run_bounded( + command, + "sleep\u{1b}[31m", + Duration::from_millis(150), + 1024, + || GitError::BlobTooLarge { limit: 1024 }, + |chunk| captured.extend_from_slice(chunk), + ) + .await + else { + panic!("expected timeout error"); + }; + assert!(!command.contains('\u{1b}')); + let pid: u32 = String::from_utf8_lossy(&captured).trim().parse().unwrap(); + let alive = std::process::Command::new("kill") + .args(["-0", &pid.to_string()]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .unwrap() + .success(); + assert!( + !alive, + "timed-out child {pid} survived or remained unreaped" + ); + } + + #[tokio::test] + async fn sha256_git_repository_format_is_supported() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + run(dir, &["init", "-q", "--object-format=sha256", "-b", "main"]); + run(dir, &["config", "user.email", "dev@example.com"]); + run(dir, &["config", "user.name", "dev"]); + let body = b"sha256 repo content\n"; + let commit = commit_file(dir, "mod.rs", body, "init"); + let limits = InspectionLimits::default(); + assert_eq!(commit.len(), 64); + assert!(commit_exists(dir, &commit, limits).await.unwrap()); + let TreeObject::RegularBlob { oid } = + tree_object(dir, &commit, "mod.rs", limits).await.unwrap() + else { + panic!("expected regular blob"); + }; + assert_eq!(oid.len(), 64); + assert_eq!( + blob_sha256(dir, &oid, limits).await.unwrap(), + format!("{:x}", Sha256::digest(body)) + ); + } +} diff --git a/src/lib.rs b/src/lib.rs index 2ac4644..77f56d7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ mod coverage; pub mod credentials; mod deploy; pub mod device; +mod evidence; pub mod git; mod github_actions; mod hooks; @@ -24,6 +25,7 @@ mod sarif; mod scan; mod setup; mod severity; +mod source_evidence; pub mod text; mod tls; pub mod update; @@ -172,6 +174,9 @@ enum Command { Stop(StopArgs), /// Show the findings of the latest review of a commit or pull request. Findings(FindingsArgs), + /// Inspect commit-pinned source evidence against the local Git checkout. + #[command(subcommand)] + Evidence(evidence::EvidenceCommand), /// Forward a coding agent's stdio messages to this console's MCP server. Mcp, /// Commands for a CI job. @@ -291,14 +296,14 @@ struct RepositoryArgs { } #[derive(Clone, Copy, Debug, clap::ValueEnum)] -enum SourceProvider { +pub(crate) enum SourceProvider { Github, Gitlab, Git, } impl SourceProvider { - const fn as_str(self) -> &'static str { + pub(crate) const fn as_str(self) -> &'static str { match self { Self::Github => "github", Self::Gitlab => "gitlab", @@ -639,6 +644,10 @@ pub async fn run(cli: Cli, token: Option) -> anyhow::Result { + let api = connect(Http::new(origin)?, token, cli.org).await?; + evidence::run(&api, &args).await + } Command::Mcp => { let http = Http::new(origin)?; let token = credentials::load_token(http.origin(), token, cli.org).await?; diff --git a/src/sarif.rs b/src/sarif.rs index 5134174..f737799 100644 --- a/src/sarif.rs +++ b/src/sarif.rs @@ -8,6 +8,7 @@ use uuid::Uuid; use crate::model::{Assessment, CodeAssessment, EvidenceRef, Finding, ReviewDetail}; use crate::outcome::{self, Outcome}; +use crate::source_evidence::{self, PrimarySourceExclusion}; const SCHEMA: &str = "https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/schemas/sarif-schema-2.1.0.json"; @@ -612,30 +613,16 @@ fn code_location<'a>( reference: &'a EvidenceRef, head: &str, ) -> Result<(&'a str, u32, u32), LocationStatus> { - if reference.kind == "companion_repository_file" || reference.companion_repository.is_some() { - return Err(LocationStatus::CompanionRepository); - } - if reference.kind != "repository_file" { - return Err(LocationStatus::NonCodeReference); - } - if reference.provenance_status.as_deref() != Some("VERIFIED_REPOSITORY_READ") { - return Err(LocationStatus::UnverifiedProvenance); - } - let commit = reference - .commit_sha - .as_deref() - .ok_or(LocationStatus::CommitUnavailable)?; - if !matches!(commit.len(), 40 | 64) || !commit.bytes().all(|byte| byte.is_ascii_hexdigit()) { - return Err(LocationStatus::InvalidCommit); - } - if !commit.eq_ignore_ascii_case(head) { - return Err(LocationStatus::DifferentCommit); - } - let path = reference - .repository_path - .as_deref() - .filter(|path| valid_path(path)) - .ok_or(LocationStatus::InvalidPath)?; + let path = + source_evidence::primary_source_path(reference, head).map_err(|reason| match reason { + PrimarySourceExclusion::CompanionRepository => LocationStatus::CompanionRepository, + PrimarySourceExclusion::NonCodeReference => LocationStatus::NonCodeReference, + PrimarySourceExclusion::UnverifiedProvenance => LocationStatus::UnverifiedProvenance, + PrimarySourceExclusion::CommitUnavailable => LocationStatus::CommitUnavailable, + PrimarySourceExclusion::InvalidCommit => LocationStatus::InvalidCommit, + PrimarySourceExclusion::DifferentCommit => LocationStatus::DifferentCommit, + PrimarySourceExclusion::InvalidPath => LocationStatus::InvalidPath, + })?; let start = reference .start_line .filter(|&line| line > 0) @@ -647,14 +634,6 @@ fn code_location<'a>( Ok((path, start, end)) } -fn valid_path(path: &str) -> bool { - !path.split('/').any(|part| matches!(part, "" | "." | "..")) - && !path.chars().any(|ch| { - ch.is_control() - || matches!(ch, '\\' | ':' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') - }) -} - fn path_uri(path: &str) -> String { const HEX: &[u8; 16] = b"0123456789ABCDEF"; let mut uri = String::new(); diff --git a/src/source_evidence.rs b/src/source_evidence.rs new file mode 100644 index 0000000..2832696 --- /dev/null +++ b/src/source_evidence.rs @@ -0,0 +1,59 @@ +//! Shared eligibility rules for commit-pinned primary-repository source +//! evidence references. Used by both SARIF export and local evidence +//! inspection so neither presentation or inspection feature depends on the +//! other. + +use crate::model::EvidenceRef; + +/// Why an evidence reference does not identify a verified primary-repository +/// source file at the review's head commit. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum PrimarySourceExclusion { + CompanionRepository, + NonCodeReference, + UnverifiedProvenance, + CommitUnavailable, + InvalidCommit, + DifferentCommit, + InvalidPath, +} + +/// Validates that `reference` is a verified primary-repository file read at +/// `head` with a safe repository-relative path, returning that path. +pub(crate) fn primary_source_path<'a>( + reference: &'a EvidenceRef, + head: &str, +) -> Result<&'a str, PrimarySourceExclusion> { + if reference.kind == "companion_repository_file" || reference.companion_repository.is_some() { + return Err(PrimarySourceExclusion::CompanionRepository); + } + if reference.kind != "repository_file" { + return Err(PrimarySourceExclusion::NonCodeReference); + } + if reference.provenance_status.as_deref() != Some("VERIFIED_REPOSITORY_READ") { + return Err(PrimarySourceExclusion::UnverifiedProvenance); + } + let commit = reference + .commit_sha + .as_deref() + .ok_or(PrimarySourceExclusion::CommitUnavailable)?; + if !matches!(commit.len(), 40 | 64) || !commit.bytes().all(|byte| byte.is_ascii_hexdigit()) { + return Err(PrimarySourceExclusion::InvalidCommit); + } + if !commit.eq_ignore_ascii_case(head) { + return Err(PrimarySourceExclusion::DifferentCommit); + } + reference + .repository_path + .as_deref() + .filter(|path| valid_path(path)) + .ok_or(PrimarySourceExclusion::InvalidPath) +} + +fn valid_path(path: &str) -> bool { + !path.split('/').any(|part| matches!(part, "" | "." | "..")) + && !path.chars().any(|ch| { + ch.is_control() + || matches!(ch, '\\' | ':' | '\u{200e}' | '\u{200f}' | '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') + }) +} diff --git a/tests/evidence.rs b/tests/evidence.rs new file mode 100644 index 0000000..f87b762 --- /dev/null +++ b/tests/evidence.rs @@ -0,0 +1,737 @@ +//! End-to-end CLI integration tests for `proofline evidence inspect` against +//! mock HTTP review responses and real temporary Git repositories. + +use std::collections::BTreeMap; +use std::path::Path; +use std::process::{Output, Stdio}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::extract::{Path as AxumPath, Query, State}; +use axum::http::{HeaderMap, Method, StatusCode, Uri, header}; +use axum::response::{IntoResponse, Response}; +use axum::routing::any; +use axum::{Json, Router}; +use serde_json::{Value, json}; +use sha2::{Digest as _, Sha256}; +use tokio::process::Command; +use uuid::Uuid; + +const ORG: &str = "0190f3a0-0000-7000-8000-000000000001"; +const REPO_ID: &str = "0190f3a0-0000-7000-8000-000000000011"; +const OTHER_REPO_ID: &str = "0190f3a0-0000-7000-8000-000000000022"; +const REVIEW_ID: &str = "0190f3a0-0000-7000-8000-000000000033"; +const OTHER_REVIEW_ID: &str = "0190f3a0-0000-7000-8000-000000000034"; +const TOKEN: &str = "pld_evidencesynthetictoken"; + +#[derive(Clone)] +struct MockServer { + doc: Value, + requests: Arc>>, +} + +impl MockServer { + fn new(doc: Value) -> Self { + Self { + doc, + requests: Arc::default(), + } + } + + fn take_requests(&self) -> Vec<(Method, String)> { + std::mem::take(&mut *self.requests.lock().unwrap()) + } +} + +fn authorized(headers: &HeaderMap) -> bool { + let expected = format!("Bearer {TOKEN}"); + headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + == Some(expected.as_str()) +} + +async fn resolve_source( + State(srv): State, + AxumPath(org): AxumPath, + Query(q): Query>, + method: Method, + uri: Uri, + headers: HeaderMap, +) -> Response { + srv.requests + .lock() + .unwrap() + .push((method, uri.path().to_owned())); + if !authorized(&headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + if org == ORG && q.get("full_name").map(String::as_str) == Some("acme/service") { + return Json(json!({ "repository_id": REPO_ID })).into_response(); + } + StatusCode::NOT_FOUND.into_response() +} + +async fn get_review( + State(srv): State, + AxumPath((org, id)): AxumPath<(String, Uuid)>, + method: Method, + uri: Uri, + headers: HeaderMap, +) -> Response { + srv.requests + .lock() + .unwrap() + .push((method, uri.path().to_owned())); + if !authorized(&headers) { + return StatusCode::UNAUTHORIZED.into_response(); + } + if org == ORG && id.to_string() == REVIEW_ID { + return Json(srv.doc).into_response(); + } + StatusCode::NOT_FOUND.into_response() +} + +async fn serve(srv: MockServer) -> String { + let app = Router::new() + .route( + "/api/v1/organizations/{org}/review-repository-source", + any(resolve_source), + ) + .route("/api/v1/organizations/{org}/reviews/{id}", any(get_review)) + .with_state(srv); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, app).await.unwrap() }); + format!("http://{addr}") +} + +async fn run_cli(origin: &str, dir: &Path, args: &[&str]) -> Output { + tokio::time::timeout( + Duration::from_secs(15), + Command::new(env!("CARGO_BIN_EXE_proofline")) + .args(["--base-url", origin, "--org", ORG]) + .args(args) + .env("PROOFLINE_TOKEN", TOKEN) + .env("PROOFLINE_NO_UPDATE_CHECK", "1") + .current_dir(dir) + .kill_on_drop(true) + .output(), + ) + .await + .unwrap() + .unwrap() +} + +fn run_git(dir: &Path, args: &[&str]) -> String { + let out = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(args) + .output() + .unwrap(); + assert!(out.status.success(), "git {args:?}: {out:?}"); + String::from_utf8(out.stdout).unwrap() +} + +fn init_repo(dir: &Path, remote: &str, url: &str) { + run_git(dir, &["init", "-q", "-b", "main"]); + for (k, v) in [ + ("user.email", "dev@example.com"), + ("user.name", "dev"), + ("core.autocrlf", "false"), + ] { + run_git(dir, &["config", k, v]); + } + run_git(dir, &["remote", "add", remote, url]); +} + +fn hash_object(dir: &Path, bytes: &[u8]) -> String { + let mut child = std::process::Command::new("git") + .arg("-C") + .arg(dir) + .args(["hash-object", "-w", "--stdin"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + std::io::Write::write_all(child.stdin.as_mut().unwrap(), bytes).unwrap(); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + String::from_utf8(out.stdout).unwrap().trim().to_owned() +} + +fn clone_repo(origin: &Path, dest: &Path, flag: &str) { + let url = url::Url::from_file_path(origin).unwrap().to_string(); + let status = std::process::Command::new("git") + .args(["clone", "--quiet", flag, &url]) + .arg(dest) + .status() + .unwrap(); + assert!(status.success()); + run_git( + dest, + &[ + "remote", + "set-url", + "origin", + "https://github.com/acme/service.git", + ], + ); +} + +fn sha256_hex(bytes: &[u8]) -> String { + format!("{:x}", Sha256::digest(bytes)) +} + +fn expected_inspect_requests() -> Vec<(Method, String)> { + vec![ + ( + Method::GET, + format!("/api/v1/organizations/{ORG}/review-repository-source"), + ), + ( + Method::GET, + format!("/api/v1/organizations/{ORG}/reviews/{REVIEW_ID}"), + ), + ] +} + +fn by_label<'a>(doc: &'a Value, label: &str) -> &'a Value { + doc["references"] + .as_array() + .unwrap() + .iter() + .find(|item| item["label"] == label) + .unwrap_or_else(|| panic!("missing ref {label:?}")) +} + +fn assert_ref( + doc: &Value, + label: &str, + integrity: &str, + integrity_reason: Option<&str>, + local_head: &str, + local_head_reason: Option<&str>, +) { + let r = by_label(doc, label); + assert_eq!(r["integrity"], integrity, "{label}"); + assert_eq!(r["integrity_reason"].as_str(), integrity_reason, "{label}"); + assert_eq!(r["local_head"], local_head, "{label}"); + assert_eq!( + r["local_head_reason"].as_str(), + local_head_reason, + "{label}" + ); +} + +fn file_ref(label: &str, path: &str, commit: &str, digest: Option<&str>) -> Value { + json!({ + "kind": "repository_file", + "label": label, + "provenance_status": "VERIFIED_REPOSITORY_READ", + "repository_path": path, + "start_line": 1, + "end_line": 2, + "file_sha256": digest, + "commit_sha": commit, + "companion_repository": null, + }) +} + +fn base_review(head: &str, code_refs: Vec, env_refs: Vec) -> Value { + let assessments = if env_refs.is_empty() { + json!([]) + } else { + json!([{ + "id": "0190f3a0-0000-7000-8000-000000000055", + "environment_display_name": "prod\u{1b}[31m\u{202e}", + "status": "COMPLETED", + "findings": [{ + "id": "0190f3a0-0000-7000-8000-000000000062", + "finding_fingerprint": null, + "severity": "SERIOUS", + "risk_domain": "application_security", + "claim": "synthetic env finding", + "impact": "synthetic impact", + "lifecycle_state": "NEW", + "remediation": null, + "evidence_refs": env_refs, + }], + "checks": { "receipt_recorded": true, "status": "READY", "families": [] }, + "incompleteness_kind": null, + "reason_codes": null, + "release_evidence_gap": null, + }]) + }; + json!({ + "id": REVIEW_ID, + "kind": "PULL_REQUEST", + "status": "COMPLETED", + "repository_id": REPO_ID, + "repository_full_name": "acme/service", + "pull_request_number": 7, + "run_number": 1, + "base_commit_sha": "0".repeat(40), + "head_commit_sha": head, + "assessment_count": assessments.as_array().unwrap().len(), + "assessments": assessments, + "code_assessment": { + "id": "0190f3a0-0000-7000-8000-000000000044", + "status": "COMPLETED", + "base_commit_sha": "0".repeat(40), + "head_commit_sha": head, + "findings": [{ + "id": "0190f3a0-0000-7000-8000-000000000061", + "finding_fingerprint": null, + "severity": "WARNING", + "risk_domain": "authorization", + "claim": "missing tenant filter", + "impact": "cross-tenant data access", + "lifecycle_state": "NEW", + "remediation": null, + "evidence_refs": code_refs, + }], + "incompleteness_kind": null, + "reason_codes": null, + }, + "subjects": [], + }) +} + +#[tokio::test] +async fn inspect_reports_integrity_and_local_head_states_for_code_lane() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir, "origin", "https://github.com/acme/service.git"); + + let (v1, stable, removed, linked, sub_init) = ( + b"def f():\r\n pass\r\n", + b"stable = True\n", + b"tmp = 1\n", + b"reg = 1\n", + b"sub = 1\n", + ); + std::fs::create_dir_all(dir.join("ledger")).unwrap(); + for (p, b) in [ + ("ledger/service.py", v1.as_slice()), + ("ledger/stable [1].py", stable.as_slice()), + ("ledger/removed.py", removed.as_slice()), + ("ledger/now_link.py", linked.as_slice()), + ("ledger/now_sub", sub_init.as_slice()), + ] { + std::fs::write(dir.join(p), b).unwrap(); + } + run_git(dir, &["add", "."]); + run_git(dir, &["commit", "-qm", "reviewed"]); + let rev = run_git(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + + // Establish an actual git replace spoofing object against ledger/service.py. + let blob_oid = run_git(dir, &["rev-parse", &format!("{rev}:ledger/service.py")]) + .trim() + .to_owned(); + let spoof_oid = hash_object(dir, b"spoofed"); + run_git(dir, &["replace", &blob_oid, &spoof_oid]); + + std::fs::write( + dir.join("ledger/service.py"), + b"def f():\r\n return 42\r\n", + ) + .unwrap(); + run_git(dir, &["rm", "-q", "ledger/removed.py", "ledger/now_sub"]); + #[cfg(unix)] + { + std::fs::remove_file(dir.join("ledger/now_link.py")).unwrap(); + std::os::unix::fs::symlink("service.py", dir.join("ledger/now_link.py")).unwrap(); + } + let sub = dir.join("ledger/now_sub"); + std::fs::create_dir_all(&sub).unwrap(); + init_repo(&sub, "origin", "https://github.com/acme/sub.git"); + std::fs::write(sub.join("inner.py"), "x = 1\n").unwrap(); + run_git(&sub, &["add", "."]); + run_git(&sub, &["commit", "-qm", "sub"]); + run_git( + dir, + &[ + "add", + "ledger/service.py", + "ledger/now_link.py", + "ledger/now_sub", + ], + ); + run_git(dir, &["commit", "-qm", "evolved"]); + let local_head = run_git(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + + // Dirty both staged index and unstaged working tree on ledger/stable [1].py. + std::fs::write(dir.join("ledger/stable [1].py"), b"staged\n").unwrap(); + run_git(dir, &["add", "ledger/stable [1].py"]); + std::fs::write(dir.join("ledger/stable [1].py"), b"unstaged\n").unwrap(); + + let (s_v1, s_st, s_rm, s_ln, s_sb) = ( + sha256_hex(v1), + sha256_hex(stable), + sha256_hex(removed), + sha256_hex(linked), + sha256_hex(sub_init), + ); + let mk = |l, p, d| file_ref(l, p, &rev, d); + let bad = "a".repeat(64); + let code_refs = vec![ + mk("svc:match", "ledger/service.py", Some(&s_v1)), + mk("svc:contradict", "ledger/service.py", Some(&bad)), + mk("stable:nodigest", "ledger/stable [1].py", None), + mk("rm:match", "ledger/removed.py", Some(&s_rm)), + mk("link:head", "ledger/now_link.py", Some(&s_ln)), + mk("sub:head", "ledger/now_sub", Some(&s_sb)), + mk("miss:rev", "ledger/never_existed.py", Some(&s_st)), + mk("stable:bad", "ledger/stable [1].py", Some("bad")), + ]; + + let server = MockServer::new(base_review(&rev, code_refs, Vec::new())); + let origin = serve(server.clone()).await; + + let out = run_cli(&origin, dir, &["evidence", "inspect", REVIEW_ID, "--json"]).await; + assert_eq!(out.status.code(), Some(0), "{out:?}"); + assert_eq!(server.take_requests(), expected_inspect_requests()); + + let doc: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(doc["schema"], "proofline.evidence-inspection.v1"); + assert_eq!(doc["reviewed_head_sha"], rev); + assert_eq!(doc["local_head_sha"], local_head); + + let s = &doc["summary"]; + assert_eq!(s["total_references"], 8); + assert_eq!(s["eligible_references"], 8); + assert_eq!(s["outside_scope_references"], 0); + assert_eq!(s["unique_files"], 6); + assert_eq!(s["unique_files_changed_at_local_head"], 1); + assert_eq!(s["unique_files_absent_at_local_head"], 1); + assert_eq!(s["integrity"]["matched"], 4); + assert_eq!(s["integrity"]["mismatch"], 1); + assert_eq!(s["integrity"]["not_recorded"], 1); + assert_eq!(s["integrity"]["unavailable"], 2); + + assert_ref(&doc, "svc:match", "matched", None, "changed", None); + assert_ref(&doc, "svc:contradict", "mismatch", None, "changed", None); + assert_ref( + &doc, + "stable:nodigest", + "not_recorded", + None, + "unchanged", + None, + ); + assert_ref(&doc, "rm:match", "matched", None, "absent", None); + assert_ref( + &doc, + "sub:head", + "matched", + None, + "unavailable", + Some("unsupported_object_type"), + ); + assert_ref( + &doc, + "miss:rev", + "unavailable", + Some("reviewed_path_absent"), + "unavailable", + Some("reviewed_path_absent"), + ); + assert_ref( + &doc, + "stable:bad", + "unavailable", + Some("malformed_recorded_digest"), + "unchanged", + None, + ); + #[cfg(unix)] + assert_ref( + &doc, + "link:head", + "matched", + None, + "unavailable", + Some("unsupported_object_type"), + ); +} + +#[tokio::test] +async fn inspect_handles_env_lane_exclusions_and_sanitizes_terminal_output() { + let repo = tempfile::tempdir().unwrap(); + let dir = repo.path(); + init_repo(dir, "origin", "https://github.com/acme/service.git"); + + let stable = b"stable = True\n"; + std::fs::create_dir_all(dir.join("ledger")).unwrap(); + std::fs::write(dir.join("ledger/stable [1].py"), stable).unwrap(); + run_git(dir, &["add", "."]); + run_git(dir, &["commit", "-qm", "reviewed"]); + let rev = run_git(dir, &["rev-parse", "HEAD"]).trim().to_owned(); + + let s_st = sha256_hex(stable); + let mk = |l, p, d| file_ref(l, p, &rev, d); + + let mut world = file_ref("db\u{1b}[2J\u{202e}cluster", "", &rev, None); + world["kind"] = json!("world_entity"); + world["provenance_status"] = json!("PINNED_WORLD_ENTITY"); + world["repository_path"] = Value::Null; + world["commit_sha"] = Value::Null; + + let mut comp = mk("comp:ref", "infra/main.tf", None); + comp["kind"] = json!("companion_repository_file"); + comp["companion_repository"] = json!("acme/infra"); + + let mut unv = mk("unv:ref", "ledger/stable [1].py", None); + unv["provenance_status"] = json!("LEGACY_UNSTRUCTURED"); + + let code_refs = vec![mk("code:stable", "ledger/stable [1].py", Some(&s_st))]; + let env_refs = vec![ + mk("env:stable", "ledger/stable [1].py", Some(&s_st)), + world, + comp, + unv, + file_ref("diff:commit", "ledger/stable [1].py", &"1".repeat(40), None), + mk("bad:path", "../etc/passwd", None), + ]; + + let server = MockServer::new(base_review(&rev, code_refs, env_refs)); + let origin = serve(server.clone()).await; + + let json_out = run_cli(&origin, dir, &["evidence", "inspect", REVIEW_ID, "--json"]).await; + assert_eq!(json_out.status.code(), Some(0), "{json_out:?}"); + assert_eq!(server.take_requests(), expected_inspect_requests()); + + let doc: Value = serde_json::from_slice(&json_out.stdout).unwrap(); + assert_eq!(doc["summary"]["total_references"], 7); + assert_eq!(doc["summary"]["eligible_references"], 2); + assert_eq!(doc["summary"]["outside_scope_references"], 5); + assert_eq!(doc["summary"]["unique_files"], 1); + assert_eq!(by_label(&doc, "code:stable")["lane"], "CODE"); + assert_eq!(by_label(&doc, "env:stable")["lane"], "ENV"); + assert_ref(&doc, "code:stable", "matched", None, "unchanged", None); + assert_ref(&doc, "env:stable", "matched", None, "unchanged", None); + + for (label, reason) in [ + ("db\u{1b}[2J\u{202e}cluster", "non_repository_file"), + ("comp:ref", "companion_repository"), + ("unv:ref", "unverified_provenance"), + ("diff:commit", "different_commit"), + ("bad:path", "invalid_path"), + ] { + assert_ref( + &doc, + label, + "outside_scope", + Some(reason), + "outside_scope", + Some(reason), + ); + } + + let text_out = run_cli(&origin, dir, &["evidence", "inspect", REVIEW_ID]).await; + assert_eq!(text_out.status.code(), Some(0)); + assert_eq!(server.take_requests(), expected_inspect_requests()); + let text = String::from_utf8(text_out.stdout).unwrap(); + assert!( + text.contains("2 eligible references inspected (1 unique source file)"), + "{text}" + ); + assert!(text.contains("5 references outside scope"), "{text}"); + assert!( + text.contains("Uncommitted changes are not inspected."), + "{text}" + ); + assert!( + text.contains("do not establish finding validity."), + "{text}" + ); + assert!(!text.contains('\u{1b}') && !text.contains('\u{202e}') && !text.contains(TOKEN)); +} + +#[tokio::test] +async fn inspect_handles_stale_code_assessment_and_shallow_clone() { + let root = tempfile::tempdir().unwrap(); + let remote = root.path().join("remote"); + std::fs::create_dir_all(&remote).unwrap(); + init_repo(&remote, "origin", "https://github.com/acme/service.git"); + let v1 = b"v1 = 1\n"; + std::fs::write(remote.join("keep.py"), v1).unwrap(); + std::fs::write(remote.join("gone.py"), b"gone\n").unwrap(); + run_git(&remote, &["add", "."]); + run_git(&remote, &["commit", "-qm", "reviewed"]); + let rev = run_git(&remote, &["rev-parse", "HEAD"]).trim().to_owned(); + + // Stale code_assessment (mismatched head_commit_sha) is excluded with a warning. + let s1 = sha256_hex(v1); + let mut stale = base_review( + &rev, + vec![file_ref("keep", "keep.py", &rev, Some(&s1))], + Vec::new(), + ); + stale["code_assessment"]["head_commit_sha"] = json!("9".repeat(40)); + let stale_origin = serve(MockServer::new(stale)).await; + + let out = run_cli( + &stale_origin, + &remote, + &["evidence", "inspect", REVIEW_ID, "--json"], + ) + .await; + assert_eq!(out.status.code(), Some(0)); + let doc: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(doc["summary"]["eligible_references"], 0); + assert_eq!(doc["warnings"][0]["code"], "CODE_ASSESSMENT_UNAVAILABLE"); + + let text = String::from_utf8( + run_cli(&stale_origin, &remote, &["evidence", "inspect", REVIEW_ID]) + .await + .stdout, + ) + .unwrap(); + assert!(text.contains("0 eligible source references inspected") && !text.contains("matched")); + + // Shallow clone missing the reviewed commit reports unavailable for local_head. + std::fs::write(remote.join("keep.py"), b"v2 = 2\n").unwrap(); + run_git(&remote, &["rm", "-q", "gone.py"]); + run_git(&remote, &["add", "keep.py"]); + run_git(&remote, &["commit", "-qm", "latest"]); + + let shallow = root.path().join("shallow"); + clone_repo(&remote, &shallow, "--depth=1"); + + let refs = vec![ + file_ref("keep", "keep.py", &rev, Some(&s1)), + file_ref("gone", "gone.py", &rev, None), + ]; + let origin = serve(MockServer::new(base_review(&rev, refs, Vec::new()))).await; + let out = run_cli( + &origin, + &shallow, + &["evidence", "inspect", REVIEW_ID, "--json"], + ) + .await; + assert_eq!(out.status.code(), Some(0)); + let doc: Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_ref( + &doc, + "keep", + "unavailable", + Some("reviewed_commit_missing"), + "unavailable", + Some("reviewed_commit_missing"), + ); + assert_ref( + &doc, + "gone", + "not_recorded", + None, + "unavailable", + Some("reviewed_commit_missing"), + ); +} + +#[tokio::test] +async fn inspect_enforces_identity_binding_preconditions_partial_clones_and_remote_sanitization() { + let root = tempfile::tempdir().unwrap(); + let repo = root.path().join("repo"); + std::fs::create_dir_all(&repo).unwrap(); + init_repo(&repo, "upstream", "https://github.com/acme/service.git"); + run_git(&repo, &["config", "uploadpack.allowFilter", "true"]); + let body = b"print(1)\n"; + std::fs::write(repo.join("a.py"), body).unwrap(); + run_git(&repo, &["add", "a.py"]); + run_git(&repo, &["commit", "-qm", "init"]); + let head = run_git(&repo, &["rev-parse", "HEAD"]).trim().to_owned(); + + let s = sha256_hex(body); + let ok_review = base_review( + &head, + vec![file_ref("a", "a.py", &head, Some(&s))], + Vec::new(), + ); + let ok_server = MockServer::new(ok_review.clone()); + let ok_origin = serve(ok_server.clone()).await; + + let ok_out = run_cli( + &ok_origin, + &repo, + &[ + "evidence", "inspect", REVIEW_ID, "--remote", "upstream", "--json", + ], + ) + .await; + assert_eq!(ok_out.status.code(), Some(0)); + assert_eq!(ok_server.take_requests(), expected_inspect_requests()); + + // `--repo` override is rejected before any HTTP call. + let bad_flag = run_cli( + &ok_origin, + &repo, + &["evidence", "inspect", REVIEW_ID, "--repo", "acme/service"], + ) + .await; + assert_eq!(bad_flag.status.code(), Some(1)); + assert!(ok_server.take_requests().is_empty()); + + // Terminal control characters in a Git error are sanitized. + let bad_rem = run_cli( + &ok_origin, + &repo, + &[ + "evidence", + "inspect", + REVIEW_ID, + "--remote", + "bad\u{1b}[31mrem", + ], + ) + .await; + assert_eq!(bad_rem.status.code(), Some(1)); + assert!(!String::from_utf8_lossy(&bad_rem.stderr).contains('\u{1b}')); + + for (field, value, expected) in [ + ("id", json!(OTHER_REVIEW_ID), OTHER_REVIEW_ID), + ( + "repository_id", + Value::Null, + "records no repository identity", + ), + ("kind", json!("PATCH"), "pull-request reviews"), + ( + "head_commit_sha", + json!("not-a-sha"), + "full head commit SHA", + ), + ] { + let mut doc = ok_review.clone(); + doc[field] = value; + let origin = serve(MockServer::new(doc)).await; + let out = run_cli( + &origin, + &repo, + &["evidence", "inspect", REVIEW_ID, "--remote", "upstream"], + ) + .await; + assert_eq!(out.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&out.stderr).contains(expected)); + } + + // Real partial clone tests both repo mismatch before Git inspection and partial-clone refusal. + let partial = root.path().join("partial"); + clone_repo(&repo, &partial, "--filter=blob:none"); + + let mut wrong_repo = ok_review; + wrong_repo["repository_id"] = json!(OTHER_REPO_ID); + let wrong_origin = serve(MockServer::new(wrong_repo)).await; + let mismatch = run_cli(&wrong_origin, &partial, &["evidence", "inspect", REVIEW_ID]).await; + assert_eq!(mismatch.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&mismatch.stderr).contains("belongs to repository")); + + let partial_out = run_cli(&ok_origin, &partial, &["evidence", "inspect", REVIEW_ID]).await; + assert_eq!(partial_out.status.code(), Some(1)); + assert!( + String::from_utf8_lossy(&partial_out.stderr).contains("partial or promisor Git clones") + ); +}