caretta 0.14.1

caretta agent
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
use crate::agent::types::{AgentEvent, EVENT_SENDER};
use regex::Regex;
use serde_json::Value;
use std::collections::HashSet;
use std::path::Path;
use std::process::{self, Command, Stdio};
use std::sync::{LazyLock, RwLock};
use tracing::info;

#[cfg(not(target_arch = "wasm32"))]
pub use toak_rs::count_tokens;

#[cfg(target_arch = "wasm32")]
pub fn count_tokens(s: &str) -> usize {
    s.len() / 4
}

/// Log the elapsed time for a labelled operation.
#[macro_export]
macro_rules! timed {
    ($label:expr, $body:expr) => {{
        let _t0 = Instant::now();
        let _result = $body;
        $crate::agent::cmd::log(&format!(
            "[timing] {} completed in {:.2?}",
            $label,
            _t0.elapsed()
        ));
        _result
    }};
}

pub fn die(msg: &str) -> ! {
    eprintln!("ERROR: {msg}");
    process::exit(1);
}

pub fn log(msg: &str) {
    let sanitized = sanitize_log_message(msg);
    info!("{sanitized}");
    if let Some(tx) = EVENT_SENDER.get() {
        let _ = tx.send(AgentEvent::Log(sanitized));
    }
}

static KV_QUOTED_SECRET_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?i)("?(?P<key>api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|token|secret|password|passwd|authorization)"?\s*[:=]\s*")(?P<value>[^"\\]{4,})(")"#)
        .expect("valid secret kv quoted regex")
});
static KV_BARE_SECRET_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?i)(?P<key>api[_-]?key|access[_-]?token|refresh[_-]?token|id[_-]?token|token|secret|password|passwd|authorization)(?P<sep>\s*[:=]\s*)(?P<value>[^\s,;]+)"#)
        .expect("valid secret kv bare regex")
});
static AUTH_BEARER_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?i)(authorization\s*:\s*bearer\s+)([A-Za-z0-9._~+/\-=]+)"#)
        .expect("valid authorization bearer regex")
});
static GH_TOKEN_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"\b(gh[pousr]_[A-Za-z0-9_]{16,})\b"#).expect("valid gh token regex")
});
static OPENAI_TOKEN_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"\b(sk-[A-Za-z0-9_-]{16,})\b"#).expect("valid openai token regex")
});
static AWS_ACCESS_KEY_ID_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"\b(AKIA[0-9A-Z]{16})\b"#).expect("valid aws access key id regex")
});
static PRIVATE_KEY_BLOCK_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"(?s)-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----.*?-----END [A-Z0-9 ]*PRIVATE KEY-----"#)
        .expect("valid private key block regex")
});
static EMAIL_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}"#).expect("valid email regex")
});
static UUID_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r#"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"#)
        .expect("valid uuid regex")
});

#[derive(Default)]
struct RuntimeRedactionConfig {
    allowlist_keys: HashSet<String>,
    denylist_regexes: Vec<Regex>,
}

static LOG_REDACTION_CONFIG: LazyLock<RwLock<RuntimeRedactionConfig>> =
    LazyLock::new(|| RwLock::new(RuntimeRedactionConfig::default()));

pub fn configure_log_redaction(cfg: &cli_common::LogRedactionConfigFile) {
    let allowlist_keys = cfg
        .allowlist_keys
        .iter()
        .map(|k| k.trim().to_ascii_lowercase())
        .filter(|k| !k.is_empty())
        .collect::<HashSet<_>>();
    let denylist_regexes = cfg
        .denylist_patterns
        .iter()
        .filter_map(|p| Regex::new(p).ok())
        .collect::<Vec<_>>();
    if let Ok(mut state) = LOG_REDACTION_CONFIG.write() {
        state.allowlist_keys = allowlist_keys;
        state.denylist_regexes = denylist_regexes;
    }
}

pub fn sanitize_log_message(msg: &str) -> String {
    let state = LOG_REDACTION_CONFIG.read().ok();
    sanitize_log_message_with_cfg(msg, state.as_deref())
}

