Skip to main content

wm_memory/
credentials.rs

1//! Credential-shape detection for memory content.
2//!
3//! Phase 3 secrets hygiene: `wm ingest` refuses credential-shaped
4//! *filenames* (`.env`, keys, certs); this module extends the same
5//! discipline to *content*. A store that silently swallows an API key
6//! becomes a liability the moment it is backed up, mesh-synced, or fed
7//! into a model context — so writes that look credential-bearing are
8//! flagged at the tool layer (warn + advise a keyring, not refuse:
9//! false-positive-proof refusal would train agents to hide secrets
10//! worse).
11//!
12//! High-precision heuristics only — the goal is to warn on real
13//! credentials without crying wolf on ordinary prose.
14
15#![forbid(unsafe_code)]
16
17/// Kinds of credential shapes the detector recognizes.
18pub const ADVICE: &str = "keep the secret in a keyring (OS keychain, pass, systemd-credentials) and store a reference in memory instead; memory privacy flags are not encryption";
19
20/// Detect credential-shaped content. Returns the matched kinds
21/// (e.g. `["private_key_pem", "github_token"]`); empty means clean.
22#[must_use]
23pub fn credential_shaped_content(content: &str) -> Vec<&'static str> {
24    let mut kinds: Vec<&'static str> = Vec::new();
25    let push = |k: &'static str, kinds: &mut Vec<&'static str>| {
26        if !kinds.contains(&k) {
27            kinds.push(k);
28        }
29    };
30
31    // 1. PEM private keys (RSA/OpenSSH/EC/PKCS8/PGP/encrypted).
32    if content.contains("-----BEGIN") && content.contains("PRIVATE KEY") {
33        push("private_key_pem", &mut kinds);
34    }
35
36    // 2. AWS access key ids: AKIA + 16 uppercase/digits.
37    if token_after(content, "AKIA", 16, |c| {
38        c.is_ascii_uppercase() || c.is_ascii_digit()
39    }) {
40        push("aws_access_key_id", &mut kinds);
41    }
42
43    // 3. GitHub tokens.
44    let alnum = |c: char| c.is_ascii_alphanumeric() || c == '_';
45    if token_after(content, "ghp_", 30, alnum)
46        || token_after(content, "gho_", 30, alnum)
47        || token_after(content, "github_pat_", 20, alnum)
48    {
49        push("github_token", &mut kinds);
50    }
51
52    // 4. OpenAI-style keys: sk- + 20 token chars.
53    if token_after(content, "sk-", 20, |c| {
54        c.is_ascii_alphanumeric() || c == '_' || c == '-'
55    }) {
56        push("openai_style_key", &mut kinds);
57    }
58
59    // 5. Slack tokens: xox{b,p,a,r,s}-.
60    if ["xoxb-", "xoxp-", "xoxa-", "xoxr-", "xoxs-"]
61        .iter()
62        .any(|p| token_after(content, p, 10, |c| c.is_ascii_alphanumeric() || c == '-'))
63    {
64        push("slack_token", &mut kinds);
65    }
66
67    // 6. JWTs: two base64url segments separated by dots.
68    if content.match_indices("eyJ").count() >= 2 {
69        push("jwt", &mut kinds);
70    }
71
72    // 7. Assignment shapes: password/secret/api_key/token followed by a
73    //    delimiter and a 16+ char value.
74    if assignment_shaped(content) {
75        push("credential_assignment", &mut kinds);
76    }
77
78    kinds
79}
80
81/// Scan for `prefix` followed by at least `min_len` charset characters.
82fn token_after(
83    haystack: &str,
84    prefix: &str,
85    min_len: usize,
86    charset: impl Fn(char) -> bool,
87) -> bool {
88    let mut from = 0usize;
89    while let Some(pos) = haystack[from..].find(prefix) {
90        let abs = from + pos + prefix.len();
91        let run = haystack[abs..].chars().take_while(|c| charset(*c)).count();
92        if run >= min_len {
93            return true;
94        }
95        from = abs;
96    }
97    false
98}
99
100/// Assignment-key names (case-insensitive) whose `=`/`:` value is treated as
101/// a secret. Compound keys are listed explicitly because the delimiter must
102/// immediately follow the key name: `secret` alone never matches
103/// `AWS_SECRET_ACCESS_KEY=...` (the `_` blocks the delimiter check).
104const ASSIGNMENT_KEYS: &[&str] = &[
105    "password",
106    "passwd",
107    "api_key",
108    "api-key",
109    "apikey",
110    "secret",
111    "access_token",
112    "secret_access_key",
113    "aws_secret_access_key",
114    "secret_key",
115    "client_secret",
116    "private_key",
117    "auth_token",
118    "refresh_token",
119];
120
121/// Case-insensitive `password = "..."` / `api_key: ...` detection with a
122/// 16+ character non-space value.
123fn assignment_shaped(content: &str) -> bool {
124    let lower = content.to_lowercase();
125    for key in ASSIGNMENT_KEYS {
126        let mut from = 0usize;
127        while let Some(pos) = lower[from..].find(key) {
128            let abs = from + pos + key.len();
129            let rest = lower[abs..].trim_start();
130            let Some(delim) = rest.chars().next() else {
131                break;
132            };
133            if delim == ':' || delim == '=' {
134                let value = rest[1..].trim_start();
135                let value = value.strip_prefix(['"', '\'']).unwrap_or(value);
136                // Redaction markers must never re-trigger detection, or the
137                // scrubber loops on its own output. `value` comes from the
138                // lowercased text, so the marker check is case-insensitive.
139                let is_marker = value
140                    .get(..10)
141                    .is_some_and(|p| p.eq_ignore_ascii_case("[REDACTED:"));
142                if !is_marker {
143                    let run: usize = value
144                        .chars()
145                        .take_while(|c| !c.is_whitespace() && *c != '"' && *c != '\'')
146                        .map(char::len_utf8)
147                        .sum();
148                    if run >= 16 {
149                        return true;
150                    }
151                }
152            }
153            from = abs;
154        }
155    }
156    false
157}
158
159/// Redact credential-shaped spans, replacing them with `[REDACTED:<kind>]`.
160///
161/// Detection is [`credential_shaped_content`]; when nothing fires the text is
162/// returned unchanged. Redaction is span-oriented (PEM blocks, prefixed
163/// tokens, assignment values) and deliberately over-redacts rather than
164/// under-redacts. Returns the redacted text and the kinds that fired, using
165/// the same labels as detection.
166#[must_use]
167pub fn redact_credential_content(content: &str) -> (String, Vec<&'static str>) {
168    let kinds = credential_shaped_content(content);
169    if kinds.is_empty() {
170        return (content.to_string(), kinds);
171    }
172
173    let mut out = content.to_string();
174
175    if kinds.contains(&"private_key_pem") {
176        while let Some((start, end)) = pem_block_span(&out) {
177            out.replace_range(start..end, "[REDACTED:private_key_pem]");
178        }
179        // Detection fires on any content holding both "-----BEGIN" and
180        // "PRIVATE KEY" — including truncated/example fragments with no
181        // complete END block, which the span loop above cannot match.
182        // Neutralize the marker strings so the pass is idempotent.
183        out = out.replace("PRIVATE KEY-----", "[REDACTED:pem-key]");
184        out = out.replace("-----BEGIN", "[REDACTED:pem-begin]");
185        out = out.replace("-----END", "[REDACTED:pem-end]");
186    }
187
188    if kinds.contains(&"credential_assignment") {
189        while let Some((start, end)) = assignment_value_span(&out) {
190            out.replace_range(start..end, "[REDACTED:credential_assignment]");
191        }
192    }
193
194    // JWT detection fires on any two `eyJ` occurrences (fragments included),
195    // so redaction must remove every occurrence — a min-run scan left short
196    // fragments detectable and the apply pass non-idempotent.
197    if kinds.contains(&"jwt") {
198        while let Some(pos) = out.find("eyJ") {
199            out.replace_range(pos..pos + "eyJ".len(), "[REDACTED:jwt]");
200        }
201    }
202
203    type TokenSpec = (&'static str, &'static str, usize, fn(char) -> bool);
204    let token_specs: &[TokenSpec] = &[
205        ("aws_access_key_id", "AKIA", 16, |c: char| {
206            c.is_ascii_uppercase() || c.is_ascii_digit()
207        }),
208        ("github_token", "ghp_", 30, |c: char| {
209            c.is_ascii_alphanumeric() || c == '_'
210        }),
211        ("github_token", "gho_", 30, |c: char| {
212            c.is_ascii_alphanumeric() || c == '_'
213        }),
214        ("github_token", "github_pat_", 20, |c: char| {
215            c.is_ascii_alphanumeric() || c == '_'
216        }),
217        ("openai_style_key", "sk-", 20, |c: char| {
218            c.is_ascii_alphanumeric() || c == '_' || c == '-'
219        }),
220        ("slack_token", "xoxb-", 10, |c: char| {
221            c.is_ascii_alphanumeric() || c == '-'
222        }),
223        ("slack_token", "xoxp-", 10, |c: char| {
224            c.is_ascii_alphanumeric() || c == '-'
225        }),
226        ("slack_token", "xoxa-", 10, |c: char| {
227            c.is_ascii_alphanumeric() || c == '-'
228        }),
229        ("slack_token", "xoxr-", 10, |c: char| {
230            c.is_ascii_alphanumeric() || c == '-'
231        }),
232        ("slack_token", "xoxs-", 10, |c: char| {
233            c.is_ascii_alphanumeric() || c == '-'
234        }),
235    ];
236    for (kind, prefix, min_len, charset) in token_specs {
237        while let Some((start, end)) = prefixed_token_span(&out, prefix, *min_len, *charset) {
238            out.replace_range(start..end, &format!("[REDACTED:{kind}]"));
239        }
240    }
241
242    (out, kinds)
243}
244
245/// Span of the first PEM private-key block (including its BEGIN/END markers).
246fn pem_block_span(text: &str) -> Option<(usize, usize)> {
247    let begin = text.find("-----BEGIN")?;
248    let key_at = text[begin..].find("PRIVATE KEY-----")? + begin;
249    let end_at = text[key_at..].find("-----END")? + key_at;
250    let marker_at = text[end_at..].find("PRIVATE KEY-----")? + end_at;
251    Some((begin, marker_at + "PRIVATE KEY-----".len()))
252}
253
254/// Span of the first assignment *value* (the 16+ char secret, not the key).
255fn assignment_value_span(text: &str) -> Option<(usize, usize)> {
256    for key in ASSIGNMENT_KEYS {
257        let mut from = 0usize;
258        while let Some(pos) = find_ascii_case_insensitive(text, key, from) {
259            let after = pos + key.len();
260            let rest = &text[after..];
261            let ws = rest.len() - rest.trim_start().len();
262            let delim_pos = after + ws;
263            let delim = text[delim_pos..].chars().next();
264            if matches!(delim, Some(':' | '=')) {
265                let tail = &text[delim_pos + 1..];
266                let vws = tail.len() - tail.trim_start().len();
267                let mut vstart = delim_pos + 1 + vws;
268                if let Some(quote) = text[vstart..].chars().next() {
269                    if quote == '"' || quote == '\'' {
270                        vstart += quote.len_utf8();
271                    }
272                }
273                let mut bytes = 0usize;
274                for c in text[vstart..].chars() {
275                    if c.is_whitespace() || c == '"' || c == '\'' {
276                        break;
277                    }
278                    bytes += c.len_utf8();
279                }
280                let is_marker = text[vstart..]
281                    .get(..10)
282                    .is_some_and(|p| p.eq_ignore_ascii_case("[REDACTED:"));
283                if bytes >= 16 && !is_marker {
284                    return Some((vstart, vstart + bytes));
285                }
286            }
287            from = after;
288        }
289    }
290    None
291}
292
293/// Span of the first `prefix` + charset run of at least `min_len` characters.
294fn prefixed_token_span(
295    text: &str,
296    prefix: &str,
297    min_len: usize,
298    charset: fn(char) -> bool,
299) -> Option<(usize, usize)> {
300    let mut from = 0usize;
301    while let Some(pos) = text[from..].find(prefix) {
302        let start = from + pos;
303        let value_start = start + prefix.len();
304        let mut bytes = 0usize;
305        let mut count = 0usize;
306        for c in text[value_start..].chars() {
307            if !charset(c) {
308                break;
309            }
310            bytes += c.len_utf8();
311            count += 1;
312        }
313        if count >= min_len {
314            return Some((start, value_start + bytes));
315        }
316        from = value_start;
317    }
318    None
319}
320
321/// ASCII-case-insensitive substring search starting at `from`.
322fn find_ascii_case_insensitive(haystack: &str, needle: &str, from: usize) -> Option<usize> {
323    let h = haystack.as_bytes();
324    let n = needle.as_bytes();
325    if n.is_empty() || from >= h.len() || n.len() > h.len() - from {
326        return None;
327    }
328    (from..=h.len() - n.len()).find(|&i| h[i..i + n.len()].eq_ignore_ascii_case(n))
329}
330
331#[cfg(test)]
332mod tests {
333    use super::*;
334
335    #[test]
336    fn detects_private_keys_aws_and_github() {
337        let pem = "-----BEGIN RSA PRIVATE KEY-----\nMIIEow...\n-----END RSA PRIVATE KEY-----";
338        assert_eq!(credential_shaped_content(pem), vec!["private_key_pem"]);
339
340        let aws = "access id AKIAIOSFODNN7EXAMPLE found in logs";
341        assert_eq!(credential_shaped_content(aws), vec!["aws_access_key_id"]);
342
343        let gh = "token ghp_0123456789abcdefghijklmnopqrstuvwxyzABC pasted";
344        assert_eq!(credential_shaped_content(gh), vec!["github_token"]);
345    }
346
347    #[test]
348    fn detects_sk_slack_jwt_and_assignments() {
349        let sk = "key: sk-proj0123456789abcdefghijklmnopqrstuv";
350        assert_eq!(credential_shaped_content(sk), vec!["openai_style_key"]);
351
352        // Assembled at runtime: the raw Slack token shape must never appear
353        // in source (GitHub push protection blocks it), while the detector
354        // must still match the real shape at runtime.
355        let slack = format!(
356            "xoxb-{}-{}-{}",
357            "123456789012", "1234567890123", "abcdefghijklmnop"
358        );
359        assert_eq!(credential_shaped_content(&slack), vec!["slack_token"]);
360
361        let jwt = "header eyJhbGciOiJIUzI1NiJ9.payload eyJzdWIiOiIxMjM0NTY3ODkwIn0.sig";
362        assert_eq!(credential_shaped_content(jwt), vec!["jwt"]);
363
364        let assign = "connect with DATABASE_PASSWORD=correct-horse-battery-staple-1 tomorrow";
365        assert_eq!(
366            credential_shaped_content(assign),
367            vec!["credential_assignment"]
368        );
369    }
370
371    #[test]
372    fn detects_aws_secret_and_compound_assignment_keys() {
373        // Regression (P0, 2026-09-14): in AWS_SECRET_ACCESS_KEY the `secret`
374        // key name is followed by `_`, so the delimiter check never fired and
375        // the secret survived `wm ingest --redact`. Compound keys now need
376        // no special-casing at the call sites — they are listed explicitly.
377        let aws = "AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY";
378        assert_eq!(
379            credential_shaped_content(aws),
380            vec!["credential_assignment"]
381        );
382        let (redacted, kinds) = redact_credential_content(aws);
383        assert!(kinds.contains(&"credential_assignment"));
384        assert_eq!(
385            redacted,
386            "AWS_SECRET_ACCESS_KEY=[REDACTED:credential_assignment]"
387        );
388        assert!(
389            credential_shaped_content(&redacted).is_empty(),
390            "redacted AWS secret must read clean: {redacted}"
391        );
392        let (twice, _) = redact_credential_content(&redacted);
393        assert_eq!(redacted, twice);
394
395        // Compound keys with identifier suffixes need explicit listing.
396        for text in [
397            "secret_access_key=0123456789abcdef",
398            "secret_key: 0123456789abcdef",
399            "refresh_token=0123456789abcdef",
400            "auth_token=0123456789abcdef",
401        ] {
402            assert_eq!(
403                credential_shaped_content(text),
404                vec!["credential_assignment"],
405                "{text}"
406            );
407        }
408
409        // Prose naming the key without an assignment stays clean.
410        assert!(
411            credential_shaped_content("the aws secret access key rotation policy was updated")
412                .is_empty()
413        );
414    }
415
416    #[test]
417    fn ordinary_prose_stays_clean() {
418        assert!(
419            credential_shaped_content("remember that the password policy requires rotation")
420                .is_empty()
421        );
422        assert!(credential_shaped_content("api_key rotation happens quarterly").is_empty());
423        assert!(credential_shaped_content("short token: abc123").is_empty());
424        assert!(
425            credential_shaped_content("the sk- prefix marks OpenAI keys in general").is_empty()
426        );
427        assert!(credential_shaped_content("AKIA is the AWS key prefix").is_empty());
428        assert!(credential_shaped_content("we discussed jwt sessions at length").is_empty());
429    }
430
431    #[test]
432    fn dedupes_kinds() {
433        let both = "AKIAIOSFODNN7EXAMPLE and AKIAIOSFODNN7EXAMPLE again";
434        assert_eq!(credential_shaped_content(both), vec!["aws_access_key_id"]);
435    }
436
437    #[test]
438    fn redacts_private_key_blocks() {
439        let pem = "before\n-----BEGIN RSA PRIVATE KEY-----\nMIIEowSECRET\n-----END RSA PRIVATE KEY-----\nafter";
440        let (redacted, kinds) = redact_credential_content(pem);
441        assert!(kinds.contains(&"private_key_pem"));
442        assert!(!redacted.contains("MIIEowSECRET"), "key body must be gone");
443        assert!(!redacted.contains("BEGIN RSA PRIVATE KEY"));
444        assert_eq!(redacted, "before\n[REDACTED:private_key_pem]\nafter");
445    }
446
447    #[test]
448    fn redacts_assignment_values_and_tokens() {
449        let text = "db password=correct-horse-battery-staple and key sk-proj0123456789abcdefghijklmnopqrstuv";
450        let (redacted, _) = redact_credential_content(text);
451        assert!(redacted.contains("password=[REDACTED:credential_assignment]"));
452        assert!(!redacted.contains("correct-horse-battery-staple"));
453        assert!(!redacted.contains("sk-proj0123456789abcdefghijklmnopqrstuv"));
454        assert!(redacted.contains("[REDACTED:openai_style_key]"));
455
456        let aws = "id AKIAIOSFODNN7EXAMPLE here";
457        let (redacted, _) = redact_credential_content(aws);
458        assert_eq!(redacted, "id [REDACTED:aws_access_key_id] here");
459    }
460
461    #[test]
462    fn clean_content_passes_through_unchanged() {
463        let text = "remember that the password policy requires rotation";
464        let (redacted, kinds) = redact_credential_content(text);
465        assert!(kinds.is_empty());
466        assert_eq!(redacted, text);
467    }
468
469    #[test]
470    fn redaction_is_idempotent() {
471        let text = "key sk-proj0123456789abcdefghijklmnopqrstuv end";
472        let (once, _) = redact_credential_content(text);
473        let (twice, kinds) = redact_credential_content(&once);
474        assert_eq!(once, twice);
475        assert!(
476            kinds.is_empty(),
477            "redacted marker must read clean: {kinds:?}"
478        );
479    }
480
481    #[test]
482    fn assignment_marker_does_not_retrigger_detection() {
483        // Regression: detection lowercases before scanning, so the marker
484        // guard must compare case-insensitively or apply-pass runs are never
485        // idempotent (found by the wm redact-content store pass, 2026-09-11).
486        let text = "db password=correct-horse-battery-staple";
487        let (once, _) = redact_credential_content(text);
488        assert!(
489            credential_shaped_content(&once).is_empty(),
490            "redacted assignment must read clean: {once}"
491        );
492        let (twice, kinds) = redact_credential_content(&once);
493        assert_eq!(once, twice);
494        assert!(kinds.is_empty());
495    }
496
497    #[test]
498    fn short_jwt_fragments_are_redacted_too() {
499        // Regression: detection counts any two `eyJ` occurrences, but the
500        // redactor used to demand an 8-char run — short fragments stayed
501        // detectable and the store pass kept re-finding them (2026-09-11).
502        let text = "tokens eyJab and eyJcd appeared in logs";
503        let (once, kinds) = redact_credential_content(text);
504        assert!(kinds.contains(&"jwt"));
505        assert!(
506            credential_shaped_content(&once).is_empty(),
507            "short fragments must read clean after redaction: {once}"
508        );
509        let (twice, _) = redact_credential_content(&once);
510        assert_eq!(once, twice);
511    }
512
513    #[test]
514    fn pem_fragments_are_redacted_too() {
515        // Regression: a truncated/example PEM with no END block fires
516        // detection but has no complete span; the marker strings themselves
517        // must be neutralized so the store pass is idempotent (2026-09-11).
518        let text = "docs explain -----BEGIN PRIVATE KEY----- when truncated";
519        let (once, kinds) = redact_credential_content(text);
520        assert!(kinds.contains(&"private_key_pem"));
521        assert!(
522            credential_shaped_content(&once).is_empty(),
523            "PEM fragments must read clean after redaction: {once}"
524        );
525        let (twice, _) = redact_credential_content(&once);
526        assert_eq!(once, twice);
527    }
528}