openclaw-scan 0.1.1

Security scanner for agentic AI framework installations (OpenClaw, Claude Code, and compatible)
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
469
470
471
472
473
474
475
476
477
//! Rich human-readable terminal output.
//!
//! Produces a coloured report with a banner, findings table,
//! per-category score bars, and a summary section.

use owo_colors::{OwoColorize, Style};

use crate::finding::{Finding, Severity};
use crate::report::{CategoryReport, Grade, Report};

use super::OutputConfig;

// ── Public entry point ────────────────────────────────────────────────────────

/// Print `report` to stdout using the rich terminal format.
pub fn print(report: &Report, cfg: &OutputConfig) -> anyhow::Result<()> {
    let use_color = cfg.color && std::io::IsTerminal::is_terminal(&std::io::stdout());

    if !cfg.quiet {
        print_banner(report, use_color);
    }

    if report.findings.is_empty() {
        print_clean(use_color);
        return Ok(());
    }

    print_findings(report, cfg, use_color);
    print_summary(report, use_color);

    if !cfg.quiet {
        print_hints(cfg);
    }

    Ok(())
}

// ── Banner ────────────────────────────────────────────────────────────────────

fn print_banner(report: &Report, color: bool) {
    let framework_label = if report.scanned_paths.iter().any(|p| p.contains(".claude")) {
        "Claude Code"
    } else {
        "Agentic Framework"
    };

    let inner = format!(
        "  openclaw-scan v{}{} Security  ",
        report.version, framework_label
    );
    let width = inner.len();
    let top = format!("{}", "".repeat(width));
    let mid = format!("{}", inner);
    let bot = format!("{}", "".repeat(width));

    if color {
        println!("{}", top.bold());
        println!("{}", mid.bold());
        println!("{}", bot.bold());
    } else {
        println!("{top}");
        println!("{mid}");
        println!("{bot}");
    }
    println!();

    for path in &report.scanned_paths {
        let msg = format!("Scanning {}  [{}]", path, report.scanned_at);
        if color {
            println!("{}", msg.dimmed());
        } else {
            println!("{msg}");
        }
    }
    println!();
}

// ── Clean (no findings) ───────────────────────────────────────────────────────

fn print_clean(color: bool) {
    let msg = "✓ No security findings detected. Score: 100/100 (A)";
    if color {
        println!("{}", msg.green().bold());
    } else {
        println!("{msg}");
    }
    println!();
}

// ── Findings table ────────────────────────────────────────────────────────────

fn print_findings(report: &Report, cfg: &OutputConfig, color: bool) {
    let header = "FINDINGS";
    let separator = "".repeat(54);
    if color {
        println!("{} {}", header.bold(), separator.dimmed());
    } else {
        println!("{header} {separator}");
    }

    for f in &report.findings {
        print_finding_row(f, cfg.verbose, color);
    }
    println!();
}

fn print_finding_row(f: &Finding, verbose: bool, color: bool) {
    let bullet = "";
    let sev_style = severity_style(f.severity, color);
    let cat_label = format!("[{}]", f.category);

    // Location: path + optional line number
    let location = match f.line {
        Some(ln) => format!("{}:{}", f.path.display(), ln),
        None => f.path.display().to_string(),
    };
    // Trim the location to a reasonable width
    let location_short = truncate(&location, 40);

    if color {
        println!(
            "{} {}  {}  {}  {}",
            bullet.style(sev_style),
            f.severity.label().trim().style(sev_style),
            cat_label.cyan(),
            f.title,
            location_short.dimmed()
        );
    } else {
        println!(
            "{bullet} {}  {cat_label}  {}  {location_short}",
            f.severity.label().trim(),
            f.title
        );
    }

    if verbose {
        if let Some(ref ev) = f.evidence {
            let evidence_line = format!("          Evidence:     {ev}");
            if color {
                println!("{}", evidence_line.dimmed());
            } else {
                println!("{evidence_line}");
            }
        }
        let desc_line = format!("          Description:  {}", f.description);
        if color {
            println!("{}", desc_line.dimmed());
        } else {
            println!("{desc_line}");
        }
        let rem_line = format!("          Remediation:  {}", f.remediation);
        if color {
            println!("{}", rem_line.yellow());
        } else {
            println!("{rem_line}");
        }
        println!();
    }
}

