agent-shield 0.8.7

Security scanner for AI agent extensions — offline-first, multi-framework, SARIF output
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
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
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
mod hotspots;
mod roots;

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use crate::config::ScanPathFilterSummary;
use crate::error::ShieldError;
use crate::ir::Language;
use crate::rules::{AttackCategory, Finding, Severity};
use crate::ScanReport;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CoverageConfidence {
    High,
    Medium,
    Low,
}

impl CoverageConfidence {
    fn label(self) -> &'static str {
        match self {
            Self::High => "High",
            Self::Medium => "Medium",
            Self::Low => "Low",
        }
    }

    fn reason(self) -> &'static str {
        match self {
            Self::High => "known adapter(s) matched and source files were parsed",
            Self::Medium => "known adapter(s) matched, but code parsing coverage is limited",
            Self::Low => "no supported agent extension surface was detected",
        }
    }
}

#[derive(Debug, Clone)]
pub struct ExplainOptions {
    pub ignore_tests: bool,
}

#[derive(Debug, Clone)]
pub struct CiInstallOptions<'a> {
    pub fail_on: &'a str,
    pub ignore_tests: bool,
    pub scan_path: &'a str,
    pub baseline_path: Option<&'a str>,
    pub upload_sarif: bool,
}

pub fn quickstart_config_toml(fail_on: Severity, ignore_tests: bool) -> String {
    format!(
        r#"# AgentShield configuration
# Generated by `agentshield quickstart`.

[policy]
fail_on = "{fail_on}"

[scan]
ignore_tests = {ignore_tests}

[runtime.proxy]
fail_on = "block"
"#
    )
}

pub fn github_actions_workflow(options: &CiInstallOptions<'_>) -> String {
    let baseline_input = options
        .baseline_path
        .map(|path| format!("          baseline: \"{path}\"\n"))
        .unwrap_or_default();

    format!(
        r#"name: AgentShield

on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read
  security-events: write

jobs:
  agentshield:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: aiconnai/agentshield@main
        with:
          path: "{scan_path}"
          fail-on: "{fail_on}"
          ignore-tests: {ignore_tests}
{baseline_input}          upload-sarif: {upload_sarif}
"#,
        scan_path = options.scan_path,
        fail_on = options.fail_on,
        ignore_tests = options.ignore_tests,
        baseline_input = baseline_input,
        upload_sarif = options.upload_sarif,
    )
}

pub fn render_explain(report: &ScanReport, options: &ExplainOptions) -> String {
    let coverage = coverage_summary(report);
    let confidence = confidence_for_report(report);
    let runtime_findings: Vec<&Finding> = report
        .findings
        .iter()
        .filter(|finding| finding.attack_category != AttackCategory::SupplyChain)
        .collect();
    let supply_chain_findings: Vec<&Finding> = report
        .findings
        .iter()
        .filter(|finding| finding.attack_category == AttackCategory::SupplyChain)
        .collect();

    let mut output = String::new();
    output.push_str("AgentShield explain\n");
    output.push_str("===================\n\n");
    output.push_str(&format!(
        "Gate: {}\n",
        if report.verdict.pass { "PASS" } else { "FAIL" }
    ));
    output.push_str(&format!("Reason: {}\n", gate_reason(report)));
    output.push_str(&format!(
        "Security confidence: {} - {}\n\n",
        confidence.label(),
        confidence.reason()
    ));

    output.push_str("Coverage:\n");
    output.push_str(&format!(
        "- Adapters: {}\n",
        display_list(&coverage.frameworks, "none")
    ));
    output.push_str(&roots::render(report));
    output.push_str(&format!("- Targets: {}\n", coverage.targets));
    output.push_str(&format!(
        "- Source files parsed: {} ({})\n",
        coverage.source_files,
        display_list(&coverage.languages, "no code parser coverage")
    ));
    output.push_str(&format!("- Tools discovered: {}\n", coverage.tools));
    output.push_str(&format!(
        "- Dependencies checked: {}\n",
        coverage.dependencies
    ));
    output.push_str(&format!("- Lockfiles detected: {}\n", coverage.lockfiles));
    output.push_str(&format!(
        "- Test file exclusion: {}\n",
        if options.ignore_tests {
            "enabled"
        } else {
            "disabled"
        }
    ));
    output.push_str(&format!(
        "- Path filters: {}\n\n",
        format_path_filters(&report.path_filter_summary)
    ));

    output.push_str("Findings:\n");
    output.push_str(&format!(
        "- Runtime-risk findings: {}\n",
        finding_group_summary(&runtime_findings)
    ));
    output.push_str(&format!(
        "- Supply-chain hygiene: {}\n",
        finding_group_summary(&supply_chain_findings)
    ));
    output.push_str(&format!(
        "- Severity counts: {}\n\n",
        severity_counts(&report.findings)
    ));

    output.push_str(&hotspots::render(report));

    output.push_str("Next actions:\n");
    for action in next_actions(report) {
        output.push_str(&format!("- {action}\n"));
    }

    output.push_str("\nWhat this does not prove:\n");
    output.push_str("- This scan does not execute tools or prove absence of vulnerabilities.\n");
    output.push_str(
        "- It checks known risky patterns in supported agent surfaces and dependency metadata.\n",
    );

    output
}

