zeph-core 0.18.0

Core agent loop, configuration, context builder, metrics, and vault for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use std::borrow::Cow;
use std::sync::LazyLock;

/// Apply both secret redaction and path sanitization in a single pass.
///
/// Returns `Cow::Borrowed` when no changes are needed (zero-allocation fast path).
#[must_use]
pub fn scrub_content(text: &str) -> Cow<'_, str> {
    let after_secrets = match redact_secrets(text) {
        Cow::Borrowed(_) => {
            // No secrets found: only run path scan on original text
            return match sanitize_paths(text) {
                Cow::Owned(s) => Cow::Owned(s),
                Cow::Borrowed(_) => Cow::Borrowed(text),
            };
        }
        Cow::Owned(s) => s,
    };

    // Second pass: path sanitization on already-modified string
    match sanitize_paths(&after_secrets) {
        Cow::Owned(s) => Cow::Owned(s),
        Cow::Borrowed(_) => Cow::Owned(after_secrets),
    }
}

use regex::Regex;

const SECRET_PREFIXES: &[&str] = &[
    "sk-",
    "sk_live_",
    "sk_test_",
    "AKIA",
    "ghp_",
    "gho_",
    "-----BEGIN",
    "xoxb-",
    "xoxp-",
    "AIza",
    "ya29\\.",
    "glpat-",
    "hf_",
    "npm_",
    "dckr_pat_",
];

// Matches any secret prefix followed by non-whitespace characters.
// Using alternation so a single pass covers all prefixes.
static SECRET_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    let pattern = SECRET_PREFIXES.join("|");
    let full = format!("(?:{pattern})[^\\s\"'`,;{{}}\\[\\]]*");
    Regex::new(&full).expect("secret redaction regex is valid")
});

static PATH_REGEX: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?:/home/|/Users/|/root/|/tmp/|/var/)[^\s"'`,;{}\[\]]*"#)
        .expect("path redaction regex is valid")
});

/// Replace tokens containing known secret patterns with `[REDACTED]`.
///
/// Detects secrets embedded in URLs, JSON values, and quoted strings.
/// Returns `Cow::Borrowed` when no secrets found (zero-allocation fast path).
#[must_use]
pub fn redact_secrets(text: &str) -> Cow<'_, str> {
    // Fast path: check for any prefix substring before running regex.
    let raw_prefixes = &[
        "sk-",
        "sk_live_",
        "sk_test_",
        "AKIA",
        "ghp_",
        "gho_",
        "-----BEGIN",
        "xoxb-",
        "xoxp-",
        "AIza",
        "ya29.",
        "glpat-",
        "hf_",
        "npm_",
        "dckr_pat_",
    ];
    if !raw_prefixes.iter().any(|p| text.contains(p)) {
        return Cow::Borrowed(text);
    }

    let result = SECRET_REGEX.replace_all(text, "[REDACTED]");
    match result {
        Cow::Borrowed(_) => Cow::Borrowed(text),
        Cow::Owned(s) => Cow::Owned(s),
    }
}

