tirith 0.4.1

Terminal security - catches homograph attacks, pipe-to-shell, ANSI injection
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
use tirith_core::audit_aggregator::{self, AuditFilter};

/// Run the `tirith audit export` subcommand.
pub fn export(
    format: &str,
    since: Option<&str>,
    until: Option<&str>,
    session: Option<&str>,
    action: Option<&str>,
    rule_ids: &[String],
    entry_type: &str,
) -> i32 {
    if !matches!(
        entry_type,
        "verdict" | "hook_telemetry" | "trust_change" | "all"
    ) {
        eprintln!(
            "tirith: unknown entry type '{entry_type}' (use 'verdict', 'hook_telemetry', 'trust_change', or 'all')"
        );
        eprintln!("  try: tirith audit export --entry-type verdict");
        return 1;
    }

    if format == "csv" && entry_type != "verdict" {
        eprintln!(
            "tirith: CSV export only supports verdict entries; use --format json for {entry_type}"
        );
        return 1;
    }

    let log_path = match tirith_core::policy::data_dir() {
        Some(d) => d.join("log.jsonl"),
        None => {
            eprintln!("tirith: could not determine audit log path");
            return 1;
        }
    };

    if !log_path.exists() {
        eprintln!("tirith: no audit log found at {}", log_path.display());
        return 1;
    }

    let result = match audit_aggregator::read_log(&log_path) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("tirith: {e}");
            return 1;
        }
    };
    if result.skipped_lines > 0 {
        eprintln!(
            "tirith: warning: {} malformed audit log line(s) skipped",
            result.skipped_lines
        );
    }
    let records = result.records;

    let filter = AuditFilter {
        since: since.map(String::from),
        until: until.map(String::from),
        session_id: session.map(String::from),
        action: action.map(String::from),
        rule_ids: rule_ids.to_vec(),
        entry_type: Some(entry_type.to_string()),
    };

    let filtered = audit_aggregator::filter_records(&records, &filter);

    match format {
        "csv" => print!("{}", audit_aggregator::export_csv(&filtered)),
        _ => println!("{}", audit_aggregator::export_json(&filtered)),
    }

    0
}

/// Run the `tirith audit stats` subcommand.
pub fn stats(session: Option<&str>, json: bool, entry_type: &str) -> i32 {
    match entry_type {
        "verdict" | "hook_telemetry" => {}
        "all" | "trust_change" => {
            eprintln!(
                "tirith: --entry-type {entry_type} is not supported for stats; use verdict or hook_telemetry"
            );
            return 1;
        }
        _ => {
            eprintln!("tirith: unknown --entry-type {entry_type}; use verdict or hook_telemetry");
            return 1;
        }
    }

    let log_path = match tirith_core::policy::data_dir() {
        Some(d) => d.join("log.jsonl"),
        None => {
            eprintln!("tirith: could not determine audit log path");
            return 1;
        }
    };

    if !log_path.exists() {
        eprintln!("tirith: no audit log found at {}", log_path.display());
        return 1;
    }

    let result = match audit_aggregator::read_log(&log_path) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("tirith: {e}");
            return 1;
        }
    };
    if result.skipped_lines > 0 {
        eprintln!(
            "tirith: warning: {} malformed audit log line(s) skipped",
            result.skipped_lines
        );
    }
    let records = result.records;

    let filtered = if let Some(sid) = session {
        let filter = AuditFilter {
            session_id: Some(sid.to_string()),
            entry_type: Some(entry_type.to_string()),
            ..Default::default()
        };
        audit_aggregator::filter_records(&records, &filter)
    } else {
        let filter = AuditFilter {
            entry_type: Some(entry_type.to_string()),
            ..Default::default()
        };
        audit_aggregator::filter_records(&records, &filter)
    };

    if entry_type == "hook_telemetry" {
        let hook_stats = audit_aggregator::compute_hook_stats(&filtered);

        if json {
            println!(
                "{}",
                serde_json::to_string_pretty(&hook_stats).unwrap_or_else(|e| {
                    eprintln!("tirith: audit stats: JSON serialization failed: {e}");
                    "{}".into()
                })
            );
        } else {
            println!("Hook telemetry:");
            // Sort by integration name then event name for stable output.
            let mut integrations: Vec<_> = hook_stats.events_by_integration.keys().collect();
            integrations.sort();
            for integration in integrations {
                let events = &hook_stats.events_by_integration[integration];
                let mut event_list: Vec<_> = events.iter().collect();
                event_list.sort_by(|a, b| b.1.cmp(a.1).then_with(|| a.0.cmp(b.0)));
                for (event, count) in event_list {
                    // repo-0360: integration/event strings come from the audit
                    // log, which records caller-supplied values — sanitize
                    // terminal controls before printing.
                    println!(
                        "  {} / {}: {count:>5}",
                        super::sanitize_for_human_output(integration, false),
                        super::sanitize_for_human_output(event, false),
                    );
                }
            }
            if hook_stats.total_events == 0 {
                println!("  (no events recorded)");
            }
        }
    } else {
        let stats = audit_aggregator::compute_stats(&filtered);

        if json {
            println!(
                "{}",
                serde_json::to_string_pretty(&stats).unwrap_or_else(|e| {
                    eprintln!("tirith: audit stats: JSON serialization failed: {e}");
                    "{}".into()
                })
            );
        } else {
            println!("Commands analyzed: {}", stats.total_commands);
            println!("Total findings:    {}", stats.total_findings);
            println!("Block rate:        {:.1}%", stats.block_rate * 100.0);
            println!("Sessions:          {}", stats.sessions_seen);
            if let Some((ref first, ref last)) = stats.time_range {
                println!("Time range:        {first} to {last}");
            }
            if !stats.top_rules.is_empty() {
                println!("\nTop rules:");
                for (rule, count) in &stats.top_rules {
                    println!("  {rule}: {count}");
                }
            }
        }
    }

    0
}

