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:
2026-10-29 00:08:02 +07:00
parent 25b8be5bbd
commit 62bc3db416
11 changed files with 963 additions and 55 deletions

217
core/src/secrets.rs Normal file
View 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());
}
}