pub fn render_no_adapter_explain(
    path: &Path,
    ignore_tests: bool,
    path_filters: &ScanPathFilterSummary,
) -> String {
    let mut output = String::new();
    output.push_str("AgentShield explain\n");
    output.push_str("===================\n\n");
    output.push_str("Gate: INCONCLUSIVE\n");
    output.push_str("Reason: no supported agent extension surface was detected.\n");
    output.push_str(&format!(
        "Security confidence: {} - {}\n\n",
        CoverageConfidence::Low.label(),
        CoverageConfidence::Low.reason()
    ));
    output.push_str("Coverage:\n");
    output.push_str("- Adapters: none\n");
    output.push_str(&format!("- Target: {}\n", path.display()));
    output.push_str(&format!(
        "- Test file exclusion: {}\n",
        if ignore_tests { "enabled" } else { "disabled" }
    ));
    output.push_str(&format!(
        "- Path filters: {}\n\n",
        format_path_filters(path_filters)
    ));
    output.push_str("Next actions:\n");
    output.push_str("- Confirm this repository contains an MCP server, OpenClaw skill, Hermes agent, CrewAI/LangChain tool, GPT Action, or Cursor Rules surface.\n");
    output.push_str("- If it does, add a framework manifest or dependency metadata that AgentShield can detect.\n");
    output.push_str("- Run `agentshield doctor .` to inspect adapter detection.\n\n");
    output.push_str("What this does not prove:\n");
    output.push_str("- This result does not mean the project is safe; it means AgentShield did not find a supported surface to scan.\n");
    output
}

pub fn is_no_adapter(error: &ShieldError) -> bool {
    matches!(error, ShieldError::NoAdapter(_))
}

#[derive(Debug, Default)]
struct CoverageSummary {
    frameworks: BTreeSet<String>,
    languages: BTreeSet<String>,
    targets: usize,
    source_files: usize,
    tools: usize,
    dependencies: usize,
    lockfiles: usize,
}

fn coverage_summary(report: &ScanReport) -> CoverageSummary {
    let mut summary = CoverageSummary {
        targets: report.targets.len(),
        ..CoverageSummary::default()
    };

    for target in &report.targets {
        summary.frameworks.insert(target.framework.to_string());
        summary.source_files += target.source_files.len();
        summary.tools += target.tools.len();
        summary.dependencies += target.dependencies.dependencies.len();
        if target.dependencies.lockfile.is_some() {
            summary.lockfiles += 1;
        }
        for source in &target.source_files {
            summary
                .languages
                .insert(display_language(source.language).into());
        }
    }

    summary
}

fn confidence_for_report(report: &ScanReport) -> CoverageConfidence {
    if report.targets.is_empty() {
        CoverageConfidence::Low
    } else if report
        .targets
        .iter()
        .any(|target| !target.source_files.is_empty())
    {
        CoverageConfidence::High
    } else {
        CoverageConfidence::Medium
    }
}

fn gate_reason(report: &ScanReport) -> String {
    if report.verdict.pass {
        match report.verdict.highest_severity {
            Some(severity) => format!(
                "no findings at or above the {} threshold; highest finding is {}",
                report.verdict.fail_threshold, severity
            ),
            None => format!(
                "no findings remained after policy, suppressions, and baseline filtering; threshold is {}",
                report.verdict.fail_threshold
            ),
        }
    } else {
        format!(
            "at least one finding meets or exceeds the {} threshold; highest finding is {}",
            report.verdict.fail_threshold,
            report
                .verdict
                .highest_severity
                .map(|severity| severity.to_string())
                .unwrap_or_else(|| "unknown".into())
        )
    }
}

