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
use anyhow::{Context, Result};
use assay_evidence::lint::engine::{lint_bundle_with_options, LintOptions};
use assay_evidence::lint::packs::{load_packs, LoadedPack};
use assay_evidence::lint::sarif::{to_sarif_with_options, SarifOptions};
use assay_evidence::lint::Severity;
use assay_evidence::VerifyLimits;
use clap::{Args, ValueEnum};
use std::fs::File;
use super::report_lines::ReportLines;
/// Default pack when --pack is omitted (ADR-023).
const DEFAULT_PACK: &str = "cicd-starter";
/// The shapes `evidence lint` can emit. A type rather than a string, so the match over it is
/// exhaustive and no spelling can reach it that the parser did not accept.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum LintFormat {
Json,
Sarif,
Text,
}
/// The severity at which a finding gates the run. `None` gates on nothing, which is what a caller
/// that reads the SARIF itself needs; it was documented and shipped for a long time before it was
/// implemented, because a `_` arm reinterpreted it as `Error`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum FailOn {
Error,
#[value(alias = "warning")]
Warn,
Info,
None,
}
#[derive(Debug, Args, Clone)]
pub struct LintArgs {
/// Bundle to lint (omit when using --explain)
#[arg(value_name = "BUNDLE", required_unless_present = "explain")]
pub bundle: Option<std::path::PathBuf>,
/// Output format: json, sarif, or text
#[arg(long, default_value = "text")]
pub format: LintFormat,
/// Fail (exit 1) if findings at or above this severity exist
#[arg(long, default_value = "error")]
pub fail_on: FailOn,
/// Comma-separated pack references (built-in name or file path)
#[arg(long, value_delimiter = ',')]
pub pack: Option<Vec<String>>,
/// Explain a rule (print help_markdown and exit). Use short id (e.g. CICD-003) or canonical (e.g. cicd-starter@1.0.0:CICD-003)
#[arg(long, value_name = "RULE_ID")]
pub explain: Option<String>,
/// Maximum results in output (for GitHub SARIF limits)
#[arg(long, default_value = "500")]
pub max_results: usize,
}
pub fn cmd_lint(args: LintArgs) -> Result<i32> {
// --explain: show rule help and exit (no bundle needed)
if let Some(rule_ref) = &args.explain {
let packs = match load_packs_for_lint(&args.pack) {
Ok(p) => p,
Err(e) => {
eprintln!("Pack loading failed: {}", e);
return Ok(3);
}
};
return explain_rule(&packs, rule_ref);
}
let bundle = args
.bundle
.as_ref()
.expect("bundle required when not --explain");
let f = File::open(bundle)
.with_context(|| format!("failed to open bundle {}", bundle.display()))?;
let limits = VerifyLimits::for_retained_events();
// Load packs: explicit --pack or default (ADR-023)
let (packs, is_default_pack) = if let Some(pack_refs) = &args.pack {
match load_packs(pack_refs) {
Ok(p) => (p, false),
Err(e) => {
eprintln!("Pack loading failed: {}", e);
return Ok(3); // Exit code 3 = pack error
}
}
} else {
match load_packs(&[DEFAULT_PACK.to_string()]) {
Ok(p) => (p, true),
Err(e) => {
eprintln!("Default pack loading failed: {}", e);
return Ok(3);
}
}
};
// Build lint options
let options = LintOptions {
packs,
max_results: Some(args.max_results),
bundle_path: Some(bundle.display().to_string()),
};
let result = match lint_bundle_with_options(f, limits, options) {
Ok(r) => r,
Err(e) => {
ReportLines::new(std::io::stderr().lock())
.line(format!("Verification failed: {}", e))?;
return Ok(2);
}
};
let report = &result.report;
let pack_meta = &result.pack_meta;
match args.format {
LintFormat::Json => {
// Add disclaimer to JSON output for compliance packs
let mut json_report = serde_json::to_value(report)?;
if let Some(meta) = pack_meta {
if let Some(disclaimer) = &meta.disclaimer {
json_report
.as_object_mut()
.unwrap()
.insert("disclaimer".into(), serde_json::json!(disclaimer));
}
if meta.truncated {
json_report
.as_object_mut()
.unwrap()
.insert("truncated".into(), serde_json::json!(true));
json_report.as_object_mut().unwrap().insert(
"truncated_count".into(),
serde_json::json!(meta.truncated_count),
);
}
}
println!("{}", serde_json::to_string_pretty(&json_report)?);
}
LintFormat::Sarif => {
#[allow(deprecated)]
let sarif_options = SarifOptions {
pack_meta: pack_meta.clone(),
bundle_path: Some(bundle.display().to_string()),
working_directory: None, // Deprecated: no longer included in output
};
let sarif = to_sarif_with_options(report, sarif_options);
println!("{}", serde_json::to_string_pretty(&sarif)?);
}
LintFormat::Text => {
// Every line goes through `ReportLines`: the findings quote the bundle (a source, a
// bundle id), and a quoted string must neither reach the terminal as a control
// sequence nor add a line of its own.
let stderr = std::io::stderr();
let mut out = ReportLines::new(stderr.lock());
out.line("Assay Evidence Lint")?;
out.line("===================")?;
out.line(format!(
"Bundle: {} (events: {}, verified: {})",
report.bundle_meta.bundle_id, report.bundle_meta.event_count, report.verified
))?;
// Print pack info
if let Some(meta) = pack_meta {
let pack_str = meta
.packs
.iter()
.map(|p| {
let suffix = if is_default_pack && p.name == DEFAULT_PACK {
" (default)"
} else {
""
};
format!("{}@{}{}", p.name, p.version, suffix)
})
.collect::<Vec<_>>()
.join(", ");
out.line(format!("Packs: {}", pack_str))?;
if is_default_pack {
out.line("(Next: add compliance packs — --pack eu-ai-act-baseline or --pack soc2-baseline)")?;
}
// Print disclaimer for compliance packs
if let Some(disclaimer) = &meta.disclaimer {
out.blank()?;
out.line("⚠️ COMPLIANCE DISCLAIMER")?;
// `split`, not `lines`: a pack's disclaimer ends with a newline, and the
// report has always printed the empty line that follows it.
for line in disclaimer.split('\n') {
out.line(line)?;
}
}
if meta.truncated {
out.blank()?;
out.line(format!(
"⚠️ Results truncated: {} findings omitted (--max-results {})",
meta.truncated_count, args.max_results
))?;
}
}
if !report.skipped_rules.is_empty() {
out.blank()?;
out.line(format!(
"⚠️ Rules not run: {} (this engine cannot execute them, so they produced no findings)",
report.skipped_rules.len()
))?;
for skipped in &report.skipped_rules {
out.line(format!(" {}: {}", skipped.rule_id, skipped.reason))?;
}
}
out.blank()?;
if report.findings.is_empty() {
out.line("No findings.")?;
} else {
for finding in &report.findings {
let loc_str = match &finding.location {
Some(loc) => format!("seq:{} line:{}", loc.seq, loc.line),
None => "global".into(),
};
// Extract article_ref from tags if present
let article_ref = finding
.tags
.iter()
.find(|t| t.starts_with("article_ref:"))
.map(|t| t.strip_prefix("article_ref:").unwrap_or(""));
if let Some(ref_) = article_ref {
out.line(format!(
"[{}] {} ({}) {} [Article {}]",
finding.severity, finding.rule_id, loc_str, finding.message, ref_
))?;
} else {
out.line(format!(
"[{}] {} ({}) {}",
finding.severity, finding.rule_id, loc_str, finding.message
))?;
}
out.line(format!(
" Hint: run `assay evidence lint --explain {}`",
finding.rule_id
))?;
}
out.blank()?;
out.line(format!(
"Summary: {} total ({} errors, {} warnings, {} info)",
report.summary.total,
report.summary.errors,
report.summary.warnings,
report.summary.infos
))?;
}
}
}
// Exit codes: 0 = no findings at/above threshold, 1 = findings found, 2 = verification failure, 3 = pack error
match gate_threshold(args.fail_on) {
Some(t) if report.has_findings_at_or_above(&t) => Ok(1),
_ => Ok(0),
}
}
/// The severity at which a finding gates the run, or `None` when no finding does.
///
/// `none` exists because a caller that reads the SARIF itself needs a non-zero exit to mean a pack
/// or runtime fault rather than a policy finding. `assay-action` asks for it with a hard-coded
/// `--fail-on none` at `action.yml:888`, and it was never implemented: the old match sent it to
/// `_ => Severity::Error`, gating on exactly the findings the caller had asked to ignore.
///
/// The action input also called `fail_on` used to be a different thing, implemented in a bash
/// `case` that never reached this flag and had no default arm, so any value it did not recognize
/// gated nothing. It now forwards the input here unmodified, which makes this function the only
/// definition of the threshold vocabulary on either side of that boundary.
///
/// The value parser on `--fail-on` decides what reaches this function, so an unrecognized value is
/// rejected before the command runs and never arrives here.
fn gate_threshold(fail_on: FailOn) -> Option<Severity> {
match fail_on {
FailOn::None => None,
FailOn::Warn => Some(Severity::Warn),
FailOn::Info => Some(Severity::Info),
FailOn::Error => Some(Severity::Error),
}
}
/// Load packs for lint (default or explicit).
fn load_packs_for_lint(
pack_refs: &Option<Vec<String>>,
) -> Result<Vec<LoadedPack>, assay_evidence::lint::packs::PackError> {
let refs: Vec<String> = pack_refs
.clone()
.unwrap_or_else(|| vec![DEFAULT_PACK.to_string()]);
load_packs(&refs)
}
/// Print rule help and exit. Returns Ok(0) on success, Ok(1) if not found or ambiguous.
fn explain_rule(packs: &[LoadedPack], rule_ref: &str) -> Result<i32> {
let want_canonical = rule_ref.contains('@') && rule_ref.contains(':');
let mut matches: Vec<(
&LoadedPack,
&assay_evidence::lint::packs::schema::PackRule,
String,
)> = Vec::new();
for p in packs {
for r in &p.definition.rules {
let canonical = p.canonical_rule_id(&r.id);
let ok = if want_canonical {
canonical == rule_ref
} else {
r.id == rule_ref || canonical == rule_ref
};
if ok {
matches.push((p, r, canonical));
}
}
}
if matches.is_empty() {
eprintln!("Rule '{}' not found in selected packs.", rule_ref);
return Ok(1);
}
if matches.len() > 1 && !want_canonical {
eprintln!("Rule '{}' is ambiguous. Specify canonical form:", rule_ref);
for (_, _, canonical) in &matches {
eprintln!(" --explain {}", canonical);
}
return Ok(1);
}
let (p, r, canonical) = &matches[0];
println!("{}", canonical);
println!("Pack: {}@{}", p.definition.name, p.definition.version);
println!("Severity: {:?}", r.severity);
println!();
println!("{}", r.description);
if let Some(article) = &r.article_ref {
println!();
println!("Reference: {}", article);
}
if let Some(help) = &r.help_markdown {
println!();
println!("---");
println!("{}", help.trim());
println!();
} else {
println!();
println!("(No additional help text provided.)");
}
Ok(0)
}
#[cfg(test)]
mod gate_threshold_tests {
use super::*;
#[test]
fn none_gates_on_nothing() {
assert_eq!(gate_threshold(FailOn::None), None);
}
/// Every accepted value must carry its own intent. Before `none` existed it shared a threshold
/// with `error`, which inverted what the caller asked for.
#[test]
fn each_accepted_value_maps_to_its_own_threshold() {
assert_eq!(gate_threshold(FailOn::Error), Some(Severity::Error));
assert_eq!(gate_threshold(FailOn::Warn), Some(Severity::Warn));
assert_eq!(gate_threshold(FailOn::Warn), Some(Severity::Warn));
assert_eq!(gate_threshold(FailOn::Info), Some(Severity::Info));
assert_ne!(gate_threshold(FailOn::None), gate_threshold(FailOn::Error));
}
}