fn sanitize_log_message_with_cfg(msg: &str, cfg: Option<&RuntimeRedactionConfig>) -> String {
    let out = sanitize_json_if_detected(msg, cfg).unwrap_or_else(|| msg.to_string());
    let out = PRIVATE_KEY_BLOCK_RE
        .replace_all(&out, "[REDACTED_PRIVATE_KEY]")
        .into_owned();
    let out = KV_QUOTED_SECRET_RE
        .replace_all(&out, |caps: &regex::Captures<'_>| {
            let key = caps
                .name("key")
                .map_or("", |m| m.as_str())
                .to_ascii_lowercase();
            if cfg.is_some_and(|c| c.allowlist_keys.contains(&key)) {
                caps.get(0)
                    .map_or(String::new(), |m| m.as_str().to_string())
            } else {
                format!("{}[REDACTED]{}", &caps[1], &caps[4])
            }
        })
        .into_owned();
    let out = AUTH_BEARER_RE
        .replace_all(&out, "$1[REDACTED]")
        .into_owned();
    let out = KV_BARE_SECRET_RE
        .replace_all(&out, |caps: &regex::Captures<'_>| {
            let key = caps
                .name("key")
                .map_or("", |m| m.as_str())
                .to_ascii_lowercase();
            if cfg.is_some_and(|c| c.allowlist_keys.contains(&key)) {
                return caps
                    .get(0)
                    .map_or(String::new(), |m| m.as_str().to_string());
            }
            let value = caps.name("value").map_or("", |m| m.as_str());
            if value.eq_ignore_ascii_case("bearer") {
                caps.get(0)
                    .map_or(String::new(), |m| m.as_str().to_string())
            } else {
                format!("{}{}[REDACTED]", &caps["key"], &caps["sep"])
            }
        })
        .into_owned();
    let out = GH_TOKEN_RE
        .replace_all(&out, "[REDACTED_GH_TOKEN]")
        .into_owned();
    let out = OPENAI_TOKEN_RE
        .replace_all(&out, "[REDACTED_OPENAI_KEY]")
        .into_owned();
    let out = AWS_ACCESS_KEY_ID_RE
        .replace_all(&out, "[REDACTED_AWS_ACCESS_KEY_ID]")
        .into_owned();
    let out = redact_sensitive_plain_text(out);
    if let Some(cfg) = cfg {
        cfg.denylist_regexes.iter().fold(out, |acc, re| {
            re.replace_all(&acc, "[REDACTED_CUSTOM]").into_owned()
        })
    } else {
        out
    }
}

fn sanitize_json_if_detected(msg: &str, cfg: Option<&RuntimeRedactionConfig>) -> Option<String> {
    let trimmed = msg.trim();
    let (json_start, json_end) = if trimmed.starts_with('{') || trimmed.starts_with('[') {
        (0, trimmed.len().saturating_sub(1))
    } else {
        let start = trimmed.find('{').or_else(|| trimmed.find('['))?;
        let end = trimmed
            .rfind('}')
            .or_else(|| trimmed.rfind(']'))
            .filter(|end| *end > start)?;
        (start, end)
    };
    if json_start > json_end {
        return None;
    }
    let candidate = &trimmed[json_start..=json_end];
    let Ok(value) = serde_json::from_str::<Value>(candidate) else {
        return None;
    };
    let value = sanitize_json_value(value, None, cfg);
    let redacted = serde_json::to_string(&value).ok()?;
    if json_start == 0 && json_end + 1 == trimmed.len() {
        return Some(redacted);
    }
    let mut out = String::with_capacity(trimmed.len());
    out.push_str(&trimmed[..json_start]);
    out.push_str(&redacted);
    if json_end + 1 < trimmed.len() {
        out.push_str(&trimmed[json_end + 1..]);
    }
    Some(out)
}

fn sanitize_json_value(
    value: Value,
    parent: Option<&str>,
    cfg: Option<&RuntimeRedactionConfig>,
) -> Value {
    match value {
        Value::Object(map) => {
            let mut out = serde_json::Map::with_capacity(map.len());
            for (key, child_value) in map {
                let should_redact = should_redact_json_key(&key, parent, cfg);
                let next = if should_redact {
                    Value::String("[REDACTED]".to_string())
                } else {
                    sanitize_json_value(child_value, Some(&key), cfg)
                };
                out.insert(key, next);
            }
            Value::Object(out)
        }
        Value::Array(values) => Value::Array(
            values
                .into_iter()
                .map(|value| sanitize_json_value(value, parent, cfg))
                .collect(),
        ),
        Value::String(value) => Value::String(redact_sensitive_string(value)),
        _ => value,
    }
}

