//! `lunehub hook pre-receive`: the hub's secret check (P3), run by Git before it accepts any change. use crate::db; use anyhow::{Context, Result}; use lune_core::git2::{self, Oid, Repository}; use lune_core::secrets; use std::io::BufRead; use std::path::PathBuf; /// Returns false (refuse) if any new history entry adds a line that looks like a secret. pub fn pre_receive() -> Result { // Open with Git's environment so we can see the incoming (still quarantined) objects. let repo = Repository::open_from_env().context("can't open the vault")?; let data = PathBuf::from(std::env::var("LUNE_HUB_DATA").context("LUNE_HUB_DATA not set")?); let vault_id: i64 = repo .path() .file_name() .and_then(|n| n.to_str()) .and_then(|n| n.strip_suffix(".git")) .and_then(|n| n.parse().ok()) .context("unexpected vault folder")?; let conn = db::open(&data)?; let allowed = db::not_secrets(&conn, vault_id)?; let mut found = vec![]; for line in std::io::stdin().lock().lines() { let line = line?; let mut parts = line.split_whitespace(); let (Some(_old), Some(new), Some(_name)) = (parts.next(), parts.next(), parts.next()) else { continue }; let new = Oid::from_str(new)?; if new.is_zero() { continue; } let mut walk = repo.revwalk()?; walk.push(new)?; for r in repo.references()? { if let Some(target) = r?.target() { walk.hide(target)?; } } for id in walk { found.extend(check_commit(&repo, &repo.find_commit(id?)?, &allowed)?); } } if found.is_empty() { return Ok(true); } for f in &found { eprintln!("lune: {f}"); } let vault: String = conn.query_row("SELECT name FROM vaults WHERE id = ?1", [vault_id], |r| r.get(0)).unwrap_or_default(); let actor = std::env::var("LUNE_ACTOR").unwrap_or_else(|_| "unknown device".into()); db::log(&conn, &actor, "change refused", &format!("{vault}: possible secret — {}", found.join("; ")))?; Ok(false) } /// Lines this history entry adds (relative to all its parents) that look like secrets. fn check_commit(repo: &Repository, commit: &git2::Commit, allowed: &std::collections::HashSet) -> Result> { let parents: Vec = commit.parents().map(|p| p.tree()).collect::>()?; let tree = commit.tree()?; let first = parents.first(); let diff = repo.diff_tree_to_tree(first, Some(&tree), None)?; let mut out = vec![]; for delta in diff.deltas() { if !matches!(delta.status(), git2::Delta::Added | git2::Delta::Modified) { continue; } let Some(path) = delta.new_file().path() else { continue }; let new = repo.find_blob(delta.new_file().id())?; // A line already present in any parent isn't new here. let mut old = Vec::new(); for p in &parents { if let Ok(e) = p.get_path(path) && let Ok(b) = repo.find_blob(e.id()) { old.extend_from_slice(b.content()); old.push(b'\n'); } } let old = if old.is_empty() { None } else { Some(old.as_slice()) }; for hit in secrets::scan_bytes(new.content(), old, allowed) { out.push(format!("{} line {}: possible {}", path.display(), hit.line, hit.rule)); } } Ok(out) }