claudy 0.8.0

Modern multi-provider launcher for Claude CLI
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
use crate::config::registry::{GuardSettings, SecretPolicy};
use crate::config::vault::redact_credential;
use crate::ports::guard_ports::{ContentScanner, Finding, GuardAction, ScanReport};

use llm_kernel::dlp::{self, FindingCategory, Severity};

/// MVP engine binding: llm-kernel 0.29 `dlp` L1 scan (18 rules — secrets,
/// Korean PII with RRN checksum, local filesystem paths) wrapped in the
/// claudy proxy contract.
///
/// Division of ownership with the kernel:
/// - non-JSON / unparseable-JSON fail-open markers stay proxy-side (the
///   kernel scans extracted text only);
/// - byte identity outside detected spans is preserved — masking splices
///   `[REDACTED:<kind>]` over span bytes and nothing else;
/// - masking keeps the claudy `[REDACTED:<kind>]` format (documented in
///   README/ledger) rather than the kernel's `apply_redactions` `****`,
///   so previews stay kind-labelled.
///
/// Category policy: `Secret` follows the user's `on_secret` setting;
/// `KoreanPii`/`FileSystemPath` are warn-only — EXCEPT checksum-validated
/// RRN (severity Critical), which gets a redact floor: structurally certain
/// PII must not egress unredacted just because paths stay functional.
// ponytail: per-category config knobs when a user actually needs PII
// redaction or path stripping — warn-only keeps coding sessions
// functional (models need real paths to edit files).
pub struct RegexScanner {
    strip_images: bool,
    on_secret: SecretPolicy,
}

impl RegexScanner {
    pub fn new(settings: &GuardSettings) -> Self {
        RegexScanner {
            strip_images: settings.strip_images,
            on_secret: settings.on_secret,
        }
    }

    fn secret_action(&self) -> GuardAction {
        match self.on_secret {
            SecretPolicy::Allow => GuardAction::Allow,
            SecretPolicy::Redact => GuardAction::Redact,
            SecretPolicy::Warn => GuardAction::Warn,
            SecretPolicy::Block => GuardAction::Block,
        }
    }
}

/// Map a kernel rule label to the claudy finding kind (ledger vocabulary).
fn kind_for(rule: &str) -> &'static str {
    match rule {
        "bearer_header" => "auth_header",
        "key_value_assignment" => "key_value",
        "anthropic_key" => "anthropic_key",
        "openai_style_key" => "api_key",
        "stripe_secret_key" => "stripe_key",
        "figma_token" => "figma_token",
        "aws_access_key_id" | "aws_secret_key" => "aws_key",
        "github_token" => "github_token",
        "slack_token" => "slack_token",
        "private_key_header" => "private_key",
        "db_connection_string" => "db_connection",
        "rrn_kr" => "rrn",
        "bank_account_kr" => "bank_account",
        "phone_kr" => "phone",
        "home_path_posix" | "home_path_windows" | "tilde_path" => "local_path",
        _ => "secret",
    }
}

/// Kinds that should trigger the untrusted-provider re-route advisory.
/// Routine observations (image placeholders, boundary markers, local paths)
/// must not nag on every request.
pub fn is_advisory_sensitive(kind: &str) -> bool {
    !matches!(
        kind,
        "non_json" | "unparseable_json" | "local_path" | "image"
    )
}

/// Severity floor for Critical PII (RRN): escalate to Redact unless the
/// user ran `on_secret: block` (stronger) or `allow` (explicit full
/// opt-out — the finding is still recorded as warn).
pub(crate) fn critical_pii_action(secret_action: GuardAction) -> GuardAction {
    match secret_action {
        GuardAction::Block => GuardAction::Block,
        GuardAction::Allow => GuardAction::Warn,
        _ => GuardAction::Redact,
    }
}