fn finding_group_summary(findings: &[&Finding]) -> String {
    if findings.is_empty() {
        "none".into()
    } else {
        format!("{} ({})", findings.len(), severity_counts_refs(findings))
    }
}

fn severity_counts(findings: &[Finding]) -> String {
    let refs: Vec<&Finding> = findings.iter().collect();
    severity_counts_refs(&refs)
}

fn severity_counts_refs(findings: &[&Finding]) -> String {
    if findings.is_empty() {
        return "none".into();
    }

    let mut counts: BTreeMap<Severity, usize> = BTreeMap::new();
    for finding in findings {
        *counts.entry(finding.severity).or_default() += 1;
    }

    [
        Severity::Critical,
        Severity::High,
        Severity::Medium,
        Severity::Low,
        Severity::Info,
    ]
    .into_iter()
    .filter_map(|severity| {
        counts
            .get(&severity)
            .map(|count| format!("{count} {severity}"))
    })
    .collect::<Vec<_>>()
    .join(", ")
}

fn next_actions(report: &ScanReport) -> Vec<String> {
    if report.findings.is_empty() {
        return vec![
            "Add a CI gate with `agentshield ci install`.".into(),
            "Keep `agentshield scan . --ignore-tests --fail-on high` in the pre-merge path.".into(),
        ];
    }

    let mut actions = Vec::new();
    if !report.verdict.pass {
        actions.push(format!(
            "Fix findings at or above `{}` first; they are blocking the security gate.",
            report.verdict.fail_threshold
        ));
    }

    let mut seen_rules = BTreeSet::new();
    for finding in &report.findings {
        if !seen_rules.insert(finding.rule_id.clone()) {
            continue;
        }
        if let Some(command) = exact_command_for_finding(finding) {
            actions.push(command);
        } else if let Some(remediation) = &finding.remediation {
            actions.push(remediation.clone());
        } else {
            actions.push(format!("Review `{}`: {}", finding.rule_id, finding.message));
        }

        if actions.len() >= 5 {
            break;
        }
    }

    actions.push("Run `agentshield scan . --explain` again after changes.".into());
    actions
}

fn exact_command_for_finding(finding: &Finding) -> Option<String> {
    let file_name = finding
        .location
        .as_ref()
        .and_then(|location| location.file.file_name())
        .map(|name| name.to_string_lossy().to_string())
        .unwrap_or_default();

    match finding.rule_id.as_str() {
        "SHIELD-009" => {
            let package = package_name_from_message(&finding.message)?;
            if file_name == "package.json" {
                Some(format!(
                    "Pin `{package}` with `npm install {package}@<exact-version> --save-exact`."
                ))
            } else if file_name == "requirements.txt" {
                Some(format!(
                    "Pin `{package}` by changing the requirement to `{package}==<exact-version>`."
                ))
            } else if file_name == "pyproject.toml" {
                Some(format!(
                    "Pin `{package}` to an exact version in `pyproject.toml`, then regenerate the lockfile."
                ))
            } else {
                None
            }
        }
        "SHIELD-012" => {
            if file_name == "package.json" {
                Some("Generate an npm lockfile with `npm install`.".into())
            } else if file_name == "requirements.txt" {
                Some(
                    "Generate a reproducible Python lockfile with `uv lock` or `poetry lock`."
                        .into(),
                )
            } else {
                None
            }
        }
        _ => None,
    }
}

fn package_name_from_message(message: &str) -> Option<&str> {
    let start = message.find('\'')? + 1;
    let rest = &message[start..];
    let end = rest.find('\'')?;
    Some(&rest[..end])
}

fn display_list(values: &BTreeSet<String>, empty: &str) -> String {
    if values.is_empty() {
        empty.into()
    } else {
        values.iter().cloned().collect::<Vec<_>>().join(", ")
    }
}

fn format_path_filters(summary: &ScanPathFilterSummary) -> String {
    if summary.include.is_empty() && summary.exclude.is_empty() {
        return "disabled".into();
    }

    let include = if summary.include.is_empty() {
        "all".into()
    } else {
        summary.include.join(", ")
    };
    let exclude = if summary.exclude.is_empty() {
        "none".into()
    } else {
        summary.exclude.join(", ")
    };

    format!("include {include}; exclude {exclude}")
}