// ── Summary ───────────────────────────────────────────────────────────────────

fn print_summary(report: &Report, color: bool) {
    let header = "SUMMARY";
    let separator = "".repeat(54);
    if color {
        println!("{} {}", header.bold(), separator.dimmed());
    } else {
        println!("{header} {separator}");
    }
    println!();

    // Overall score + grade
    let grade_style = grade_style(report.overall_grade, color);
    let score_line = format!(
        "  Score  {} / 100   Grade: {}",
        report.overall_score, report.overall_grade
    );
    if color {
        println!("{}", score_line.bold().style(grade_style));
    } else {
        println!("{score_line}");
    }
    println!();

    // Per-category rows
    for cat_report in &report.categories {
        print_category_row(cat_report, color);
    }
    println!();

    // Totals line
    let totals = format_totals(report);
    if color {
        println!("  {}", totals.bold());
    } else {
        println!("  {totals}");
    }
    println!();
}

fn print_category_row(cat: &CategoryReport, color: bool) {
    let bar = score_bar(cat.score);
    let counts = format_category_counts(cat);
    let name = format!("{:<13}", cat.category.label().trim());
    let score_str = format!("{:>3}", cat.score);

    if color {
        let bar_style = score_bar_style(cat.score);
        println!(
            "  {}  {}  {}  {}",
            name.bold(),
            bar.style(bar_style),
            score_str,
            counts.dimmed()
        );
    } else {
        println!("  {name}  {bar}  {score_str}  {counts}");
    }
}

/// Build a 10-cell bar like `████████░░` from a 0–100 score.
fn score_bar(score: u32) -> String {
    let filled = (score / 10) as usize;
    let empty = 10usize.saturating_sub(filled);
    format!("{}{}", "".repeat(filled), "".repeat(empty))
}

/// Build a compact count string from (count, label) pairs, joined by `sep`.
/// Returns `none` when all counts are zero.
fn format_counts(counts: &[(usize, &str)], sep: &str, none: &str) -> String {
    let parts: Vec<String> = counts
        .iter()
        .filter(|&&(n, _)| n > 0)
        .map(|&(n, label)| format!("{} {}", n, label))
        .collect();
    if parts.is_empty() {
        none.to_string()
    } else {
        parts.join(sep)
    }
}

fn format_category_counts(cat: &CategoryReport) -> String {
    format_counts(
        &[
            (cat.critical_count, "critical"),
            (cat.high_count, "high"),
            (cat.medium_count, "medium"),
            (cat.low_count, "low"),
            (cat.info_count, "info"),
        ],
        "  ",
        "",
    )
}

fn format_totals(report: &Report) -> String {
    let total = report.total_critical
        + report.total_high
        + report.total_medium
        + report.total_low
        + report.total_info;
    if total == 0 {
        return "0 findings".to_string();
    }
    let detail = format_counts(
        &[
            (report.total_critical, "critical"),
            (report.total_high, "high"),
            (report.total_medium, "medium"),
            (report.total_low, "low"),
            (report.total_info, "info"),
        ],
        " · ",
        "",
    );
    format!("{} findings  ({})", total, detail)
}

// ── Hints ─────────────────────────────────────────────────────────────────────

fn print_hints(cfg: &OutputConfig) {
    if !cfg.verbose {
        println!("Run `ocls -v` for remediation steps.");
    }
    if !cfg.json {
        println!("Run `ocls --json` for machine-readable output.");
    }
    println!();
}

// ── Styling helpers ───────────────────────────────────────────────────────────

fn severity_style(sev: Severity, color: bool) -> Style {
    if !color {
        return Style::new();
    }
    match sev {
        Severity::Critical => Style::new().red().bold(),
        Severity::High => Style::new().yellow().bold(),
        Severity::Medium => Style::new().yellow(),
        Severity::Low => Style::new().blue(),
        Severity::Info => Style::new().dimmed(),
    }
}

fn grade_style(grade: Grade, color: bool) -> Style {
    if !color {
        return Style::new();
    }
    match grade {
        Grade::A => Style::new().green().bold(),
        Grade::B => Style::new().green(),
        Grade::C => Style::new().yellow(),
        Grade::D => Style::new().yellow().bold(),
        Grade::F => Style::new().red().bold(),
    }
}