impl ContentScanner for RegexScanner {
    fn scan(&self, body: &[u8], content_type: &str) -> ScanReport {
        if !content_type.starts_with("application/json") {
            return fail_open("non_json");
        }
        let mut root: serde_json::Value = match serde_json::from_slice(body) {
            Ok(v) => v,
            Err(_) => return fail_open("unparseable_json"),
        };

        let mut images_stripped = 0usize;
        if self.strip_images {
            images_stripped = replace_image_blocks(&mut root);
        }

        // Scan the original bytes when no surgery happened, so clean requests
        // round-trip byte-identical (serde_json reorders object keys on
        // re-serialization).
        let text = if images_stripped == 0 {
            match std::str::from_utf8(body) {
                Ok(s) => s.to_string(),
                Err(_) => return fail_open("non_json"),
            }
        } else {
            serde_json::to_string(&root).unwrap_or_default()
        };

        let kreport = dlp::scan(&text);

        // Dedup spans (sk-ant keys double-fire anthropic_key +
        // openai_style_key; anthropic_key wins the kind label), resolve the
        // action per category, and collect redaction work.
        let mut findings: Vec<Finding> = Vec::new();
        // (span, kind, action) — one entry per unique span.
        let mut spans: Vec<(dlp::Span, String, GuardAction)> = Vec::new();
        let secret_action = self.secret_action();
        for kf in &kreport.findings {
            let kind = kind_for(&kf.rule);
            let action = match kf.category {
                FindingCategory::Secret => secret_action,
                FindingCategory::KoreanPii if kf.severity >= Severity::Critical => {
                    critical_pii_action(secret_action)
                }
                FindingCategory::KoreanPii | FindingCategory::FileSystemPath => GuardAction::Warn,
                _ => GuardAction::Warn,
            };
            let preview = if matches!(kf.category, FindingCategory::Secret) {
                redact_credential(&text[kf.span.start..kf.span.end])
            } else {
                let raw = &text[kf.span.start..kf.span.end];
                raw.chars().take(48).collect()
            };
            findings.push(Finding {
                kind: kind.to_string(),
                action,
                preview,
            });
            match spans.iter_mut().find(|(s, _, _)| *s == kf.span) {
                Some((_, k, _)) => {
                    if kind == "anthropic_key" {
                        *k = kind.to_string();
                    }
                }
                None => spans.push((kf.span, kind.to_string(), action)),
            }
        }

        let mut redacted = text;
        let mut redacted_any = false;
        if spans
            .iter()
            .any(|(_, _, action)| *action == GuardAction::Redact)
        {
            // Replace descending by start so earlier byte offsets stay valid.
            let mut work: Vec<_> = spans
                .iter()
                .filter(|(_, _, action)| *action == GuardAction::Redact)
                .collect();
            work.sort_by_key(|(span, _, _)| std::cmp::Reverse(span.start));
            for (span, kind, _) in work {
                redacted.replace_range(span.start..span.end, &format!("[REDACTED:{}]", kind));
                redacted_any = true;
            }
        }

        if images_stripped > 0 {
            findings.push(Finding {
                kind: "image".to_string(),
                action: if self.strip_images {
                    GuardAction::Redact
                } else {
                    GuardAction::Allow
                },
                preview: format!("{} block(s)", images_stripped),
            });
        }

        let redacted_body = if images_stripped > 0 || redacted_any {
            Some(redacted.into_bytes())
        } else {
            None
        };

        ScanReport {
            findings,
            redacted_body,
            images_stripped,
        }
    }
}

fn fail_open(kind: &str) -> ScanReport {
    ScanReport {
        findings: vec![Finding {
            kind: kind.to_string(),
            action: GuardAction::Warn,
            preview: String::new(),
        }],
        redacted_body: None,
        images_stripped: 0,
    }
}