fn display_language(language: Language) -> &'static str {
    match language {
        Language::Python => "Python",
        Language::TypeScript => "TypeScript",
        Language::JavaScript => "JavaScript",
        Language::Shell => "Shell",
        Language::Json => "JSON",
        Language::Toml => "TOML",
        Language::Yaml => "YAML",
        Language::Markdown => "Markdown",
        Language::Unknown => "Unknown",
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use crate::ir::{Framework, ScanTarget, SourceFile};
    use crate::rules::policy::PolicyVerdict;
    use crate::rules::{AttackCategory, Confidence, Evidence, Finding};

    use super::*;

    fn finding(rule_id: &str, severity: Severity, category: AttackCategory) -> Finding {
        Finding {
            rule_id: rule_id.into(),
            rule_name: "Rule".into(),
            severity,
            confidence: Confidence::High,
            attack_category: category,
            message: "Dependency '@modelcontextprotocol/sdk' is not pinned: ^1.0.0".into(),
            location: Some(crate::ir::SourceLocation {
                file: PathBuf::from("package.json"),
                line: 1,
                column: 0,
                end_line: None,
                end_column: None,
            }),
            evidence: vec![Evidence {
                description: "evidence".into(),
                location: None,
                snippet: None,
            }],
            taint_path: None,
            remediation: Some("fix it".into()),
            cwe_id: None,
        }
    }

    fn report(findings: Vec<Finding>) -> ScanReport {
        ScanReport {
            target_name: "fixture".into(),
            findings,
            verdict: PolicyVerdict {
                pass: true,
                total_findings: 2,
                effective_findings: 2,
                highest_severity: Some(Severity::Medium),
                fail_threshold: Severity::High,
            },
            scan_root: PathBuf::from("."),
            targets: vec![ScanTarget {
                name: "fixture".into(),
                framework: Framework::Mcp,
                root_path: PathBuf::from("."),
                tools: vec![],
                execution: Default::default(),
                data: Default::default(),
                dependencies: Default::default(),
                provenance: Default::default(),
                source_files: vec![SourceFile {
                    path: PathBuf::from("server.py"),
                    language: Language::Python,
                    content: String::new(),
                    size_bytes: 0,
                    content_hash: String::new(),
                }],
            }],
            path_filter_summary: ScanPathFilterSummary::default(),
        }
    }

    #[test]
    fn explain_separates_runtime_and_supply_chain_findings() {
        let output = render_explain(
            &report(vec![finding(
                "SHIELD-009",
                Severity::Medium,
                AttackCategory::SupplyChain,
            )]),
            &ExplainOptions { ignore_tests: true },
        );

        assert!(output.contains("Gate: PASS"));
        assert!(output.contains("Runtime-risk findings: none"));
        assert!(output.contains("Supply-chain hygiene: 1"));
        assert!(output.contains("Security confidence: High"));
        assert!(
            output.contains("npm install @modelcontextprotocol/sdk@<exact-version> --save-exact")
        );
    }

    #[test]
    fn no_adapter_explain_is_inconclusive() {
        let output =
            render_no_adapter_explain(Path::new("."), true, &ScanPathFilterSummary::default());

        assert!(output.contains("Gate: INCONCLUSIVE"));
        assert!(output.contains("does not mean the project is safe"));
    }

    #[test]
    fn ci_workflow_uses_expected_action_inputs() {
        let workflow = github_actions_workflow(&CiInstallOptions {
            fail_on: "high",
            ignore_tests: true,
            scan_path: ".",
            baseline_path: None,
            upload_sarif: true,
        });

        assert!(workflow.contains("uses: aiconnai/agentshield@main"));
        assert!(workflow.contains("fail-on: \"high\""));
        assert!(workflow.contains("ignore-tests: true"));
        assert!(workflow.contains("upload-sarif: true"));
        assert!(!workflow.contains("baseline:"));
    }

    #[test]
    fn ci_workflow_can_use_baseline_file() {
        let workflow = github_actions_workflow(&CiInstallOptions {
            fail_on: "high",
            ignore_tests: true,
            scan_path: ".",
            baseline_path: Some(".agentshield-baseline.json"),
            upload_sarif: true,
        });

        assert!(workflow.contains("baseline: \".agentshield-baseline.json\""));
        assert!(workflow.contains("upload-sarif: true"));
    }

    #[test]
    fn quickstart_config_enables_project_defaults() {
        let config = quickstart_config_toml(Severity::High, true);

        assert!(config.contains("fail_on = \"high\""));
        assert!(config.contains("ignore_tests = true"));
        assert!(config.contains("[runtime.proxy]"));
    }
}