Milestone 2: secret check and runaway guard
Notes with a likely secret on a new line are held on the device (own short rule list, per SPEC §8); `lunesync held pointer|not-secret` resolves them. Bursts removing or rewriting a big part of the vault are saved but not shared until `lunesync held share|undo`. Incoming edits to a held note land in place with the held version kept beside it. Adds `tidy show` and SPEC §6 detail for M2. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
98
core/src/guard.rs
Normal file
98
core/src/guard.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
//! Runaway guard (S6): a burst that removes or rewrites a big part of the vault is held for the owner.
|
||||
|
||||
use anyhow::Result;
|
||||
use git2::{DiffFindOptions, Patch, Repository, Tree, TreeWalkMode, TreeWalkResult};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::Path;
|
||||
|
||||
/// A saved burst that isn't shared until the owner says so.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HeldBurst {
|
||||
pub id: String,
|
||||
pub message: String,
|
||||
pub removed: usize,
|
||||
pub rewritten: usize,
|
||||
pub total: usize,
|
||||
pub at: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct Damage {
|
||||
pub removed: usize,
|
||||
pub rewritten: usize,
|
||||
/// Notes in the vault before the burst.
|
||||
pub total: usize,
|
||||
}
|
||||
|
||||
impl Damage {
|
||||
pub fn is_runaway(&self) -> bool {
|
||||
let n = self.removed + self.rewritten;
|
||||
n >= 50 || (n >= 5 && n * 5 >= self.total)
|
||||
}
|
||||
}
|
||||
|
||||
/// Counts notes removed and heavily rewritten (more than half their lines gone). Renames don't count.
|
||||
pub fn assess(repo: &Repository, old: &Tree, new: &Tree) -> Result<Damage> {
|
||||
let mut diff = repo.diff_tree_to_tree(Some(old), Some(new), None)?;
|
||||
diff.find_similar(Some(DiffFindOptions::new().renames(true)))?;
|
||||
let mut d = Damage::default();
|
||||
old.walk(TreeWalkMode::PreOrder, |_, e| {
|
||||
if e.kind() == Some(git2::ObjectType::Blob) {
|
||||
d.total += 1;
|
||||
}
|
||||
TreeWalkResult::Ok
|
||||
})?;
|
||||
for delta in diff.deltas() {
|
||||
match delta.status() {
|
||||
git2::Delta::Deleted => d.removed += 1,
|
||||
git2::Delta::Modified => {
|
||||
let before = repo.find_blob(delta.old_file().id())?;
|
||||
let after = repo.find_blob(delta.new_file().id())?;
|
||||
if before.is_binary() || after.is_binary() {
|
||||
d.rewritten += 1;
|
||||
continue;
|
||||
}
|
||||
let lines = before.content().split(|&b| b == b'\n').filter(|l| !l.is_empty()).count();
|
||||
let patch = Patch::from_blobs(&before, None, &after, None, None)?;
|
||||
let (_, _, gone) = patch.line_stats()?;
|
||||
if lines > 0 && gone * 2 > lines {
|
||||
d.rewritten += 1;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
fn path(git_dir: &Path) -> std::path::PathBuf {
|
||||
crate::state::lune_dir(git_dir).join("held.json")
|
||||
}
|
||||
|
||||
pub fn load(git_dir: &Path) -> Vec<HeldBurst> {
|
||||
std::fs::read_to_string(path(git_dir)).ok().and_then(|t| serde_json::from_str(&t).ok()).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn save(git_dir: &Path, held: &[HeldBurst]) -> Result<()> {
|
||||
let p = path(git_dir);
|
||||
std::fs::create_dir_all(p.parent().unwrap())?;
|
||||
let tmp = p.with_extension("json.tmp");
|
||||
std::fs::write(&tmp, serde_json::to_vec_pretty(held)?)?;
|
||||
std::fs::rename(tmp, p)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn thresholds() {
|
||||
let d = |removed, rewritten, total| Damage { removed, rewritten, total };
|
||||
assert!(d(50, 0, 10_000).is_runaway());
|
||||
assert!(d(10, 10, 100).is_runaway());
|
||||
assert!(!d(19, 0, 100).is_runaway());
|
||||
assert!(!d(4, 0, 10).is_runaway(), "tiny vaults need at least 5 notes touched");
|
||||
assert!(d(5, 0, 10).is_runaway());
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
pub use git2;
|
||||
|
||||
pub mod config;
|
||||
pub mod guard;
|
||||
pub mod names;
|
||||
pub mod remote;
|
||||
pub mod runner;
|
||||
pub mod secrets;
|
||||
pub mod state;
|
||||
pub mod tidy;
|
||||
pub mod vault;
|
||||
|
||||
@@ -91,6 +91,8 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
||||
let mut sync_at = Instant::now();
|
||||
let mut backoff = poll;
|
||||
let mut was_waiting = false;
|
||||
let mut was_holding = false;
|
||||
let mut announced: HashSet<String> = HashSet::new();
|
||||
loop {
|
||||
let first = rx.recv_timeout(Duration::from_millis(250));
|
||||
for ev in first.into_iter().chain(rx.try_iter()) {
|
||||
@@ -116,11 +118,39 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
||||
match vault.save_changes(None, &skip) {
|
||||
Ok(Some(saved)) => {
|
||||
say(&format!("saved: {}", saved.message));
|
||||
if let Some(d) = saved.held {
|
||||
say(&format!(
|
||||
"HELD: this change removes or rewrites {} of {} notes, so it stays on this device. \
|
||||
`lunesync held share` to send it anyway, `lunesync held undo` to bring everything back",
|
||||
d.removed + d.rewritten,
|
||||
d.total
|
||||
));
|
||||
}
|
||||
sync_at = now;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => say(&format!("couldn't save changes: {e:#}")),
|
||||
}
|
||||
match vault.secret_holds() {
|
||||
Ok(notes) => {
|
||||
let mut current = HashSet::new();
|
||||
for n in notes {
|
||||
for h in n.hits {
|
||||
let key = format!("{}:{}", n.path, h.line_hash);
|
||||
if !announced.contains(&key) {
|
||||
say(&format!(
|
||||
"HELD: {} line {} has a possible {} ({}), so this note isn't shared. \
|
||||
`lunesync held` to replace it with a pointer or mark it not a secret",
|
||||
n.path, h.line, h.rule, h.hint
|
||||
));
|
||||
}
|
||||
current.insert(key);
|
||||
}
|
||||
}
|
||||
announced = current;
|
||||
}
|
||||
Err(e) => say(&format!("couldn't run the secret check: {e:#}")),
|
||||
}
|
||||
}
|
||||
|
||||
if Instant::now() >= sync_at {
|
||||
@@ -131,9 +161,13 @@ pub fn run(cfg: &VaultConfig, label: &str, poll: Duration, timing: Timing, log:
|
||||
match result {
|
||||
Ok(report) => {
|
||||
st.last_error = None;
|
||||
if !report.waiting_for_local_edits {
|
||||
if !report.waiting_for_local_edits && !report.holding {
|
||||
st.last_synced = st.last_attempt;
|
||||
}
|
||||
if report.holding && !was_holding {
|
||||
say("not sharing anything from this device while a big change is held");
|
||||
}
|
||||
was_holding = report.holding;
|
||||
if report.waiting_for_local_edits && !was_waiting {
|
||||
say("new changes are waiting until your current edits settle");
|
||||
}
|
||||
@@ -180,6 +214,9 @@ fn print_report(r: &SyncReport, say: &dyn Fn(&str)) {
|
||||
for (note, copy) in &r.kept_both {
|
||||
say(&format!("{note} was changed in two places — kept both, yours is in \"{copy}\""));
|
||||
}
|
||||
for (note, copy) in &r.set_aside {
|
||||
say(&format!("{note} changed elsewhere while held here — your held version is now \"{copy}\""));
|
||||
}
|
||||
for (old, new) in &r.case_renamed {
|
||||
say(&format!("{old} clashed with another name differing only by case — renamed to {new}"));
|
||||
}
|
||||
|
||||
217
core/src/secrets.rs
Normal file
217
core/src/secrets.rs
Normal file
@@ -0,0 +1,217 @@
|
||||
//! The secret check (P2): our own short list of high-confidence rules, run before a change becomes history.
|
||||
|
||||
use anyhow::Result;
|
||||
use regex::Regex;
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
struct Rule {
|
||||
name: &'static str,
|
||||
re: Regex,
|
||||
/// Extra test on the matched secret, for rules that would otherwise catch ordinary words.
|
||||
looks_random: bool,
|
||||
}
|
||||
|
||||
static RULES: LazyLock<Vec<Rule>> = LazyLock::new(|| {
|
||||
let r = |name, pattern: &str, looks_random| Rule { name, re: Regex::new(pattern).unwrap(), looks_random };
|
||||
vec![
|
||||
r("private key", r"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----(?:.*?-----END [A-Z0-9 ]*PRIVATE KEY(?: BLOCK)?-----|.*)", false),
|
||||
r("AWS access key", r"\b((?:AKIA|ASIA|ABIA|ACCA)[0-9A-Z]{16})\b", false),
|
||||
r("AWS secret key", r#"(?i)aws.{0,20}(?:secret|key).{0,20}?[:=]\s*["']?([A-Za-z0-9/+=]{40})(?:[^A-Za-z0-9/+=]|$)"#, false),
|
||||
r("GitHub token", r"\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})", false),
|
||||
r("GitLab token", r"\b(glpat-[A-Za-z0-9_\-]{20,})", false),
|
||||
r("Slack token", r"\b(xox[baprs]-[A-Za-z0-9-]{10,})", false),
|
||||
r("Slack webhook", r"(https://hooks\.slack\.com/services/[A-Za-z0-9/]{20,})", false),
|
||||
r("Stripe key", r"\b((?:sk|rk)_live_[A-Za-z0-9]{20,})", false),
|
||||
r("Google API key", r"\b(AIza[0-9A-Za-z_\-]{35})", false),
|
||||
r("Google client secret", r"\b(GOCSPX-[A-Za-z0-9_\-]{28})", false),
|
||||
r("Anthropic key", r"\b(sk-ant-[A-Za-z0-9_\-]{32,})", false),
|
||||
r("OpenAI key", r"\b(sk-(?:proj-|svcacct-)?[A-Za-z0-9_\-]{32,})", false),
|
||||
r("npm token", r"\b(npm_[A-Za-z0-9]{36})\b", false),
|
||||
r("DigitalOcean token", r"\b(do[opr]_v1_[a-f0-9]{64})\b", false),
|
||||
r("SendGrid key", r"\b(SG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43})", false),
|
||||
r("Telegram bot token", r"\b(\d{8,10}:AA[A-Za-z0-9_\-]{33})", false),
|
||||
r("Vault token", r"\b(hv[sb]\.[A-Za-z0-9_\-]{90,})", false),
|
||||
r("JSON web token", r"\b(eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,})", false),
|
||||
r("password in a URL", r"\b[a-z][a-z0-9+.\-]*://[^\s:/@]+:([^\s@/]{3,})@", true),
|
||||
r(
|
||||
"password or token",
|
||||
r#"(?i)(?:password|passwd|pwd|secret|token|api[_\-]?key|access[_\-]?key|client[_\-]?secret|private[_\-]?key)["']?\s*[:=]\s*["'`]?([^\s"'`,;]{12,})"#,
|
||||
true,
|
||||
),
|
||||
]
|
||||
});
|
||||
|
||||
/// One suspected secret in a note.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Hit {
|
||||
pub rule: &'static str,
|
||||
/// Byte span of the secret itself.
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
/// 1-based line where it starts.
|
||||
pub line: usize,
|
||||
/// Fingerprint of the exact line(s) it sits on, for "not a secret".
|
||||
pub line_hash: String,
|
||||
/// Masked preview, never the full secret.
|
||||
pub hint: String,
|
||||
}
|
||||
|
||||
/// Secrets on lines of `text` that aren't in `old` (already shared) and aren't allowed.
|
||||
pub fn scan(text: &str, old: Option<&str>, allowed: &HashSet<String>) -> Vec<Hit> {
|
||||
let old_lines: HashSet<&str> = old.map(|o| o.lines().collect()).unwrap_or_default();
|
||||
let mut hits: Vec<Hit> = vec![];
|
||||
for rule in RULES.iter() {
|
||||
for caps in rule.re.captures_iter(text) {
|
||||
let m = caps.get(1).unwrap_or_else(|| caps.get(0).unwrap());
|
||||
if hits.iter().any(|h| m.start() < h.end && h.start < m.end()) {
|
||||
continue;
|
||||
}
|
||||
if rule.looks_random && !looks_random(m.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let ls = text[..m.start()].rfind('\n').map_or(0, |i| i + 1);
|
||||
let le = text[m.end()..].find('\n').map_or(text.len(), |i| m.end() + i);
|
||||
let lines = &text[ls..le];
|
||||
if lines.lines().all(|l| old_lines.contains(l)) {
|
||||
continue;
|
||||
}
|
||||
let line_hash = fingerprint(lines);
|
||||
if allowed.contains(&line_hash) {
|
||||
continue;
|
||||
}
|
||||
hits.push(Hit {
|
||||
rule: rule.name,
|
||||
start: m.start(),
|
||||
end: m.end(),
|
||||
line: text[..m.start()].matches('\n').count() + 1,
|
||||
line_hash,
|
||||
hint: mask(m.as_str()),
|
||||
});
|
||||
}
|
||||
}
|
||||
hits.sort_by_key(|h| h.start);
|
||||
hits
|
||||
}
|
||||
|
||||
/// Scans a file's bytes; binary files are skipped.
|
||||
pub fn scan_bytes(new: &[u8], old: Option<&[u8]>, allowed: &HashSet<String>) -> Vec<Hit> {
|
||||
if new.iter().take(8000).any(|&b| b == 0) {
|
||||
return vec![];
|
||||
}
|
||||
let Ok(text) = std::str::from_utf8(new) else { return vec![] };
|
||||
let old = old.and_then(|o| std::str::from_utf8(o).ok());
|
||||
scan(text, old, allowed)
|
||||
}
|
||||
|
||||
/// Replaces every hit (or only the one on `line`) with `pointer`.
|
||||
pub fn replace_with_pointer(text: &str, hits: &[Hit], line: Option<usize>, pointer: &str) -> String {
|
||||
let mut out = text.to_string();
|
||||
for h in hits.iter().rev().filter(|h| line.is_none_or(|l| h.line == l)) {
|
||||
out.replace_range(h.start..h.end, pointer);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn fingerprint(s: &str) -> String {
|
||||
git2::Oid::hash_object(git2::ObjectType::Blob, s.as_bytes()).map(|o| o.to_string()).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn mask(s: &str) -> String {
|
||||
let first_line = s.lines().next().unwrap_or("");
|
||||
let shown: String = first_line.chars().take(4).collect();
|
||||
format!("{shown}… ({} characters)", s.chars().count())
|
||||
}
|
||||
|
||||
/// Long, mixed and not a placeholder: what real generated secrets look like.
|
||||
fn looks_random(s: &str) -> bool {
|
||||
let lower = s.to_lowercase();
|
||||
let placeholder = ["<", ">", "${", "{{", "xxx", "changeme", "example", "your", "redacted", "placeholder", "****"]
|
||||
.iter()
|
||||
.any(|p| lower.contains(p));
|
||||
if placeholder || s.len() < 8 {
|
||||
return false;
|
||||
}
|
||||
let classes = [s.bytes().any(|b| b.is_ascii_lowercase()), s.bytes().any(|b| b.is_ascii_uppercase()), s.bytes().any(|b| b.is_ascii_digit()), s.bytes().any(|b| !b.is_ascii_alphanumeric())];
|
||||
let mut counts = std::collections::HashMap::new();
|
||||
for c in s.chars() {
|
||||
*counts.entry(c).or_insert(0usize) += 1;
|
||||
}
|
||||
let n = s.chars().count() as f64;
|
||||
let entropy: f64 = counts.values().map(|&c| { let p = c as f64 / n; -p * p.log2() }).sum();
|
||||
classes.iter().filter(|&&c| c).count() >= 2 && entropy >= 3.0
|
||||
}
|
||||
|
||||
/// Lines this device was told are not secrets, as fingerprints. Lives in `.git/lune/`.
|
||||
pub fn load_allowed(git_dir: &Path) -> HashSet<String> {
|
||||
std::fs::read_to_string(crate::state::lune_dir(git_dir).join("not-secrets"))
|
||||
.unwrap_or_default()
|
||||
.lines()
|
||||
.filter_map(|l| l.split_whitespace().next().map(String::from))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn allow(git_dir: &Path, hit: &Hit, file: &str) -> Result<()> {
|
||||
use std::io::Write;
|
||||
let dir = crate::state::lune_dir(git_dir);
|
||||
std::fs::create_dir_all(&dir)?;
|
||||
let mut f = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("not-secrets"))?;
|
||||
writeln!(f, "{} {} line {} · {}", hit.line_hash, file, hit.line, hit.rule)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn rules_hit(text: &str) -> Vec<&'static str> {
|
||||
scan(text, None, &HashSet::new()).into_iter().map(|h| h.rule).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catches_real_looking_secrets() {
|
||||
assert_eq!(rules_hit("key: AKIAIOSFODNN7EXAMPLE\n"), ["AWS access key"]);
|
||||
assert_eq!(rules_hit("aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY\n"), ["AWS secret key"]);
|
||||
assert_eq!(rules_hit("-----BEGIN OPENSSH PRIVATE KEY-----\nb3Blbn\n-----END OPENSSH PRIVATE KEY-----\n"), ["private key"]);
|
||||
assert_eq!(rules_hit("token ghp_0123456789abcdefghijABCDEFGHIJ012345\n"), ["GitHub token"]);
|
||||
assert_eq!(rules_hit("sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789\n"), ["Anthropic key"]);
|
||||
assert_eq!(rules_hit("db: postgres://app:S3cr3t-Pa55w0rd@db.internal/app\n"), ["password in a URL"]);
|
||||
assert_eq!(rules_hit("DB_PASSWORD=Xq7#pL9!vR2@mK4z\n"), ["password or token"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leaves_pointers_and_prose_alone() {
|
||||
for ok in [
|
||||
"Get the DB password from 1Password: search prod-db\n",
|
||||
"password: <ask Sen>\n",
|
||||
"token = ${GITHUB_TOKEN}\n",
|
||||
"secret: see Secrets Manager prod/deploy\n",
|
||||
"use tsh login --proxy=teleport.internal\n",
|
||||
"postgres://app@db.internal/app\n",
|
||||
"api_key = changeme_changeme\n",
|
||||
] {
|
||||
assert!(rules_hit(ok).is_empty(), "{ok}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_new_lines_count_and_allowed_lines_are_remembered() {
|
||||
let old = "AKIAIOSFODNN7EXAMPLE\n";
|
||||
assert!(scan("AKIAIOSFODNN7EXAMPLE\nmore\n", Some(old), &HashSet::new()).is_empty());
|
||||
let hits = scan("x\nkey AKIAIOSFODNN7EXAMPLE\n", None, &HashSet::new());
|
||||
assert_eq!(hits[0].line, 2);
|
||||
let allowed = HashSet::from([hits[0].line_hash.clone()]);
|
||||
assert!(scan("x\nkey AKIAIOSFODNN7EXAMPLE\n", None, &allowed).is_empty());
|
||||
assert!(!hits[0].hint.contains("IOSFODNN7EXAMPLE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pointer_replaces_only_the_secret() {
|
||||
let text = "aws_access_key_id = AKIAIOSFODNN7EXAMPLE\n";
|
||||
let hits = scan(text, None, &HashSet::new());
|
||||
let out = replace_with_pointer(text, &hits, None, "(search prod-deploy in Secrets Manager)");
|
||||
assert_eq!(out, "aws_access_key_id = (search prod-deploy in Secrets Manager)\n");
|
||||
assert!(scan(&out, None, &HashSet::new()).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,6 @@
|
||||
use crate::names;
|
||||
use crate::vault::{Saved, Vault};
|
||||
use anyhow::{Result, bail};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct KeptBoth {
|
||||
@@ -65,5 +64,40 @@ pub fn keep(vault: &Vault, file: &str, choice: Keep) -> Result<Option<Saved>> {
|
||||
_ => std::fs::remove_file(©)?,
|
||||
}
|
||||
}
|
||||
vault.save_changes(Some(&format!("Tidied {note}")), &HashSet::new())
|
||||
vault.save_unguarded(Some(&format!("Tidied {note}")))
|
||||
}
|
||||
|
||||
/// Line-by-line comparison of a note and its kept copy: `-` only in the note, `+` only in the copy.
|
||||
pub fn show(vault: &Vault, file: &str) -> Result<String> {
|
||||
let all = list(vault)?;
|
||||
let pairs: Vec<&KeptBoth> = all.iter().filter(|k| k.copy == file || k.note == file).collect();
|
||||
let mut out = String::new();
|
||||
if pairs.is_empty() {
|
||||
bail!("{file} has no kept-both versions to compare");
|
||||
}
|
||||
for k in pairs {
|
||||
let note = std::fs::read(vault.root.join(&k.note)).unwrap_or_default();
|
||||
let copy = std::fs::read(vault.root.join(&k.copy))?;
|
||||
let whose = |copy_side: bool| {
|
||||
if k.label.eq_ignore_ascii_case(&vault.label) == copy_side { "yours" } else { "theirs" }
|
||||
};
|
||||
out.push_str(&format!("- {} ({})\n+ {} ({})\n", k.note, whose(false), k.copy, whose(true)));
|
||||
let patch = git2::Patch::from_buffers(¬e, None, ©, None, None)?;
|
||||
if patch.num_hunks() == 0 {
|
||||
out.push_str(" (identical)\n");
|
||||
}
|
||||
for h in 0..patch.num_hunks() {
|
||||
out.push_str(" ···\n");
|
||||
for l in 0..patch.num_lines_in_hunk(h)? {
|
||||
let line = patch.line_in_hunk(h, l)?;
|
||||
let text = String::from_utf8_lossy(line.content());
|
||||
out.push_str(&format!("{} {}", line.origin(), text));
|
||||
if !text.ends_with('\n') {
|
||||
out.push('\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! One vault on disk: setting it up, saving bursts of edits as history entries, and syncing with the remote.
|
||||
|
||||
use crate::config::VaultConfig;
|
||||
use crate::guard::{self, Damage, HeldBurst};
|
||||
use crate::names;
|
||||
use crate::remote;
|
||||
use crate::secrets::{self, Hit};
|
||||
use crate::state;
|
||||
use anyhow::{Context, Result, bail};
|
||||
use git2::build::{CheckoutBuilder, TreeUpdateBuilder};
|
||||
@@ -43,6 +45,15 @@ pub struct Saved {
|
||||
pub id: Oid,
|
||||
pub message: String,
|
||||
pub files: Vec<String>,
|
||||
/// Set when the runaway guard held this burst back.
|
||||
pub held: Option<Damage>,
|
||||
}
|
||||
|
||||
/// A note whose change is held back because it seems to contain a secret.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SecretNote {
|
||||
pub path: String,
|
||||
pub hits: Vec<Hit>,
|
||||
}
|
||||
|
||||
/// What one sync round did, in terms the run log can print.
|
||||
@@ -60,6 +71,10 @@ pub struct SyncReport {
|
||||
pub shared: usize,
|
||||
/// Incoming changes touch a file that is still being edited here; they'll land after it settles.
|
||||
pub waiting_for_local_edits: bool,
|
||||
/// (note, copy) for held notes moved aside so an incoming version could land.
|
||||
pub set_aside: Vec<(String, String)>,
|
||||
/// A big change is held here, so nothing from this device was shared.
|
||||
pub holding: bool,
|
||||
}
|
||||
|
||||
impl Vault {
|
||||
@@ -119,8 +134,20 @@ impl Vault {
|
||||
self.repo.is_path_ignored(rel).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Saves every changed file as one history entry, except paths in `skip` (still being written).
|
||||
/// Saves every changed file as one history entry, except paths in `skip` (still being written)
|
||||
/// and notes that seem to contain a secret. A runaway burst is saved but held (S6).
|
||||
pub fn save_changes(&self, message: Option<&str>, skip: &HashSet<String>) -> Result<Option<Saved>> {
|
||||
self.save(message, skip, true)
|
||||
}
|
||||
|
||||
/// Like `save_changes`, without the runaway guard: for changes the app makes on the owner's say-so.
|
||||
pub fn save_unguarded(&self, message: Option<&str>) -> Result<Option<Saved>> {
|
||||
self.save(message, &HashSet::new(), false)
|
||||
}
|
||||
|
||||
fn save(&self, message: Option<&str>, skip: &HashSet<String>, guarded: bool) -> Result<Option<Saved>> {
|
||||
let mut skip = skip.clone();
|
||||
skip.extend(self.secret_holds()?.into_iter().map(|n| n.path));
|
||||
let mut index = self.repo.index()?;
|
||||
index.read(false)?;
|
||||
let mut filter = |p: &Path, _: &[u8]| -> i32 { if skip.contains(&names::slash_path(p)) { 1 } else { 0 } };
|
||||
@@ -143,10 +170,107 @@ impl Vault {
|
||||
Some(m) => m.to_string(),
|
||||
None => describe_files(&diff),
|
||||
};
|
||||
let damage = match &old_tree {
|
||||
Some(old) if guarded => Some(guard::assess(&self.repo, old, &tree)?).filter(|d| d.is_runaway()),
|
||||
_ => None,
|
||||
};
|
||||
let sig = self.signature()?;
|
||||
let parents: Vec<&Commit> = parent.iter().collect();
|
||||
let id = self.repo.commit(Some(&self.branch_ref()), &sig, &sig, &message, &tree, &parents)?;
|
||||
Ok(Some(Saved { id, message, files }))
|
||||
if let Some(d) = damage {
|
||||
let mut held = guard::load(&self.git_dir);
|
||||
held.push(HeldBurst {
|
||||
id: id.to_string(),
|
||||
message: message.clone(),
|
||||
removed: d.removed,
|
||||
rewritten: d.rewritten,
|
||||
total: d.total,
|
||||
at: chrono::Utc::now().timestamp(),
|
||||
});
|
||||
guard::save(&self.git_dir, &held)?;
|
||||
}
|
||||
Ok(Some(Saved { id, message, files, held: damage }))
|
||||
}
|
||||
|
||||
/// Changed notes (not yet saved) that seem to contain a secret on a new line.
|
||||
pub fn secret_holds(&self) -> Result<Vec<SecretNote>> {
|
||||
let allowed = secrets::load_allowed(&self.git_dir);
|
||||
let head_tree = self.head_commit()?.map(|c| c.tree()).transpose()?;
|
||||
let mut known_blobs: Option<HashSet<Oid>> = None;
|
||||
let mut opts = StatusOptions::new();
|
||||
opts.include_untracked(true).recurse_untracked_dirs(true).include_ignored(false);
|
||||
let mut out = vec![];
|
||||
for entry in self.repo.statuses(Some(&mut opts))?.iter() {
|
||||
let st = entry.status();
|
||||
if st.is_wt_deleted() || st.is_index_deleted() {
|
||||
continue;
|
||||
}
|
||||
let Ok(path) = entry.path() else { continue };
|
||||
let Ok(bytes) = std::fs::read(self.root.join(path)) else { continue };
|
||||
let old = match head_tree.as_ref().and_then(|t| t.get_path(Path::new(path)).ok()) {
|
||||
Some(e) => Some(self.repo.find_blob(e.id())?.content().to_vec()),
|
||||
None => {
|
||||
// A new file whose exact bytes are already in the vault (a copy or a move) was already shared.
|
||||
let known = known_blobs.get_or_insert_with(|| blob_ids(head_tree.as_ref()));
|
||||
if known.contains(&Oid::hash_object(git2::ObjectType::Blob, &bytes)?) {
|
||||
continue;
|
||||
}
|
||||
None
|
||||
}
|
||||
};
|
||||
let hits = secrets::scan_bytes(&bytes, old.as_deref(), &allowed);
|
||||
if !hits.is_empty() {
|
||||
out.push(SecretNote { path: path.to_string(), hits });
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Owner says the held big change was intended: share it.
|
||||
pub fn share_held(&self) -> Result<Vec<HeldBurst>> {
|
||||
let held = guard::load(&self.git_dir);
|
||||
guard::save(&self.git_dir, &[])?;
|
||||
Ok(held)
|
||||
}
|
||||
|
||||
/// Owner says the held big change was a mistake: bring back exactly what it removed or rewrote.
|
||||
/// Notes edited elsewhere meanwhile keep both versions. The caller holds the op lock.
|
||||
pub fn undo_held(&self) -> Result<Vec<(String, String)>> {
|
||||
let held = guard::load(&self.git_dir);
|
||||
let mut kept_both = vec![];
|
||||
for h in held.iter().rev() {
|
||||
let burst = self.repo.find_commit(Oid::from_str(&h.id)?)?;
|
||||
let head = self.head_commit()?.context("nothing to undo")?;
|
||||
let mut index = self.repo.revert_commit(&burst, &head, 0, None)?;
|
||||
self.keep_both(&mut index, &mut kept_both)?;
|
||||
let reverted = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
|
||||
// Notes the burst added stay: undo only brings back what it removed or rewrote.
|
||||
let added = self.repo.diff_tree_to_tree(Some(&burst.parent(0)?.tree()?), Some(&burst.tree()?), None)?;
|
||||
let head_tree = head.tree()?;
|
||||
let mut keep = TreeUpdateBuilder::new();
|
||||
for d in added.deltas().filter(|d| d.status() == git2::Delta::Added) {
|
||||
if let Some(p) = d.new_file().path()
|
||||
&& let Ok(e) = head_tree.get_path(p)
|
||||
{
|
||||
keep.upsert(p, e.id(), file_mode(e.filemode()));
|
||||
}
|
||||
}
|
||||
let tree = self.repo.find_tree(keep.create_updated(&self.repo, &reverted)?)?;
|
||||
if tree.id() == head.tree_id() {
|
||||
continue;
|
||||
}
|
||||
let sig = self.signature()?;
|
||||
let id = self.repo.commit(None, &sig, &sig, &format!("Undid: {}", h.message), &tree, &[&head])?;
|
||||
self.move_to(id).map_err(|e| {
|
||||
if e.code() == ErrorCode::Conflict {
|
||||
anyhow::anyhow!("some of those notes are being edited right now — try again in a few seconds")
|
||||
} else {
|
||||
e.into()
|
||||
}
|
||||
})?;
|
||||
}
|
||||
guard::save(&self.git_dir, &[])?;
|
||||
Ok(kept_both)
|
||||
}
|
||||
|
||||
/// A named checkpoint (S3). If everything is already saved, records the name on its own.
|
||||
@@ -225,6 +349,7 @@ impl Vault {
|
||||
let target = self.fix_case_clashes(target, &mut report)?;
|
||||
let incoming = incoming.as_ref().unwrap();
|
||||
self.note_incoming(local.as_ref(), incoming, target, &mut report)?;
|
||||
self.set_aside_held_notes(target, &mut report)?;
|
||||
match self.move_to(target) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.code() == ErrorCode::Conflict => {
|
||||
@@ -244,6 +369,10 @@ impl Vault {
|
||||
if ahead == 0 {
|
||||
return Ok(report);
|
||||
}
|
||||
if !guard::load(&self.git_dir).is_empty() {
|
||||
report.holding = true;
|
||||
return Ok(report);
|
||||
}
|
||||
if self.push()? {
|
||||
report.shared += ahead;
|
||||
return Ok(report);
|
||||
@@ -255,6 +384,20 @@ impl Vault {
|
||||
/// Combines two lines of history. Same-lines clashes keep both: incoming in place, ours beside it (S4).
|
||||
fn combine(&self, local: &Commit, incoming: &Commit, report: &mut SyncReport) -> Result<Oid> {
|
||||
let mut index = self.repo.merge_commits(local, incoming, None)?;
|
||||
self.keep_both(&mut index, &mut report.kept_both)?;
|
||||
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
|
||||
let from = incoming.author().name().unwrap_or("another device").to_string();
|
||||
let mut message = format!("Combined changes from {from}");
|
||||
if !report.kept_both.is_empty() {
|
||||
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
|
||||
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
|
||||
}
|
||||
let sig = self.signature()?;
|
||||
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
|
||||
}
|
||||
|
||||
/// Resolves every clash in `index` without markers: "their" version in place, ours beside it (S4).
|
||||
fn keep_both(&self, index: &mut git2::Index, kept_both: &mut Vec<(String, String)>) -> Result<()> {
|
||||
if index.has_conflicts() {
|
||||
let conflicts: Vec<_> = index.conflicts()?.collect::<Result<_, _>>()?;
|
||||
for c in conflicts {
|
||||
@@ -270,7 +413,7 @@ impl Vault {
|
||||
.unwrap();
|
||||
index.add(&stage0(&theirs, None))?;
|
||||
index.add(&stage0(&ours, Some(copy.as_bytes())))?;
|
||||
report.kept_both.push((note, copy));
|
||||
kept_both.push((note, copy));
|
||||
}
|
||||
// Different paths, or one side removed the note: keep whatever still exists.
|
||||
(ours, theirs) => {
|
||||
@@ -281,15 +424,7 @@ impl Vault {
|
||||
}
|
||||
}
|
||||
}
|
||||
let tree = self.repo.find_tree(index.write_tree_to(&self.repo)?)?;
|
||||
let from = incoming.author().name().unwrap_or("another device").to_string();
|
||||
let mut message = format!("Combined changes from {from}");
|
||||
if !report.kept_both.is_empty() {
|
||||
let notes: Vec<&str> = report.kept_both.iter().map(|(n, _)| n.as_str()).collect();
|
||||
message.push_str(&format!(" · kept both versions of {}", notes.join(", ")));
|
||||
}
|
||||
let sig = self.signature()?;
|
||||
Ok(self.repo.commit(None, &sig, &sig, &message, &tree, &[local, incoming])?)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Paths that differ only by letter case can't coexist on macOS/Windows. There, rename the extras so
|
||||
@@ -366,6 +501,35 @@ impl Vault {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A held note can't take an incoming version in place, and must not wait for it either:
|
||||
/// move the local version beside it (still held) and put back the saved one so the update lands.
|
||||
fn set_aside_held_notes(&self, target: Oid, report: &mut SyncReport) -> Result<()> {
|
||||
let held = self.secret_holds()?;
|
||||
if held.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let head_tree = self.head_commit()?.map(|c| c.tree()).transpose()?;
|
||||
let target_tree = self.repo.find_commit(target)?.tree()?;
|
||||
for note in held {
|
||||
let p = Path::new(¬e.path);
|
||||
let current = head_tree.as_ref().and_then(|t| t.get_path(p).ok()).map(|e| e.id());
|
||||
let incoming = target_tree.get_path(p).ok().map(|e| e.id());
|
||||
if current == incoming {
|
||||
continue;
|
||||
}
|
||||
let copy = (1..)
|
||||
.map(|n| names::copy_name(¬e.path, &self.label, n))
|
||||
.find(|c| !self.root.join(c).exists() && target_tree.get_path(Path::new(c)).is_err())
|
||||
.unwrap();
|
||||
std::fs::rename(self.root.join(p), self.root.join(©))?;
|
||||
if let Some(id) = current {
|
||||
std::fs::write(self.root.join(p), self.repo.find_blob(id)?.content())?;
|
||||
}
|
||||
report.set_aside.push((note.path, copy));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Writes `target` to the folder without touching anything that's still being edited, then makes it current.
|
||||
fn move_to(&self, target: Oid) -> Result<(), git2::Error> {
|
||||
let commit = self.repo.find_commit(target)?;
|
||||
@@ -408,6 +572,17 @@ impl Vault {
|
||||
}
|
||||
}
|
||||
|
||||
fn blob_ids(tree: Option<&git2::Tree>) -> HashSet<Oid> {
|
||||
let mut ids = HashSet::new();
|
||||
if let Some(t) = tree {
|
||||
let _ = t.walk(TreeWalkMode::PreOrder, |_, e| {
|
||||
ids.insert(e.id());
|
||||
TreeWalkResult::Ok
|
||||
});
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
fn stage0(e: &IndexEntry, path: Option<&[u8]>) -> IndexEntry {
|
||||
let mut e = IndexEntry { path: e.path.clone(), ..*e };
|
||||
e.flags = 0;
|
||||
@@ -438,7 +613,12 @@ fn describe_files(diff: &git2::Diff) -> String {
|
||||
};
|
||||
return format!("{verb} {path}");
|
||||
}
|
||||
format!("Updated {} notes", deltas.len())
|
||||
let verb = match deltas.iter().map(|d| d.status()).collect::<Vec<_>>() {
|
||||
s if s.iter().all(|&x| x == git2::Delta::Deleted) => "Removed",
|
||||
s if s.iter().all(|&x| matches!(x, git2::Delta::Added | git2::Delta::Untracked)) => "Added",
|
||||
_ => "Updated",
|
||||
};
|
||||
format!("{verb} {} notes", deltas.len())
|
||||
}
|
||||
|
||||
/// What `add` did with the folder.
|
||||
|
||||
Reference in New Issue
Block a user