/// Replace absolute filesystem paths with `[PATH]` to prevent information disclosure.
#[must_use]
pub fn sanitize_paths(text: &str) -> Cow<'_, str> {
    const PATH_PREFIXES: &[&str] = &["/home/", "/Users/", "/root/", "/tmp/", "/var/"];

    if !PATH_PREFIXES.iter().any(|p| text.contains(p)) {
        return Cow::Borrowed(text);
    }

    let result = PATH_REGEX.replace_all(text, "[PATH]");
    match result {
        Cow::Borrowed(_) => Cow::Borrowed(text),
        Cow::Owned(s) => Cow::Owned(s),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn redacts_openai_key() {
        let text = "Use key sk-abc123def456 for API calls";
        let result = redact_secrets(text);
        assert_eq!(result, "Use key [REDACTED] for API calls");
    }

    #[test]
    fn redacts_stripe_live_key() {
        let text = "Stripe key: sk_live_abcdef123456";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("sk_live_"));
    }

    #[test]
    fn redacts_stripe_test_key() {
        let text = "Test key sk_test_abc123";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn redacts_aws_key() {
        let text = "AWS access key: AKIAIOSFODNN7EXAMPLE";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("AKIA"));
    }

    #[test]
    fn redacts_github_pat() {
        let text = "Token: ghp_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("ghp_"));
    }

    #[test]
    fn redacts_github_oauth() {
        let text = "OAuth: gho_xxxxxxxxxxxx";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
    }

    #[test]
    fn redacts_private_key_header() {
        let text = "Found -----BEGIN RSA PRIVATE KEY----- in file";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("-----BEGIN"));
    }

    #[test]
    fn redacts_slack_tokens() {
        let text = "Bot token xoxb-123-456 and user xoxp-789";
        let result = redact_secrets(text);
        assert_eq!(result, "Bot token [REDACTED] and user [REDACTED]");
    }

    #[test]
    fn preserves_normal_text() {
        let text = "This is a normal response with no secrets";
        let result = redact_secrets(text);
        assert_eq!(result, text);
        assert!(matches!(result, Cow::Borrowed(_)));
    }

    #[test]
    fn handles_empty_string() {
        assert_eq!(redact_secrets(""), "");
    }

    #[test]
    fn multiple_secrets_redacted() {
        let text = "Keys: sk-abc123 AKIAIOSFODNN7 ghp_xxxxx";
        let result = redact_secrets(text);
        assert_eq!(result, "Keys: [REDACTED] [REDACTED] [REDACTED]");
    }

    #[test]
    fn preserves_multiline_whitespace() {
        let text = "Line one\n  indented line\n\ttabbed line\nsk-secret here";
        let result = redact_secrets(text);
        assert_eq!(
            result,
            "Line one\n  indented line\n\ttabbed line\n[REDACTED] here"
        );
    }

    #[test]
    fn preserves_code_block_formatting() {
        let text = "```rust\nfn main() {\n    let key = \"sk-abc123\";\n    println!(\"{}\", key);\n}\n```";
        let result = redact_secrets(text);
        assert!(result.contains("```rust\nfn"));
        assert!(result.contains("    let"));
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("sk-abc123"));
    }

    #[test]
    fn preserves_multiple_spaces() {
        let text = "word1   word2     word3";
        let result = redact_secrets(text);
        assert_eq!(result, text);
    }

    #[test]
    fn no_allocation_without_secrets() {
        let text = "safe text without any secrets";
        let result = redact_secrets(text);
        assert!(matches!(result, Cow::Borrowed(_)));
    }

    #[test]
    fn all_secret_prefixes_tested() {
        for prefix in &[
            "sk-",
            "sk_live_",
            "sk_test_",
            "AKIA",
            "ghp_",
            "gho_",
            "-----BEGIN",
            "xoxb-",
            "xoxp-",
            "AIza",
            "ya29.",
            "glpat-",
            "hf_",
            "npm_",
            "dckr_pat_",
        ] {
            let text = format!("token: {prefix}abc123");
            let result = redact_secrets(&text);
            assert!(result.contains("[REDACTED]"), "Failed for prefix: {prefix}");
            assert!(!result.contains(*prefix), "Prefix not redacted: {prefix}");
        }
    }

    #[test]
    fn redacts_google_api_key() {
        let text = "Google key: AIzaSyA1234567890abcdefghijklmnop";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("AIza"));
    }

    #[test]
    fn redacts_google_oauth_token() {
        let text = "OAuth token ya29.a0AfH6SMBx1234567890";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("ya29."));
    }

    #[test]
    fn redacts_gitlab_pat() {
        let text = "GitLab token: glpat-xxxxxxxxxxxxxxxxxxxx";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("glpat-"));
    }

    #[test]
    fn only_whitespace() {
        assert_eq!(redact_secrets("   \n\t  "), "   \n\t  ");
    }

    #[test]
    fn secret_at_end_of_line() {
        let text = "token: sk-abc123";
        let result = redact_secrets(text);
        assert_eq!(result, "token: [REDACTED]");
    }

    #[test]
    fn redacts_secret_in_url() {
        let text = "https://api.example.com?key=sk-abc123xyz";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("sk-abc123xyz"));
    }

    #[test]
    fn redacts_secret_in_json() {
        let text = r#"{"api_key":"sk-abc123def456"}"#;
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("sk-abc123def456"));
    }

    #[test]
    fn sanitize_home_path() {
        let text = "error at /home/user/project/src/main.rs:42";
        let result = sanitize_paths(text);
        assert_eq!(result, "error at [PATH]");
    }

    #[test]
    fn sanitize_users_path() {
        let text = "failed: /Users/dev/code/lib.rs not found";
        let result = sanitize_paths(text);
        assert!(result.contains("[PATH]"));
        assert!(!result.contains("/Users/"));
    }

    #[test]
    fn sanitize_no_paths() {
        let text = "normal error message";
        let result = sanitize_paths(text);
        assert!(matches!(result, Cow::Borrowed(_)));
    }

    #[test]
    fn redacts_huggingface_token() {
        let text = "HuggingFace token: hf_abcdefghijklmnopqrstuvwxyz";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("hf_"));
    }

    #[test]
    fn redacts_npm_token() {
        let text = "NPM token npm_abc123XYZ";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("npm_abc"));
    }

    #[test]
    fn redacts_docker_pat() {
        let text = "Docker token: dckr_pat_xxxxxxxxxxxx";
        let result = redact_secrets(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("dckr_pat_"));
    }

    use proptest::prelude::*;

    #[test]
    fn scrub_no_match_passthrough() {
        let text = "hello world, nothing sensitive here";
        let result = scrub_content(text);
        assert!(matches!(result, Cow::Borrowed(_)));
        assert_eq!(result.as_ref(), text);
    }

    #[test]
    fn scrub_only_secrets() {
        let text = "key: sk-abc123def";
        let result = scrub_content(text);
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("sk-abc123"));
        assert!(!result.contains("/home/"));
    }

    #[test]
    fn scrub_only_paths() {
        let text = "error at /Users/dev/project/src/main.rs:42";
        let result = scrub_content(text);
        assert!(result.contains("[PATH]"));
        assert!(!result.contains("/Users/dev/"));
    }

    #[test]
    fn scrub_secrets_and_paths_combined() {
        let text = "token sk-abc123 found at /home/user/config.toml";
        let result = scrub_content(text);
        assert!(result.contains("[REDACTED]"));
        assert!(result.contains("[PATH]"));
        assert!(!result.contains("sk-abc123"));
        assert!(!result.contains("/home/user/"));
    }

    #[test]
    fn scrub_secrets_no_paths() {
        // Secret found but no path → function returns Cow::Owned (modified string)
        let text = "use sk-abc123 for auth";
        let result = scrub_content(text);
        assert!(
            matches!(result, Cow::Owned(_)),
            "must return Cow::Owned when secret was found"
        );
        assert!(result.contains("[REDACTED]"));
        assert!(!result.contains("[PATH]"));
    }

    #[test]
    fn sanitize_paths_all_prefixes() {
        let cases = [
            ("/root/secrets.toml", "/root/"),
            ("/tmp/tmpfile.lock", "/tmp/"),
            ("/var/log/app.log", "/var/"),
        ];
        for (text, prefix) in cases {
            let result = sanitize_paths(text);
            assert!(result.contains("[PATH]"), "{prefix} must be sanitized");
            assert!(
                !result.contains(prefix),
                "{prefix} must be removed from output"
            );
        }
    }

    proptest! {
        #[test]
        fn redact_secrets_never_panics(s in ".*") {
            let _ = redact_secrets(&s);
        }

        #[test]
        fn sanitize_paths_never_panics(s in ".*") {
            let _ = sanitize_paths(&s);
        }

        #[test]
        fn redact_preserves_non_secret_text(s in "[a-zA-Z0-9 .,!?]{1,200}") {
            // Only test strings that genuinely contain no secret prefixes.
            let secret_prefixes = [
                "sk-", "sk_live_", "sk_test_", "AKIA", "ghp_", "gho_",
                "-----BEGIN", "xoxb-", "xoxp-", "AIza", "ya29.", "glpat-",
                "hf_", "npm_", "dckr_pat_",
            ];
            if !secret_prefixes.iter().any(|p| s.contains(p)) {
                let result = redact_secrets(&s);
                assert_eq!(result.as_ref(), s.as_str());
            }
        }

        #[test]
        fn scrub_content_never_panics(s in ".*") {
            let _ = scrub_content(&s);
        }

        #[test]
        fn scrub_content_result_never_contains_raw_secret(s in ".*") {
            let result = scrub_content(&s);
            let secret_prefixes = [
                "sk-", "sk_live_", "sk_test_", "AKIA", "ghp_", "gho_",
                "xoxb-", "xoxp-", "AIza", "glpat-", "dckr_pat_",
            ];
            for prefix in secret_prefixes {
                assert!(
                    !result.contains(prefix),
                    "scrub_content must redact prefix: {prefix}"
                );
            }
        }
    }
}