/// Run the `tirith audit verify` subcommand: check the tamper-evident chain.
pub fn verify(expected_head: Option<&str>, json: bool) -> i32 {
    let Some(path) = tirith_core::audit::audit_log_path() else {
        // Keep `--json` machine-readable on the path-resolution failure: emit the
        // same `{ ok, total_lines, problems }` error shape as the other JSON paths
        // in this handler (built via serde_json so it is always valid), and PRESERVE
        // the exit code (2) so callers still distinguish it from a verify failure (1).
        if json {
            let obj = serde_json::json!({
                "ok": false,
                "total_lines": 0,
                "problems": ["no audit log path available"],
            });
            println!("{obj}");
        } else {
            eprintln!("tirith: no audit log path available");
        }
        return 2;
    };
    // `try_exists()` (not `exists()`) so a log we CANNOT stat (permission denied,
    // etc.) is not silently collapsed into "missing" and reported as a vacuous
    // success. Fail closed on the metadata error: emit the JSON/text error shape
    // and return non-zero rather than exit 0.
    let log_exists = match path.try_exists() {
        Ok(exists) => exists,
        Err(e) => {
            if json {
                let obj = serde_json::json!({
                    "ok": false,
                    "total_lines": 0,
                    "problems": [format!(
                        "could not access audit log at {}: {e}",
                        path.display()
                    )],
                });
                println!("{obj}");
            } else {
                eprintln!(
                    "tirith audit verify: FAILED: could not access audit log at {}: {e}",
                    path.display()
                );
            }
            return 1;
        }
    };
    if !log_exists {
        // When the caller anchors verification with --expected-head, a missing
        // log is a FAILURE, not a vacuous pass: the operator asserted a specific
        // tail hash that an absent log cannot satisfy. Reporting success here
        // would let log deletion silently defeat the anchor.
        if expected_head.is_some() {
            if json {
                // Build with serde_json so the path is escaped (a Windows path with
                // backslashes, or one with quotes, would otherwise yield invalid
                // JSON). Mirrors the success-path object shape below.
                let obj = serde_json::json!({
                    "ok": false,
                    "total_lines": 0,
                    "problems": [format!(
                        "expected-head supplied but no audit log at {}",
                        path.display()
                    )],
                });
                println!("{obj}");
            } else {
                eprintln!(
                    "tirith audit verify: FAILED: expected-head supplied but no audit log at {}",
                    path.display()
                );
            }
            return 1;
        }
        if json {
            println!(r#"{{"ok":true,"total_lines":0,"note":"no audit log yet"}}"#);
        } else {
            println!("tirith audit verify: no audit log at {}", path.display());
        }
        return 0;
    }
    let report = tirith_core::audit::verify_audit_log(&path, expected_head);
    if json {
        let problems: Vec<serde_json::Value> = report
            .problems
            .iter()
            .map(|p| serde_json::Value::String(p.clone()))
            .collect();
        let obj = serde_json::json!({
            "ok": report.ok,
            "total_lines": report.total_lines,
            "chained_lines": report.chained_lines,
            "legacy_prefix": report.legacy_prefix,
            "head_status": report.head_status,
            "signed_lines": report.signed_lines,
            "signing_expected": report.signing_expected,
            "problems": problems,
        });
        println!("{obj}");
    } else {
        println!(
            "tirith audit verify: {} ({} lines, {} chained, {} legacy)",
            if report.ok { "OK" } else { "FAILED" },
            report.total_lines,
            report.chained_lines,
            report.legacy_prefix
        );
        println!("  {}", report.head_status);
        if report.signing_expected {
            println!(
                "  signing: enabled ({} signed line(s))",
                report.signed_lines
            );
        } else {
            // Honest limitation: for an UNSIGNED log there is no key, so local
            // verification cannot prove signing was never enabled. A fully local
            // attacker could strip signatures and rewrite the head to look
            // unsigned. Detecting that requires an external anchor (a signed log,
            // or an out-of-band --expected-head). See the audit.rs module note.
            println!(
                "  signing: not enabled (local verification cannot prove signing was \
                 never enabled on an unsigned log without an external anchor)"
            );
        }
        for p in &report.problems {
            println!("  problem: {p}");
        }
    }
    if report.ok {
        0
    } else {
        1
    }
}

/// Run the `tirith audit report` subcommand.
pub fn report(format: &str, since: Option<&str>, entry_type: &str) -> i32 {
    if entry_type != "verdict" {
        eprintln!(
            "tirith: --entry-type {entry_type} is not supported for reports; only verdict is supported"
        );
        return 1;
    }

    let log_path = match tirith_core::policy::data_dir() {
        Some(d) => d.join("log.jsonl"),
        None => {
            eprintln!("tirith: could not determine audit log path");
            return 1;
        }
    };

    if !log_path.exists() {
        eprintln!("tirith: no audit log found at {}", log_path.display());
        return 1;
    }

    let result = match audit_aggregator::read_log(&log_path) {
        Ok(r) => r,
        Err(e) => {
            eprintln!("tirith: {e}");
            return 1;
        }
    };
    if result.skipped_lines > 0 {
        eprintln!(
            "tirith: warning: {} malformed audit log line(s) skipped",
            result.skipped_lines
        );
    }
    let records = result.records;

    let filtered = if let Some(since_date) = since {
        let filter = AuditFilter {
            since: Some(since_date.to_string()),
            entry_type: Some("verdict".to_string()),
            ..Default::default()
        };
        audit_aggregator::filter_records(&records, &filter)
    } else {
        let filter = AuditFilter {
            entry_type: Some("verdict".to_string()),
            ..Default::default()
        };
        audit_aggregator::filter_records(&records, &filter)
    };

    let stats = audit_aggregator::compute_stats(&filtered);

    match format {
        "json" => {
            let report_json = serde_json::json!({
                "stats": stats,
                "records": filtered,
            });
            println!(
                "{}",
                serde_json::to_string_pretty(&report_json).unwrap_or_else(|e| {
                    eprintln!("tirith: audit report: JSON serialization failed: {e}");
                    "{}".into()
                })
            );
        }
        "html" => {
            print!(
                "{}",
                audit_aggregator::generate_html_report(&filtered, &stats)
            );
        }
        _ => {
            print!(
                "{}",
                audit_aggregator::generate_compliance_report(&filtered, &stats)
            );
        }
    }

    0
}

#[cfg(test)]
mod tests {
    // Use the CRATE-WIDE env lock + RAII guard from the test harness so this test
    // serializes against the other env-mutating bin tests (trust.rs, dashboard.rs,
    // doctor.rs) that also touch HOME/XDG_DATA_HOME. A module-local lock would let
    // those race this test on the same process-global env vars.
    use crate::cli::test_harness::{EnvGuard, ENV_LOCK};

    /// F8: `tirith audit verify --expected-head <hash>` must FAIL (non-zero) when
    /// the log is missing — an asserted tail hash cannot be satisfied by an absent
    /// log, so reporting success would let log deletion silently defeat the anchor.
    /// A plain `verify` (no anchor) on a missing log still succeeds (0).
    #[cfg(unix)]
    #[test]
    fn verify_missing_log_with_expected_head_fails() {
        let _lock = ENV_LOCK.lock().unwrap_or_else(|p| p.into_inner());

        let tmp = tempfile::tempdir().unwrap();
        let empty = tmp.path().join("empty_home");
        std::fs::create_dir_all(&empty).unwrap();

        // Point BOTH the XDG data dir (Linux) and HOME (macOS, via etcetera's
        // Apple strategy) at a fresh empty dir, so `audit_log_path()` resolves to a
        // file that does not exist on either platform. EnvGuard restores on Drop.
        let _home = EnvGuard::set("HOME", &empty);
        let _xdg = EnvGuard::set("XDG_DATA_HOME", &empty);

        let with_anchor = super::verify(Some("deadbeefcafe"), true);
        let without_anchor = super::verify(None, true);

        assert_eq!(
            with_anchor, 1,
            "verify --expected-head on a missing log must return non-zero"
        );
        assert_eq!(
            without_anchor, 0,
            "verify with no anchor on a missing log stays a vacuous success"
        );
    }
}