Skip to main content

gitpoulpi_core/
privacy.rs

1//! What must not leave the machine by accident: the pure half of the AI
2//! privacy and sensitive-staging hardening.
3//!
4//! Three things live here, none of them doing I/O:
5//!
6//! - a list of **sensitive path patterns** ([`DEFAULT_SENSITIVE_PATTERNS`])
7//!   and a small gitignore-style matcher ([`matching_pattern`]);
8//! - [`classify`]: why a file, given its path and (optionally) its content,
9//!   counts as sensitive. It uses the secret scanner of the history rewrite,
10//!   so the two agree on what a secret is, and **no value ever leaves this
11//!   function**: a finding carries a rule id and a masked preview;
12//! - [`redact`]: a text with every finding replaced by `[REDACTED:<rule>]`.
13
14use serde::{Deserialize, Serialize};
15
16use crate::domain::rewrite::secrets::{preview, scan_text};
17
18/// The paths the staging guard and the AI exclusion treat as sensitive. A
19/// `!` pattern re-allows what an earlier pattern matched; the last pattern
20/// that matches a path decides.
21pub const DEFAULT_SENSITIVE_PATTERNS: &[&str] = &[
22    ".env",
23    ".env.*",
24    "!.env.example",
25    "!.env.sample",
26    "!.env.template",
27    "*.pem",
28    "*.key",
29    "id_rsa*",
30    "id_ed25519*",
31    "id_ecdsa*",
32    "*.p12",
33    "*.pfx",
34    "*.jks",
35    "*.keystore",
36    "*.crt",
37    "*.cer",
38    "*.der",
39    "*.kdbx",
40];
41
42/// [`DEFAULT_SENSITIVE_PATTERNS`] as owned strings (the config default).
43pub fn default_sensitive_patterns() -> Vec<String> {
44    DEFAULT_SENSITIVE_PATTERNS
45        .iter()
46        .map(|p| (*p).to_string())
47        .collect()
48}
49
50/// Why one file is sensitive.
51#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
52pub enum Reason {
53    /// Its path matches this pattern.
54    Pattern(String),
55    /// Its content holds something the secret scanner recognises. `preview`
56    /// is masked; the value itself is never stored here.
57    Secret { rule: String, preview: String },
58}
59
60/// A file that should not be staged or sent without a decision.
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct Sensitive {
63    pub path: String,
64    pub reason: Reason,
65    /// The 1-based line of the file where the secret starts; `None` for a
66    /// path-pattern finding (the whole file is the finding) and for an answer
67    /// from an older daemon.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub line: Option<u32>,
70}
71
72impl Sensitive {
73    /// A one-line reason for a list, such as `matches .env.*` or
74    /// `secret: github-token (ghp_****)`.
75    pub fn describe(&self) -> String {
76        match &self.reason {
77            Reason::Pattern(p) => format!("matches {p}"),
78            Reason::Secret { rule, preview } => format!("secret: {rule} ({preview})"),
79        }
80    }
81}
82
83/// The paths of `files` for a message: the first few, then a count.
84pub fn summary(files: &[Sensitive]) -> String {
85    let mut paths: Vec<&str> = Vec::new();
86    for f in files {
87        if !paths.contains(&f.path.as_str()) {
88            paths.push(&f.path);
89        }
90    }
91    let shown = paths.iter().take(5).copied().collect::<Vec<_>>().join(", ");
92    if paths.len() > 5 {
93        format!("{shown}, and {} more", paths.len() - 5)
94    } else {
95        shown
96    }
97}
98
99/// One secret replaced in a text. No value: a rule and a masked preview.
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
101pub struct Redaction {
102    pub rule: String,
103    pub preview: String,
104}
105
106/// The positive pattern that makes `path` sensitive, or `None`. A pattern
107/// without a `/` matches the file name at any depth, one with a `/` matches
108/// the whole path (a leading `/` anchors it at the root), `!` re-allows,
109/// `*` and `?` do not cross a `/`, `**` does. The last matching pattern wins.
110/// Matching ignores ASCII case: a guard must not be fooled by `.ENV`.
111pub fn matching_pattern<'a, S: AsRef<str>>(path: &str, patterns: &'a [S]) -> Option<&'a str> {
112    let path = path.replace('\\', "/");
113    let path = path.trim_start_matches("./");
114    let mut hit: Option<&'a str> = None;
115    for raw in patterns {
116        let raw = raw.as_ref().trim();
117        if raw.is_empty() || raw.starts_with('#') {
118            continue;
119        }
120        let (negated, body) = match raw.strip_prefix('!') {
121            Some(rest) => (true, rest.trim()),
122            None => (false, raw),
123        };
124        if body.is_empty() || !pattern_matches(body, path) {
125            continue;
126        }
127        hit = if negated { None } else { Some(raw) };
128    }
129    hit
130}
131
132fn pattern_matches(pattern: &str, path: &str) -> bool {
133    let pattern = pattern.trim_end_matches('/');
134    let anchored = pattern.starts_with('/');
135    let pattern = pattern.trim_start_matches('/');
136    if !anchored && !pattern.contains('/') {
137        let name = path.rsplit('/').next().unwrap_or(path);
138        return glob(pattern.as_bytes(), name.as_bytes());
139    }
140    glob(pattern.as_bytes(), path.as_bytes())
141}
142
143/// `*`, `?` and `**`, case-insensitive; `/` is matched only by itself or `**`.
144fn glob(pat: &[u8], text: &[u8]) -> bool {
145    match pat.first() {
146        None => text.is_empty(),
147        Some(b'*') => {
148            let double = pat.get(1) == Some(&b'*');
149            let rest = &pat[if double { 2 } else { 1 }..];
150            // `**/` also matches no directory at all.
151            if double && rest.first() == Some(&b'/') && glob(&rest[1..], text) {
152                return true;
153            }
154            let mut i = 0;
155            loop {
156                if glob(rest, &text[i..]) {
157                    return true;
158                }
159                if i == text.len() || (!double && text[i] == b'/') {
160                    return false;
161                }
162                i += 1;
163            }
164        }
165        Some(b'?') => match text.first() {
166            Some(c) if *c != b'/' => glob(&pat[1..], &text[1..]),
167            _ => false,
168        },
169        Some(p) => match text.first() {
170            Some(c) if c.eq_ignore_ascii_case(p) => glob(&pat[1..], &text[1..]),
171            _ => false,
172        },
173    }
174}
175
176/// Why `path` (with `content`, when the caller read it) is sensitive. A path
177/// that matches a pattern gives one entry; each distinct secret in the
178/// content gives one more (a rule and a masked preview, never the value).
179pub fn classify<S: AsRef<str>>(
180    path: &str,
181    content: Option<&[u8]>,
182    patterns: &[S],
183) -> Vec<Sensitive> {
184    let mut out = Vec::new();
185    if let Some(p) = matching_pattern(path, patterns) {
186        out.push(Sensitive {
187            path: path.to_string(),
188            reason: Reason::Pattern(p.to_string()),
189            line: None,
190        });
191    }
192    if let Some(bytes) = content {
193        let mut seen: Vec<(String, String)> = Vec::new();
194        for m in scan_text(bytes, path) {
195            let key = (m.rule.to_string(), preview(m.rule, &m.value));
196            if seen.contains(&key) {
197                continue;
198            }
199            seen.push(key.clone());
200            out.push(Sensitive {
201                path: path.to_string(),
202                reason: Reason::Secret {
203                    rule: key.0,
204                    preview: key.1,
205                },
206                line: Some(line_of(bytes, m.offset)),
207            });
208        }
209    }
210    out
211}
212
213/// The 1-based line of the byte `offset` of `text`.
214fn line_of(text: &[u8], offset: usize) -> u32 {
215    let end = offset.min(text.len());
216    let newlines = text[..end].iter().filter(|b| **b == b'\n').count();
217    u32::try_from(newlines + 1).unwrap_or(u32::MAX)
218}
219
220/// `text` with every secret replaced by `[REDACTED:<rule>]`, and what was
221/// replaced.
222pub fn redact(text: &str) -> (String, Vec<Redaction>) {
223    redact_in(text, "")
224}
225
226/// [`redact`] for the content of the file at `path` (a lock file is scanned
227/// for token prefixes only).
228pub fn redact_in(text: &str, path: &str) -> (String, Vec<Redaction>) {
229    let bytes = text.as_bytes();
230    let found = scan_text(bytes, path);
231    if found.is_empty() {
232        return (text.to_string(), Vec::new());
233    }
234    let mut out = Vec::with_capacity(bytes.len());
235    let mut at = 0usize;
236    let mut redactions = Vec::new();
237    for m in found {
238        let end = m.offset + m.value.len();
239        if m.offset < at || end > bytes.len() {
240            continue;
241        }
242        out.extend_from_slice(&bytes[at..m.offset]);
243        out.extend_from_slice(format!("[REDACTED:{}]", m.rule).as_bytes());
244        redactions.push(Redaction {
245            rule: m.rule.to_string(),
246            preview: preview(m.rule, &m.value),
247        });
248        at = end;
249    }
250    out.extend_from_slice(&bytes[at..]);
251    (String::from_utf8_lossy(&out).into_owned(), redactions)
252}
253
254#[cfg(test)]
255mod tests;