-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
881 lines (803 loc) · 30.5 KB
/
Copy pathmod.rs
File metadata and controls
881 lines (803 loc) · 30.5 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
// SPDX-License-Identifier: MPL-2.0
//! Assail static analysis module
//!
//! Pre-analyzes target programs to identify weak points and recommend attacks
pub mod analyzer;
pub mod patterns;
use crate::kanren::core::{FactDB, LogicEngine};
use crate::kanren::crosslang::CrossLangAnalyzer;
use crate::kanren::strategy::{self, SearchStrategy};
use crate::kanren::taint::TaintAnalyzer;
use crate::types::*;
use anyhow::Result;
use std::path::Path;
pub use analyzer::Analyzer;
/// Run Assail analysis on a target program
pub fn analyze<P: AsRef<Path>>(target: P) -> Result<AssailReport> {
// Non-verbose mode keeps stdout clean for automation pipelines.
let analyzer = Analyzer::new(target.as_ref())?;
let mut report = analyzer.analyze()?;
// analyze() already runs suppression + user classifications; the
// explicit calls below are no-ops for existing reports but keep
// the contract explicit: apply_suppression first, then
// apply_user_classifications against the same target root.
apply_suppression(&mut report);
let target_ref = target.as_ref();
let root = if target_ref.is_dir() {
target_ref.to_path_buf()
} else {
target_ref.parent().unwrap_or(Path::new(".")).to_path_buf()
};
apply_user_classifications(&mut report, &root);
Ok(report)
}
/// Run Assail analysis with verbose output including per-file breakdown
/// and miniKanren logic engine results
pub fn analyze_verbose<P: AsRef<Path>>(target: P) -> Result<AssailReport> {
// Verbose mode is operator-facing and intentionally prints prioritization context.
let analyzer = Analyzer::new_verbose(target.as_ref())?;
let mut report = analyzer.analyze()?;
apply_suppression(&mut report);
let target_ref = target.as_ref();
let root = if target_ref.is_dir() {
target_ref.to_path_buf()
} else {
target_ref.parent().unwrap_or(Path::new(".")).to_path_buf()
};
apply_user_classifications(&mut report, &root);
let active_count = report
.weak_points
.iter()
.filter(|wp| !wp.suppressed)
.count();
let suppressed_count = report.suppressed_count;
println!("Assail Analysis Complete");
println!(" Language: {:?}", report.language);
println!(" Frameworks: {:?}", report.frameworks);
// Filtered view: what CI/fleet sees (suppressed items excluded)
println!(
" Weak Points (active): {} — these count toward CI gates and fleet dispatch",
active_count
);
// Unfiltered view: full scan for audit transparency
if suppressed_count > 0 {
println!(
" Weak Points (total): {} — {} additional suppressed by FP rules (suppressed = \
likely false positive from defensive pattern; see --show-suppressed for detail)",
report.weak_points.len(),
suppressed_count
);
}
println!(" Recommended Attacks: {:?}", report.recommended_attacks);
// Per-file breakdown sorted by risk score
if !report.file_statistics.is_empty() {
// Use search strategy to determine optimal analysis order
let strategy = SearchStrategy::auto_select(&report);
let prioritised = strategy::prioritise_files(&report, strategy);
println!("\n Search Strategy: {:?}", strategy);
println!(" Per-file Breakdown (top 10 by risk):");
for (rank, file_risk) in prioritised.iter().take(10).enumerate() {
println!(
" {}. {} ({:?}, risk: {:.1})",
rank + 1,
file_risk.file_path,
file_risk.language,
file_risk.risk_score,
);
for factor in &file_risk.risk_factors {
println!(
" - {}: {:.0} (weight: {:.1})",
factor.name, factor.value, factor.weight,
);
}
}
if prioritised.len() > 10 {
println!(" ... and {} more files", prioritised.len() - 10);
}
}
// Run miniKanren logic engine for deeper analysis
run_logic_engine(&report);
Ok(report)
}
/// Run Assail analysis for browser extensions (ignores DevTools API eval() usage)
pub fn analyze_browser_extension<P: AsRef<Path>>(target: P) -> Result<AssailReport> {
let analyzer = Analyzer::new_browser_extension(target.as_ref())?;
let mut report = analyzer.analyze()?;
apply_suppression(&mut report);
Ok(report)
}
/// Run Assail analysis for browser extensions with verbose output
pub fn analyze_verbose_browser_extension<P: AsRef<Path>>(target: P) -> Result<AssailReport> {
let analyzer = Analyzer::new_verbose_browser_extension(target.as_ref())?;
let mut report = analyzer.analyze()?;
apply_suppression(&mut report);
let active_count = report
.weak_points
.iter()
.filter(|wp| !wp.suppressed)
.count();
let suppressed_count = report.suppressed_count;
println!("Assail Analysis Complete (Browser Extension Mode)");
println!(" Language: {:?}", report.language);
println!(" Frameworks: {:?}", report.frameworks);
println!(
" Weak Points (active): {} — these count toward CI gates and fleet dispatch",
active_count
);
if suppressed_count > 0 {
println!(
" Weak Points (total): {} — {} additional suppressed by FP rules",
report.weak_points.len(),
suppressed_count
);
}
println!(" Recommended Attacks: {:?}", report.recommended_attacks);
println!(" Note: eval() checks skipped for DevTools API usage");
if !report.file_statistics.is_empty() {
let strategy = SearchStrategy::auto_select(&report);
let prioritised = strategy::prioritise_files(&report, strategy);
println!("\n Search Strategy: {:?}", strategy);
println!(" Per-file Breakdown (top 10 by risk):");
for (rank, file_risk) in prioritised.iter().take(10).enumerate() {
println!(
" {}. {} ({:?}, risk: {:.1})",
rank + 1,
file_risk.file_path,
file_risk.language,
file_risk.risk_score,
);
for factor in &file_risk.risk_factors {
println!(
" - {}: {:.0} (weight: {:.1})",
factor.name, factor.value, factor.weight,
);
}
}
if prioritised.len() > 10 {
println!(" ... and {} more files", prioritised.len() - 10);
}
}
run_logic_engine(&report);
Ok(report)
}
/// A single classification entry read from a project's
/// `audits/assail-classifications.a2ml` (or `.panic-attack-classifications.a2ml`).
/// When such a file exists, findings matching `(file, category)` are flipped
/// to `suppressed = true` after the kanren suppression pass runs.
///
/// The registry pattern lets repositories record "this finding has been
/// audited and is sound" out-of-band from the source file — so the
/// suppression is not gameable by code-only edits (adding a new unsafe
/// block cannot also add its own classification without editing the
/// registry, which is reviewable in the same PR).
#[derive(Debug, Clone)]
pub struct UserClassification {
pub file: String,
pub category: String,
}
/// Load user classifications from `<project_root>/audits/assail-classifications.a2ml`.
///
/// Empty vector if the file is absent or unreadable. Errors are swallowed by
/// design — the classification registry is optional and a missing file must
/// not break the assail pass.
///
/// Format (A2ML S-expression):
///
/// ```text
/// (assail-classifications
/// (classification
/// (file "crates/oo7-core/src/zig_bridge.rs")
/// (category "UnsafeCode")
/// (audit "audits/audit-ffi-unsafe.md §1"))
/// ...)
/// ```
pub fn load_user_classifications(project_root: &Path) -> Vec<UserClassification> {
use std::fs;
let candidate_paths = [
project_root
.join("audits")
.join("assail-classifications.a2ml"),
project_root.join(".panic-attack-classifications.a2ml"),
];
// User-classification a2ml files are hand-edited audit registries. A
// legitimate one rarely exceeds a few dozen KiB. Capping at 4 MiB
// stops a malicious or accidental input from exhausting memory during
// a multi-thousand-repo mass-panic sweep.
use std::io::Read;
const CLASSIFICATIONS_FILE_READ_LIMIT: u64 = 4 * 1024 * 1024;
let mut content = String::new();
for p in &candidate_paths {
if let Ok(mut f) = fs::File::open(p) {
let mut buf = String::new();
if (&mut f)
.take(CLASSIFICATIONS_FILE_READ_LIMIT)
.read_to_string(&mut buf)
.is_ok()
{
content = buf;
break;
}
}
}
if content.is_empty() {
return Vec::new();
}
// Strip `;;` line comments.
let stripped: String = content
.lines()
.map(|l| match l.find(";;") {
Some(idx) => &l[..idx],
None => l,
})
.collect::<Vec<_>>()
.join("\n");
let mut classifications = Vec::new();
let needle = "(classification";
let mut rest = stripped.as_str();
while let Some(start) = rest.find(needle) {
let after_keyword = &rest[start + needle.len()..];
// Walk characters tracking paren depth to find the matching ')'.
let mut depth: i32 = 1;
let mut end_idx: Option<usize> = None;
for (i, c) in after_keyword.char_indices() {
match c {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
end_idx = Some(i);
break;
}
}
_ => {}
}
}
let Some(end) = end_idx else {
break;
};
let body = &after_keyword[..end];
let file = extract_classification_field(body, "file");
let category = extract_classification_field(body, "category");
if let (Some(f), Some(c)) = (file, category) {
classifications.push(UserClassification {
file: f,
category: c,
});
}
rest = &after_keyword[end + 1..];
}
classifications
}
fn extract_classification_field(body: &str, field: &str) -> Option<String> {
let marker = format!("({} \"", field);
let idx = body.find(&marker)?;
let after = &body[idx + marker.len()..];
let end = after.find('"')?;
Some(after[..end].to_string())
}
/// Apply user classifications to a report in-place. Findings whose file
/// and category match an entry in the project's
/// `assail-classifications.a2ml` are marked `suppressed = true` and
/// counted toward `report.suppressed_count`.
///
/// Runs after the kanren-based `apply_suppression` so that the
/// structural suppression rules get first pass and the classification
/// registry covers only the genuinely-audited residuals.
pub fn apply_user_classifications(report: &mut AssailReport, project_root: &Path) {
let classifications = load_user_classifications(project_root);
if classifications.is_empty() {
return;
}
let mut additional: usize = 0;
for wp in &mut report.weak_points {
if wp.suppressed {
continue;
}
let cat = format!("{:?}", wp.category);
let loc = wp.location.as_deref().unwrap_or("");
for cl in &classifications {
if cl.category == cat && cl.file == loc {
wp.suppressed = true;
additional += 1;
break;
}
}
}
report.suppressed_count += additional;
}
/// Apply context-aware FP suppression to an assail report in-place.
///
/// Runs the full kanren logic engine, collects every `suppressed(Category, Location)`
/// fact derived by the 12 suppression rules, and marks the matching `WeakPoint`s
/// with `suppressed = true`. Also writes the suppression count to
/// `report.suppressed_count`.
///
/// Called automatically by `analyze()` and `analyze_verbose()`.
/// The suppressed items remain in `weak_points` for auditability; callers
/// (panicbot's translator, CI gates) should filter on `suppressed: false`.
pub fn apply_suppression(report: &mut AssailReport) {
let db = build_logic_db(report);
let mut count = 0usize;
for fact in db.get_facts("suppressed") {
if fact.args.len() != 2 {
continue;
}
let category_str = match &fact.args[0] {
crate::kanren::core::Term::Atom(s) => s.clone(),
_ => continue,
};
let location_str = match &fact.args[1] {
crate::kanren::core::Term::Atom(s) => s.clone(),
_ => continue,
};
// Flip every matching weak point, not just the first. Facts in
// the kanren DB are deduped by (name, args), so a single
// `suppressed(Category, File)` derivation represents "every
// finding of this (category, file) tuple is a false positive"
// — NOT "one arbitrary finding is a FP." The previous
// `break`-after-first behaviour meant a file with multiple
// findings of the same category (e.g. zig_bridge.rs with both
// "N unsafe blocks" and "Raw pointer cast" UnsafeCode
// findings) would only have one finding flipped per call, and
// the second would stay active unless a downstream pass ran
// the suppression again. Removing the `break` makes the
// behaviour idempotent in a single pass.
for wp in &mut report.weak_points {
if wp.suppressed {
continue;
}
let wp_cat = format!("{:?}", wp.category);
let wp_loc = wp.location.as_deref().unwrap_or("unknown");
if wp_cat == category_str && wp_loc == location_str {
wp.suppressed = true;
count += 1;
}
}
}
// v2.5.5 context-aware suppression pass — uses the test_context /
// comment_marker / ffi_kind / jit_context foundation modules to
// classify each finding's location and flip suppressed = true for
// findings that fall in a known-acceptable context. Runs AFTER the
// kanren-based rules above so kanren rule explanations remain the
// authoritative source for findings suppressed by structural rules.
count += apply_v255_context_suppression(report);
report.suppressed_count = count;
}
/// v2.5.5 context-aware FP suppression pass — applies four checks per
/// finding:
/// 1. Inline `panic-attack: accepted` marker on the same or
/// preceding line ([[comment_marker]]).
/// 2. PanicPath finding in a TestOnly or Doc test_context
/// ([[test_context]]).
/// 3. UnsafeFFI finding where the file's [[ffi_kind]] is
/// `BuildSystem` or `TestMock` (audit-accepted by default).
/// 4. (jit_context wire-up handled inline in analyzer.rs:1117..1129
/// already; not duplicated here.)
///
/// Sets `wp.test_context` for every finding with a known file path so
/// downstream audit consumers can render it. Returns the number of
/// findings newly flipped from `suppressed=false` to `suppressed=true`
/// (already-suppressed findings are NOT re-counted).
pub fn apply_v255_context_suppression(report: &mut AssailReport) -> usize {
use crate::comment_marker;
use crate::ffi_kind::FfiKind;
use crate::test_context;
use crate::types::{TestContext, WeakPointCategory};
let mut newly_suppressed = 0usize;
let mut content_cache: std::collections::HashMap<String, Option<String>> =
std::collections::HashMap::new();
for wp in &mut report.weak_points {
// Determine the file path; prefer the structured `file` field,
// fall back to parsing `location` ("path:line").
let file_path: Option<String> = wp.file.clone().or_else(|| {
wp.location.as_ref().and_then(|loc| {
loc.rsplit_once(':').map(|(p, _)| p.to_string()).or_else(|| Some(loc.clone()))
})
});
let Some(file) = file_path else { continue };
// Load (and cache) the file's content for marker scanning. Files
// not on disk (synthetic locations, removed-since-scan) cache
// None so we don't repeatedly retry.
let content_opt = content_cache
.entry(file.clone())
.or_insert_with(|| std::fs::read_to_string(&file).ok())
.clone();
// Always set test_context — even when the finding isn't a
// suppression candidate, downstream consumers benefit from the
// classification metadata.
if wp.test_context.is_none() {
let ctx = match content_opt.as_deref() {
Some(c) => test_context::classify(&file, c),
None => test_context::classify_path(&file),
};
wp.test_context = Some(ctx);
}
if wp.suppressed {
continue;
}
// (1) Marker-based suppression.
if let (Some(content), Some(line)) = (content_opt.as_deref(), wp.line) {
if comment_marker::is_suppressed_at(content, line).is_some() {
wp.suppressed = true;
newly_suppressed += 1;
continue;
}
}
// (2) PanicPath in test/doc scope.
if matches!(wp.category, WeakPointCategory::PanicPath)
&& matches!(
wp.test_context,
Some(TestContext::TestOnly) | Some(TestContext::Doc)
)
{
wp.suppressed = true;
newly_suppressed += 1;
continue;
}
// (3) UnsafeFFI in BuildSystem/TestMock context.
if matches!(wp.category, WeakPointCategory::UnsafeFFI) {
let kind = FfiKind::classify_by_path(&file);
if kind.is_audit_accepted_by_default() {
wp.suppressed = true;
newly_suppressed += 1;
continue;
}
}
}
newly_suppressed
}
/// Build a fully-populated kanren FactDB from an assail report.
///
/// Ingest all facts (report, taint, cross-language, context) and run
/// forward chaining including FP suppression rules.
pub fn build_logic_db(report: &AssailReport) -> FactDB {
let mut engine = LogicEngine::new();
engine.ingest_report(report);
TaintAnalyzer::extract_facts(&mut engine.db, report);
TaintAnalyzer::load_rules(&mut engine.db);
CrossLangAnalyzer::extract_facts(&mut engine.db, report);
CrossLangAnalyzer::load_rules(&mut engine.db);
engine.extract_context_facts(report);
engine.load_suppression_rules();
engine.analyze();
engine.db
}
/// Run the miniKanren-inspired logic engine on a completed report
fn run_logic_engine(report: &AssailReport) {
let mut engine = LogicEngine::new();
// Phase 1: Ingest report facts
engine.ingest_report(report);
// Phase 2: Extract taint source/sink facts
TaintAnalyzer::extract_facts(&mut engine.db, report);
TaintAnalyzer::load_rules(&mut engine.db);
// Phase 3: Extract cross-language interaction facts
CrossLangAnalyzer::extract_facts(&mut engine.db, report);
CrossLangAnalyzer::load_rules(&mut engine.db);
// Phase 4: Extract context facts and load FP suppression rules
engine.extract_context_facts(report);
engine.load_suppression_rules();
// Phase 5: Run forward chaining
let results = engine.analyze();
println!("\n Logic Engine Results:");
println!(" Total facts: {}", results.total_facts);
println!(" Derived facts: {}", results.derived_facts);
println!(" Tainted paths: {}", results.tainted_paths);
println!(
" Critical vulnerabilities: {}",
results.critical_vulnerabilities
);
println!(" High vulnerabilities: {}", results.high_vulnerabilities);
println!(" Cross-language vulns: {}", results.cross_language_vulns);
if results.suppressed_false_positives > 0 {
println!(
" Suppressed false positives: {}",
results.suppressed_false_positives
);
}
// Query taint flows
let flows = TaintAnalyzer::query_flows(&engine.db);
if !flows.is_empty() {
println!("\n Taint Flows ({}):", flows.len());
for flow in flows.iter().take(10) {
println!(
" {:?} -> {:?} ({} -> {}, confidence: {:.2})",
flow.source, flow.sink, flow.source_file, flow.sink_file, flow.confidence,
);
}
if flows.len() > 10 {
println!(" ... and {} more flows", flows.len() - 10);
}
}
// Query cross-language interactions
let interactions = CrossLangAnalyzer::query_interactions(&engine.db);
if !interactions.is_empty() {
println!(
"\n Cross-Language Interactions ({}):",
interactions.len()
);
for interaction in interactions.iter().take(10) {
println!(
" {} ({:?}) -> {} ({:?}) via {:?} (risk: {:.2})",
interaction.caller_file,
interaction.caller_lang,
interaction.callee_file,
interaction.callee_lang,
interaction.mechanism,
interaction.risk_score,
);
}
if interactions.len() > 10 {
println!(
" ... and {} more interactions",
interactions.len() - 10
);
}
}
}
#[cfg(test)]
mod classifications_tests {
use super::*;
use std::fs;
use tempfile::TempDir;
fn write_registry(dir: &Path, content: &str) {
let audits = dir.join("audits");
fs::create_dir_all(&audits).unwrap();
fs::write(audits.join("assail-classifications.a2ml"), content).unwrap();
}
#[test]
fn load_empty_when_no_registry() {
let tmp = TempDir::new().unwrap();
let classifications = load_user_classifications(tmp.path());
assert!(
classifications.is_empty(),
"Missing registry must yield empty classification list"
);
}
#[test]
fn load_single_classification() {
let tmp = TempDir::new().unwrap();
write_registry(
tmp.path(),
r#";; SPDX-License-Identifier: MPL-2.0
(assail-classifications
(classification
(file "crates/oo7-core/src/zig_bridge.rs")
(category "UnsafeCode")
(audit "audits/audit-ffi-unsafe.md §1")))
"#,
);
let classifications = load_user_classifications(tmp.path());
assert_eq!(classifications.len(), 1);
assert_eq!(classifications[0].file, "crates/oo7-core/src/zig_bridge.rs");
assert_eq!(classifications[0].category, "UnsafeCode");
}
#[test]
fn load_multiple_classifications() {
let tmp = TempDir::new().unwrap();
write_registry(
tmp.path(),
r#"(assail-classifications
(classification
(file "a/b.rs")
(category "UnsafeCode")
(audit "doc1"))
(classification
(file "c/d.rs")
(category "PanicPath")
(audit "doc2")))
"#,
);
let classifications = load_user_classifications(tmp.path());
assert_eq!(classifications.len(), 2);
assert_eq!(classifications[0].file, "a/b.rs");
assert_eq!(classifications[1].category, "PanicPath");
}
#[test]
fn comment_lines_are_ignored() {
let tmp = TempDir::new().unwrap();
write_registry(
tmp.path(),
r#";; Header comment
;; (classification (file "should-not-parse") (category "X"))
(assail-classifications
(classification
(file "real/path.rs")
(category "UnsafeCode")
(audit "doc")))
"#,
);
let classifications = load_user_classifications(tmp.path());
assert_eq!(classifications.len(), 1);
assert_eq!(classifications[0].file, "real/path.rs");
}
#[test]
fn apply_flips_matching_finding_to_suppressed() {
use crate::types::{
AssailReport, AttackAxis, Language, ProgramStatistics, Severity, WeakPoint,
WeakPointCategory,
};
let tmp = TempDir::new().unwrap();
write_registry(
tmp.path(),
r#"(assail-classifications
(classification
(file "crates/oo7-core/src/zig_bridge.rs")
(category "UnsafeCode")
(audit "audits/audit-ffi-unsafe.md §1")))
"#,
);
let mut report = AssailReport {
schema_version: "2.5".to_string(),
program_path: tmp.path().to_path_buf(),
language: Language::Rust,
frameworks: vec![],
weak_points: vec![
WeakPoint {
file: None,
line: None,
category: WeakPointCategory::UnsafeCode,
location: Some("crates/oo7-core/src/zig_bridge.rs".to_string()),
severity: Severity::High,
description: "8 unsafe blocks".to_string(),
recommended_attack: vec![AttackAxis::Memory],
suppressed: false,
test_context: None,
},
WeakPoint {
file: None,
line: None,
category: WeakPointCategory::UnsafeCode,
location: Some("other/file.rs".to_string()),
severity: Severity::High,
description: "unsafe block".to_string(),
recommended_attack: vec![AttackAxis::Memory],
suppressed: false,
test_context: None,
},
],
statistics: ProgramStatistics {
total_lines: 0,
unsafe_blocks: 0,
panic_sites: 0,
unwrap_calls: 0,
allocation_sites: 0,
io_operations: 0,
threading_constructs: 0,
safe_unwrap_calls: 0,
},
file_statistics: vec![],
recommended_attacks: vec![],
dependency_graph: Default::default(),
taint_matrix: Default::default(),
migration_metrics: None,
suppressed_count: 0,
};
apply_user_classifications(&mut report, tmp.path());
assert!(
report.weak_points[0].suppressed,
"Classified finding must be suppressed"
);
assert!(
!report.weak_points[1].suppressed,
"Unclassified finding must stay active"
);
assert_eq!(report.suppressed_count, 1);
}
}
#[cfg(test)]
mod v255_context_suppression_tests {
use super::apply_v255_context_suppression;
use crate::types::{
AssailReport, AttackAxis, ProgramStatistics, Severity, TestContext,
WeakPoint, WeakPointCategory,
};
use std::fs;
use tempfile::TempDir;
fn report_with(wp: Vec<WeakPoint>) -> AssailReport {
AssailReport {
schema_version: "2.5".to_string(),
program_path: std::path::PathBuf::from("test"),
language: crate::types::Language::Rust,
statistics: ProgramStatistics::default(),
file_statistics: vec![],
weak_points: wp,
frameworks: vec![],
recommended_attacks: vec![],
dependency_graph: Default::default(),
taint_matrix: Default::default(),
migration_metrics: None,
suppressed_count: 0,
}
}
fn wp(category: WeakPointCategory, location: &str) -> WeakPoint {
WeakPoint {
category,
location: Some(location.to_string()),
file: None,
line: None,
severity: Severity::Medium,
description: "test".to_string(),
recommended_attack: vec![AttackAxis::Memory],
suppressed: false,
test_context: None,
}
.with_parsed_location()
}
#[test]
fn panic_path_in_test_file_is_suppressed() {
let mut report = report_with(vec![wp(
WeakPointCategory::PanicPath,
"tests/foo.rs:42",
)]);
let n = apply_v255_context_suppression(&mut report);
assert_eq!(n, 1);
assert!(report.weak_points[0].suppressed);
assert_eq!(
report.weak_points[0].test_context,
Some(TestContext::TestOnly)
);
}
#[test]
fn panic_path_in_prod_file_not_suppressed() {
let mut report = report_with(vec![wp(
WeakPointCategory::PanicPath,
"src/main.rs:42",
)]);
let n = apply_v255_context_suppression(&mut report);
assert_eq!(n, 0);
assert!(!report.weak_points[0].suppressed);
assert_eq!(
report.weak_points[0].test_context,
Some(TestContext::Production)
);
}
#[test]
fn unsafe_ffi_in_build_zig_is_suppressed() {
let mut report =
report_with(vec![wp(WeakPointCategory::UnsafeFFI, "build.zig:5")]);
let n = apply_v255_context_suppression(&mut report);
assert_eq!(n, 1);
assert!(report.weak_points[0].suppressed);
}
#[test]
fn unsafe_ffi_in_bindings_not_suppressed() {
let mut report = report_with(vec![wp(
WeakPointCategory::UnsafeFFI,
"bindings/zig/cdef.zig:5",
)]);
let n = apply_v255_context_suppression(&mut report);
assert_eq!(n, 0);
assert!(!report.weak_points[0].suppressed);
}
#[test]
fn marker_suppression_via_filesystem() {
let tmp = TempDir::new().unwrap();
let path = tmp.path().join("foo.rs");
// Line 2 has an unwrap; line 1 has the marker.
fs::write(&path, "// panic-attack: accepted - test\nlet x = foo.unwrap();\n").unwrap();
let mut report = report_with(vec![wp(
WeakPointCategory::UnsafeCode,
&format!("{}:2", path.display()),
)]);
let n = apply_v255_context_suppression(&mut report);
assert_eq!(n, 1);
assert!(report.weak_points[0].suppressed);
}
#[test]
fn already_suppressed_finding_not_recounted() {
let mut report = report_with(vec![WeakPoint {
suppressed: true,
..wp(WeakPointCategory::PanicPath, "tests/foo.rs:42")
}]);
let n = apply_v255_context_suppression(&mut report);
// Already-suppressed findings are not counted as newly-suppressed,
// but their test_context is still classified for downstream
// consumers.
assert_eq!(n, 0);
assert!(report.weak_points[0].suppressed);
assert_eq!(
report.weak_points[0].test_context,
Some(TestContext::TestOnly)
);
}
}