blob: b6c1e1088c4c30a30c2f74a2afc9b51c4b0825ea [file]
// Copyright 2026 The Fuchsia Authors
//
// Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0
// <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT
// license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
// This file may not be copied, modified, or distributed except according to
// those terms.
//! Build-freshness status and fail-closed executable Git provenance checks.
use std::{
env,
path::Path,
process::Command,
time::{SystemTime, UNIX_EPOCH},
};
use serde::{Deserialize, Serialize};
use super::normalize_repo_slug;
/// Build-freshness gate enforced locally before telemetry emission.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuildFreshness {
VerifiedAtHead,
FailedOrOom,
TimedOut,
Stale,
NotRun,
}
impl BuildFreshness {
pub fn as_str(self) -> &'static str {
match self {
Self::VerifiedAtHead => "verified_at_head",
Self::FailedOrOom => "failed_or_oom",
Self::TimedOut => "timed_out",
Self::Stale => "stale",
Self::NotRun => "not_run",
}
}
pub fn parse(s: &str) -> Option<Self> {
match s {
"verified_at_head" => Some(Self::VerifiedAtHead),
"failed_or_oom" => Some(Self::FailedOrOom),
"timed_out" => Some(Self::TimedOut),
"stale" => Some(Self::Stale),
"not_run" => Some(Self::NotRun),
_ => None,
}
}
}
/// Metadata context for emitting `anneal-itree-semantic-detail/v1` and
/// `anneal-known-bug/v1` records.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TelemetryContext {
pub repo: String,
pub branch: String,
pub branch_scope: String,
pub exposed_on_main: bool,
pub commit_sha: String,
pub commit_unix_ts: i64,
pub environment_profile: String,
pub source_url: String,
pub profile_v2: bool,
pub build_freshness_override: Option<BuildFreshness>,
pub build_exit_code_override: Option<i64>,
#[serde(default)]
pub head_provenance_verified: bool,
#[serde(default)]
pub discovered_head_sha: Option<String>,
}
impl TelemetryContext {
/// Auto-discover Git repository/branch/HEAD metadata under `anneal_root`
/// with fail-safe fallbacks when executed outside a git checkout, and
/// verify whether the running executable is provably up-to-date with clean
/// `HEAD`.
pub fn discover(anneal_root: &Path) -> Self {
let origin = run_git_trimmed(anneal_root, &["remote", "get-url", "origin"])
.unwrap_or_else(|| "google/zerocopy".to_string());
let repo = normalize_repo_slug(&origin);
let branch = run_git_trimmed(anneal_root, &["rev-parse", "--abbrev-ref", "HEAD"])
.unwrap_or_else(|| "unknown".to_string());
let discovered_head_sha = run_git_trimmed(anneal_root, &["rev-parse", "--verify", "HEAD"])
.filter(|s| is_valid_git_commit_sha(s));
let commit_sha = discovered_head_sha.clone().unwrap_or_else(|| "0".repeat(40));
let commit_unix_ts = run_git_trimmed(anneal_root, &["show", "-s", "--format=%ct", "HEAD"])
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or_else(|| {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
});
let cur_exe = env::current_exe().ok();
let head_provenance_verified = verify_head_build_provenance_with(
anneal_root,
discovered_head_sha.as_deref(),
Path::new(env!("CARGO_MANIFEST_DIR")),
cur_exe.as_deref(),
None,
None,
);
let is_main = branch == "main";
Self {
repo,
branch: branch.clone(),
branch_scope: if is_main { "main".to_string() } else { "unstable_only".to_string() },
exposed_on_main: is_main,
commit_sha,
commit_unix_ts,
environment_profile: "local-itree-diff".to_string(),
source_url: String::new(),
profile_v2: false,
build_freshness_override: None,
build_exit_code_override: None,
head_provenance_verified,
discovered_head_sha,
}
}
/// Return `true` only when executable build provenance was verified on a
/// clean tree AND `self.commit_sha` still matches `discovered_head_sha`.
pub fn is_verified_for_commit(&self) -> bool {
self.head_provenance_verified
&& is_valid_git_commit_sha(&self.commit_sha)
&& self
.discovered_head_sha
.as_deref()
.is_some_and(|head| head.eq_ignore_ascii_case(&self.commit_sha))
}
}
pub(crate) fn is_40_hex_sha(s: &str) -> bool {
s.len() == 40 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
pub(crate) fn is_valid_git_commit_sha(s: &str) -> bool {
is_40_hex_sha(s) && !s.bytes().all(|b| b == b'0')
}
fn run_git_raw(cwd: &Path, args: &[&str]) -> Option<Vec<u8>> {
let mut cmd = Command::new("git");
for var in [
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
] {
cmd.env_remove(var);
}
let out = cmd
.env("GIT_TERMINAL_PROMPT", "0")
.arg("--no-optional-locks")
.arg("-C")
.arg(cwd)
.args(args)
.output()
.ok()?;
if !out.status.success() {
return None;
}
Some(out.stdout)
}
fn run_git_trimmed(cwd: &Path, args: &[&str]) -> Option<String> {
let raw = run_git_raw(cwd, args)?;
let s = String::from_utf8_lossy(&raw).trim().to_string();
if s.is_empty() { None } else { Some(s) }
}
/// Fail-closed check for executable build provenance against clean `HEAD` at
/// `anneal_root`.
///
/// Standalone `anneal-itree-diff` binaries cannot `build.rs`-embed or
/// cryptographically authenticate their own binary contents against a clean Git
/// commit (`cargo_boundary` forbids `build.rs` and unauthenticated compile-time
/// env flags like `ANNEAL_BUILD_COMMIT_SHA` or mtimes can be forged on a
/// dirty build later restored cleanly). Therefore this self-check always
/// fails closed (`false`) so unauthenticated local builds emit
/// `build_freshness = "stale"` (`overall_status = "UNVERIFIED"`), and
/// `"verified_at_head"` requires an explicit trusted orchestrator provenance
/// context.
pub fn verify_head_build_provenance_with(
anneal_root: &Path,
discovered_head_sha: Option<&str>,
_compile_manifest_dir: &Path,
_current_exe: Option<&Path>,
_build_commit_sha_env: Option<&str>,
_build_tree_clean_env: Option<&str>,
) -> bool {
let Some(_head_sha) = discovered_head_sha.filter(|s| is_valid_git_commit_sha(s)) else {
return false;
};
let Some(_status_out) =
run_git_raw(anneal_root, &["status", "--porcelain", "--untracked-files=all"])
else {
return false;
};
false
}