/// Replace every `{"type":"image", ...}` block with a text placeholder.
/// Generic recursive walk: legitimate image blocks appear in
/// `system`/`messages[*].content`/`tool_result.content` block arrays, and a
/// schema-shaped `{"type":"image"}` object elsewhere is vanishingly rare.
/// Replacement (not deletion) keeps block counts and tool_result validity.
fn replace_image_blocks(v: &mut serde_json::Value) -> usize {
    match v {
        serde_json::Value::Object(obj) => {
            if obj.get("type").and_then(|t| t.as_str()) == Some("image") {
                *v = serde_json::json!({
                    "type": "text",
                    "text": "[claudy-guard: image block removed]"
                });
                return 1;
            }
            obj.values_mut().map(replace_image_blocks).sum()
        }
        serde_json::Value::Array(items) => items.iter_mut().map(replace_image_blocks).sum(),
        _ => 0,
    }
}

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

    fn scanner(on_secret: SecretPolicy) -> RegexScanner {
        RegexScanner::new(&GuardSettings {
            strip_images: true,
            on_secret,
            trusted_providers: vec!["native".to_string()],
        })
    }

    #[test]
    fn strips_image_block_in_messages_content() {
        let body = serde_json::json!({
            "model": "glm-5",
            "messages": [
                {"role": "user", "content": [
                    {"type": "text", "text": "what is this"},
                    {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aGk="}}
                ]}
            ]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert_eq!(report.images_stripped, 1);
        let out: serde_json::Value =
            serde_json::from_slice(&report.redacted_body.unwrap()).unwrap();
        let content = out["messages"][0]["content"].as_array().unwrap();
        assert_eq!(content.len(), 2, "replacement, not deletion");
        assert_eq!(content[1]["type"], "text");
        assert!(
            content[1]["text"]
                .as_str()
                .unwrap()
                .contains("image block removed")
        );
    }

    #[test]
    fn strips_image_block_in_tool_result_nested_content() {
        let body = serde_json::json!({
            "messages": [
                {"role": "user", "content": [
                    {"type": "tool_result", "tool_use_id": "t1", "content": [
                        {"type": "text", "text": "screenshot"},
                        {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aGk="}}
                    ]}
                ]}
            ]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert_eq!(report.images_stripped, 1);
        let out: serde_json::Value =
            serde_json::from_slice(&report.redacted_body.unwrap()).unwrap();
        let nested = &out["messages"][0]["content"][0]["content"];
        assert_eq!(nested.as_array().unwrap().len(), 2);
        assert_eq!(nested[1]["type"], "text");
    }

    #[test]
    fn strips_image_block_in_system_block_array() {
        let body = serde_json::json!({
            "system": [
                {"type": "text", "text": "be helpful"},
                {"type": "image", "source": {"type": "url", "url": "https://x/1.png"}}
            ],
            "messages": []
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert_eq!(report.images_stripped, 1);
    }

    #[test]
    fn clean_body_returns_none_redacted_body() {
        let body = br#"{"model":"glm-5","messages":[{"role":"user","content":"hello"}]}"#;
        let report = scanner(SecretPolicy::Redact).scan(body, "application/json");
        assert!(report.redacted_body.is_none());
        assert!(report.findings.is_empty());
    }

    #[test]
    fn redacts_authorization_bearer_header() {
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "leak: Authorization: Bearer abcdefghijklmnop123456 said hi"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert!(report.redacted_body.is_some());
        let out = String::from_utf8(report.redacted_body.unwrap()).unwrap();
        assert!(out.contains("[REDACTED:auth_header]"), "got: {out}");
        assert!(!out.contains("abcdefghijklmnop123456"));
        assert_eq!(report.findings[0].kind, "auth_header");
        assert!(!report.findings[0].preview.contains("abcdefghijklmnop"));
    }

    #[test]
    fn redacts_sk_ant_key_with_anthropic_priority() {
        // sk-ant keys double-fire anthropic_key + openai_style_key; the
        // kind label must resolve to anthropic_key.
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "key sk-ant-api03-abcdef1234567890abcdef was rotated"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert!(report.findings.iter().any(|f| f.kind == "anthropic_key"));
        let out = String::from_utf8(report.redacted_body.unwrap()).unwrap();
        assert!(out.contains("[REDACTED:anthropic_key]"));
        assert!(!out.contains("abcdef1234567890abcdef"));
    }

    #[test]
    fn redacts_slack_xoxb_token() {
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "xoxb-1234567890abcdefghij"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert_eq!(report.findings[0].kind, "slack_token");
        let out = String::from_utf8(report.redacted_body.unwrap()).unwrap();
        assert!(out.contains("[REDACTED:slack_token]"));
    }

    #[test]
    fn json_key_colon_value_pair_not_flagged() {
        // JSON `"api_key":"value"` with a short value — no match.
        let body = br#"{"messages":[{"role":"user","content":"see api_key settings"}],"metadata":{"api_key":"short"}}"#;
        let report = scanner(SecretPolicy::Redact).scan(body, "application/json");
        assert!(report.findings.is_empty());
        assert!(report.redacted_body.is_none());
    }

    #[test]
    fn local_path_recorded_but_not_redacted() {
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "edit /Users/tester/dev/proj/src/main.rs please"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == "local_path" && f.action == GuardAction::Warn)
        );
        assert!(report.redacted_body.is_none(), "paths stay functional");
    }

    #[test]
    fn checksum_valid_rrn_gets_critical_redact_floor() {
        // 901101-1234564 passes the RRN checksum; 901101-1234567 does not.
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "user rrn 901101-1234564 registered"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        let rrn = report
            .findings
            .iter()
            .find(|f| f.kind == "rrn")
            .expect("valid RRN detected");
        assert_eq!(rrn.action, GuardAction::Redact);
        let out = String::from_utf8(report.redacted_body.expect("redacted")).unwrap();
        assert!(out.contains("[REDACTED:rrn]"));
        assert!(!out.contains("901101-1234564"));
    }

    #[test]
    fn checksum_invalid_rrn_shape_not_flagged() {
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "order 901101-1234567 shipped"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert!(!report.findings.iter().any(|f| f.kind == "rrn"));
        assert!(report.redacted_body.is_none());
    }

    #[test]
    fn bank_account_and_phone_stay_warn() {
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "계좌번호: 123-456-789012 / 010-1234-5678 로 연락"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == "bank_account" && f.action == GuardAction::Warn)
        );
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.kind == "phone" && f.action == GuardAction::Warn)
        );
        assert!(report.redacted_body.is_none());
    }

    #[test]
    fn non_json_content_type_fails_open() {
        let report = scanner(SecretPolicy::Redact).scan(b"raw", "text/event-stream");
        assert_eq!(report.findings[0].kind, "non_json");
        assert!(report.redacted_body.is_none());
    }

    #[test]
    fn unparseable_json_fails_open() {
        let report = scanner(SecretPolicy::Redact).scan(b"{broken", "application/json");
        assert_eq!(report.findings[0].kind, "unparseable_json");
        assert!(report.redacted_body.is_none());
    }

    #[test]
    fn block_policy_returns_finding_without_redacted_body() {
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "leak: Authorization: Bearer abcdefghijklmnop123456"}]
        });
        let report =
            scanner(SecretPolicy::Block).scan(body.to_string().as_bytes(), "application/json");
        assert!(
            report
                .findings
                .iter()
                .any(|f| f.action == GuardAction::Block)
        );
        assert!(
            report.redacted_body.is_none(),
            "blocked body must not be rewritten/forwarded"
        );
    }

    #[test]
    fn redaction_keeps_json_parseable() {
        // Redacted span must never swallow the closing quote of a JSON string.
        let body = serde_json::json!({
            "messages": [{"role": "user", "content": "password=supersecret123 was in .env"}]
        });
        let report =
            scanner(SecretPolicy::Redact).scan(body.to_string().as_bytes(), "application/json");
        let out = String::from_utf8(report.redacted_body.unwrap()).unwrap();
        let reparsed: serde_json::Value = serde_json::from_str(&out).expect("JSON stays parseable");
        assert!(reparsed["messages"][0]["content"].is_string());
    }
}