fn should_redact_json_key(
    key: &str,
    parent: Option<&str>,
    cfg: Option<&RuntimeRedactionConfig>,
) -> bool {
    let key_lc = key.to_ascii_lowercase();
    if cfg.is_some_and(|c| c.allowlist_keys.contains(&key_lc)) {
        return false;
    }
    if matches!(
        key_lc.as_str(),
        "email"
            | "login"
            | "username"
            | "account"
            | "account_id"
            | "user_id"
            | "session"
            | "session_id"
            | "thread"
            | "thread_id"
            | "auth"
            | "authorization"
            | "access_token"
            | "id_token"
            | "refresh_token"
    ) {
        return true;
    }
    if key_lc.ends_with("_id")
        && (key_lc.contains("session")
            || key_lc.contains("thread")
            || key_lc.contains("account")
            || key_lc.contains("user")
            || key_lc.contains("actor")
            || key_lc.contains("owner"))
    {
        return true;
    }
    if key_lc == "id" {
        let Some(parent) = parent.map(|p| p.to_ascii_lowercase()) else {
            return false;
        };
        matches!(
            parent.as_str(),
            "thread" | "session" | "account" | "user" | "actor" | "author" | "owner"
        )
    } else {
        false
    }
}

fn redact_sensitive_string(input: String) -> String {
    let out = EMAIL_RE
        .replace_all(&input, "[REDACTED_EMAIL]")
        .into_owned();
    UUID_RE.replace_all(&out, "[REDACTED_UUID]").into_owned()
}

fn redact_sensitive_plain_text(msg: String) -> String {
    let out = EMAIL_RE.replace_all(&msg, "[REDACTED_EMAIL]").into_owned();
    UUID_RE.replace_all(&out, "[REDACTED_UUID]").into_owned()
}

/// Run a command, return trimmed stdout or None on failure.
pub fn cmd_stdout(program: &str, args: &[&str]) -> Option<String> {
    Command::new(program)
        .args(args)
        .stderr(Stdio::inherit())
        .output()
        .ok()
        .filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
}

/// Run a command, return trimmed stdout or die.
pub fn cmd_stdout_or_die(program: &str, args: &[&str], context: &str) -> String {
    cmd_stdout(program, args).unwrap_or_else(|| die(context))
}

/// Default branch on `origin` (commonly `main` or `master`).
///
/// Uses `refs/remotes/origin/HEAD` when present; otherwise checks for
/// `origin/main` and `origin/master`. Falls back to `"main"`.
pub fn origin_default_branch() -> String {
    if let Some(sym) = cmd_stdout(
        "git",
        &["symbolic-ref", "--quiet", "refs/remotes/origin/HEAD"],
    ) && let Some(short) = trim_origin_head_to_branch(&sym)
    {
        return short.to_string();
    }
    for name in ["main", "master"] {
        if cmd_stdout(
            "git",
            &[
                "rev-parse",
                "--quiet",
                "--verify",
                &format!("refs/remotes/origin/{name}"),
            ],
        )
        .is_some()
        {
            return name.to_string();
        }
    }
    "main".to_string()
}

fn trim_origin_head_to_branch(sym: &str) -> Option<&str> {
    let s = sym.trim();
    s.strip_prefix("refs/remotes/origin/")
        .filter(|b| !b.is_empty())
}