fn score_bar_style(score: u32) -> Style {
    match score {
        75..=100 => Style::new().green(),
        40..=74 => Style::new().yellow(),
        _ => Style::new().red(),
    }
}

/// Truncate a string with an ellipsis prefix if it exceeds `max` characters.
///
/// Uses char-aware slicing so multi-byte UTF-8 paths never cause a panic (H-2).
fn truncate(s: &str, max: usize) -> String {
    let chars: Vec<char> = s.chars().collect();
    if chars.len() <= max {
        s.to_string()
    } else {
        let tail: String = chars[chars.len().saturating_sub(max.saturating_sub(1))..]
            .iter()
            .collect();
        format!("{}", tail)
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::finding::{Category, Finding, Severity};
    use crate::report::Report;

    fn make_report_with(findings: Vec<Finding>) -> Report {
        Report::build(findings, vec!["~/.openclaw".to_string()], "0.1.0")
    }

    #[test]
    fn score_bar_full() {
        assert_eq!(score_bar(100), "██████████");
    }

    #[test]
    fn score_bar_empty() {
        assert_eq!(score_bar(0), "░░░░░░░░░░");
    }

    #[test]
    fn score_bar_half() {
        assert_eq!(score_bar(50), "█████░░░░░");
    }

    #[test]
    fn score_bar_67() {
        assert_eq!(score_bar(67), "██████░░░░");
    }

    #[test]
    fn truncate_short_string_unchanged() {
        assert_eq!(truncate("hello", 10), "hello");
    }

    #[test]
    fn truncate_long_string_gets_ellipsis() {
        let long = "a".repeat(50);
        let result = truncate(&long, 20);
        assert!(result.starts_with(''));
        // '…' is a single char (U+2026) — count chars, not bytes
        assert!(result.chars().count() <= 20);
    }

    #[test]
    fn format_totals_empty_report() {
        let report = make_report_with(vec![]);
        assert_eq!(format_totals(&report), "0 findings");
    }

    #[test]
    fn format_totals_mixed() {
        let findings = vec![
            Finding::new(
                Severity::Critical,
                Category::SecretDetection,
                "T",
                "D",
                "/f",
                "R",
            ),
            Finding::new(
                Severity::High,
                Category::ConfigSecurity,
                "T",
                "D",
                "/f",
                "R",
            ),
            Finding::new(Severity::Info, Category::DataExposure, "T", "D", "/f", "R"),
        ];
        let report = make_report_with(findings);
        let totals = format_totals(&report);
        assert!(totals.contains("3 findings"));
        assert!(totals.contains("1 critical"));
        assert!(totals.contains("1 high"));
        assert!(totals.contains("1 info"));
    }

    #[test]
    fn format_category_counts_all_zero_shows_dash() {
        use crate::report::CategoryReport;
        let cat = CategoryReport::build(Category::HookSecurity, vec![]);
        assert_eq!(format_category_counts(&cat), "");
    }

    #[test]
    fn print_does_not_panic_on_empty_report() {
        let report = make_report_with(vec![]);
        let cfg = OutputConfig {
            json: false,
            quiet: true,
            verbose: false,
            color: false,
        };
        // Should not panic
        print(&report, &cfg).expect("print failed");
    }

    #[test]
    fn print_does_not_panic_on_full_report() {
        let findings = vec![
            Finding::new(
                Severity::Critical,
                Category::SecretDetection,
                "API key found",
                "A secret was detected in history",
                "/home/user/.openclaw/history.jsonl",
                "Rotate the key immediately.",
            )
            .with_line(42)
            .with_evidence("sk-ant****"),
            Finding::new(
                Severity::High,
                Category::ConfigSecurity,
                "Wildcard bash rule",
                "Allow rule is too broad",
                "/home/user/.openclaw/settings.json",
                "Restrict the allow list.",
            ),
        ];
        let report = make_report_with(findings);
        let cfg = OutputConfig {
            json: false,
            quiet: false,
            verbose: true,
            color: false,
        };
        print(&report, &cfg).expect("print failed");
    }
}