/// Run a command, inheriting stdio. Returns success bool.
pub fn cmd_run(program: &str, args: &[&str]) -> bool {
    Command::new(program)
        .args(args)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Run a command in a specific directory, inheriting stdio. Returns success bool.
pub fn cmd_run_in(program: &str, args: &[&str], dir: &Path) -> bool {
    Command::new(program)
        .args(args)
        .current_dir(dir)
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

/// Run a command with extra env vars set, inheriting stdio. Returns success bool.
pub fn cmd_run_env(program: &str, args: &[&str], env: &[(String, String)]) -> bool {
    let mut cmd = Command::new(program);
    cmd.args(args);
    for (k, v) in env {
        cmd.env(k, v);
    }
    cmd.status().map(|s| s.success()).unwrap_or(false)
}

/// Run a command, capture combined stdout+stderr. Returns (success, output).
pub fn cmd_capture(program: &str, args: &[&str]) -> (bool, String) {
    match Command::new(program)
        .args(args)
        .stderr(Stdio::piped())
        .stdout(Stdio::piped())
        .output()
    {
        Ok(o) => {
            let combined = format!(
                "{}{}",
                String::from_utf8_lossy(&o.stdout),
                String::from_utf8_lossy(&o.stderr)
            );
            (o.status.success(), combined)
        }
        Err(e) => (false, e.to_string()),
    }
}

pub fn has_command(name: &str) -> bool {
    Command::new("which")
        .arg(name)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

pub fn list_all_files(root: &str) -> Vec<String> {
    cmd_stdout(
        "git",
        &[
            "-C",
            root,
            "ls-files",
            "--cached",
            "--others",
            "--exclude-standard",
        ],
    )
    .unwrap_or_default()
    .lines()
    .map(|s| s.to_string())
    .collect()
}

#[cfg(test)]
mod tests {
    use super::{configure_log_redaction, sanitize_log_message, trim_origin_head_to_branch};
    use cli_common::LogRedactionConfigFile;
    use std::sync::{LazyLock, Mutex, MutexGuard};

    static LOG_REDACTION_TEST_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

    fn lock_redaction_tests() -> MutexGuard<'static, ()> {
        LOG_REDACTION_TEST_LOCK
            .lock()
            .expect("log redaction test mutex poisoned")
    }

    fn reset_redaction_config() {
        configure_log_redaction(&LogRedactionConfigFile::default());
    }

    #[test]
    fn redacts_json_secret_fields() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        let input = r#"claude: {"api_key":"supersecret123","token":"abc123"}"#;
        let out = sanitize_log_message(input);
        assert!(!out.contains("supersecret123"));
        assert!(!out.contains("abc123"));
        assert!(out.contains(r#""api_key":"[REDACTED]""#));
        assert!(out.contains(r#""token":"[REDACTED]""#));
    }

    #[test]
    fn redacts_bearer_auth() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        let input = "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
        let out = sanitize_log_message(input);
        assert!(!out.contains("eyJhbGci"));
        assert!(out.contains("Authorization: Bearer [REDACTED]"));
    }

    #[test]
    fn redacts_provider_token_prefixes() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        let input = "tokens ghp_abcdefghijklmnopqrstuvwxyz123456 and sk-proj-abcDEF1234567890";
        let out = sanitize_log_message(input);
        assert!(out.contains("[REDACTED_GH_TOKEN]"));
        assert!(out.contains("[REDACTED_OPENAI_KEY]"));
    }

    #[test]
    fn redacts_private_key_blocks() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        let input = "BEGIN\n-----BEGIN PRIVATE KEY-----\nabc123\n-----END PRIVATE KEY-----\nEND";
        let out = sanitize_log_message(input);
        assert!(!out.contains("abc123"));
        assert!(out.contains("[REDACTED_PRIVATE_KEY]"));
    }

    #[test]
    fn redacts_codex_json_session_metadata() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        let input = r#"codex: {"type":"thread.started","thread_id":"thread_abc123","account":{"id":"acc_987","email":"alice@example.com","name":"Alice"}}"#;
        let out = sanitize_log_message(input);
        assert!(!out.contains("thread_abc123"));
        assert!(!out.contains("alice@example.com"));
        assert!(out.contains(r#""thread_id":"[REDACTED]""#));
        assert!(out.contains(r#""account":"[REDACTED]""#));
    }

    #[test]
    fn redacts_email_in_plain_text() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        let input = "codex: signed in as alice@example.com for session review";
        let out = sanitize_log_message(input);
        assert!(!out.contains("alice@example.com"));
        assert!(out.contains("[REDACTED_EMAIL]"));
    }

    #[test]
    fn redacts_custom_denylist_patterns() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        configure_log_redaction(&LogRedactionConfigFile {
            denylist_patterns: vec![r#"orgsec_[A-Za-z0-9]{6,}"#.to_string()],
            allowlist_keys: vec![],
        });
        let out = sanitize_log_message("token orgsec_AbCdEf1234");
        assert!(out.contains("[REDACTED_CUSTOM]"));
    }

    #[test]
    fn honors_allowlist_keys() {
        let _guard = lock_redaction_tests();
        reset_redaction_config();
        configure_log_redaction(&LogRedactionConfigFile {
            denylist_patterns: vec![],
            allowlist_keys: vec!["token".to_string()],
        });
        let out = sanitize_log_message(r#"{"token":"not_a_secret"}"#);
        assert!(out.contains(r#""token":"not_a_secret""#));
    }

    #[test]
    fn trim_origin_head_extracts_branch_short_name() {
        assert_eq!(
            trim_origin_head_to_branch("refs/remotes/origin/main"),
            Some("main")
        );
        assert_eq!(
            trim_origin_head_to_branch("refs/remotes/origin/master\n"),
            Some("master")
        );
        assert_eq!(trim_origin_head_to_branch("refs/heads/main"), None);
    }
}