-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtranslator.rs
More file actions
740 lines (694 loc) · 29 KB
/
Copy pathtranslator.rs
File metadata and controls
740 lines (694 loc) · 29 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
// SPDX-License-Identifier: MPL-2.0
//! Translator — converts panic-attack WeakPoints into gitbot-fleet Findings.
//!
//! Core responsibility: map each `WeakPoint` from the scanner output into a
//! `Finding` struct with appropriate:
//! - Fleet category (e.g., "static-analysis/unsafe-code")
//! - Rule ID (canonical PA001–PA025 pattern for dedup with Hypatia findings)
//! - Triangle tier (Eliminate / Substitute / Control)
//! - Confidence score (honest assessment of detection accuracy)
//! - Fixability (whether automated remediation is possible)
//!
//! ## Confidence Philosophy
//!
//! These are static analysis findings from regex/AST pattern matching, NOT
//! from formal verification. Confidence values reflect honest false-positive
//! rates for each category. Values above 0.90 mean "almost certainly a real
//! bug" — we only claim that for trivially detectable patterns like
//! `String.to_atom` (atom exhaustion) or `pickle.load` (unsafe deser).
use crate::config::PanicbotConfig;
use crate::scanner::WeakPoint;
use gitbot_shared_context::bot::BotId;
use gitbot_shared_context::finding::{Finding, Severity};
use gitbot_shared_context::triangle::TriangleTier;
use std::path::PathBuf;
/// Fixability classification for a finding.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Fixability {
/// Can be automatically fixed by robot-repo-automaton.
Yes,
/// Partially fixable — some instances can be auto-fixed, others need review.
Partial,
/// Cannot be auto-fixed — requires human judgement.
No,
}
/// Translation metadata for a single WeakPoint category.
///
/// Encapsulates the mapping rules for converting a panic-attack category
/// into fleet-compatible finding attributes.
#[derive(Debug, Clone)]
pub struct CategoryMapping {
/// Fleet category string (e.g., "static-analysis/unsafe-code").
pub fleet_category: &'static str,
/// Canonical rule ID for deduplication (e.g., "PA001").
pub rule_id: &'static str,
/// Human-readable rule name.
pub rule_name: &'static str,
/// Safety triangle tier.
pub triangle_tier: TriangleTier,
/// Default confidence score (0.0 - 1.0).
pub default_confidence: f64,
/// Whether findings in this category can be auto-fixed.
pub fixability: Fixability,
}
/// Look up the mapping for a panic-attack WeakPoint category.
///
/// Returns `None` for unrecognised categories — the caller should log a
/// warning and produce a generic finding.
pub fn category_mapping(category: &str) -> Option<CategoryMapping> {
match category {
"UnsafeCode" => Some(CategoryMapping {
fleet_category: "static-analysis/unsafe-code",
rule_id: "PA001",
rule_name: "Unsafe code block",
triangle_tier: TriangleTier::Control,
default_confidence: 0.70,
fixability: Fixability::No,
}),
"PanicPath" => Some(CategoryMapping {
fleet_category: "static-analysis/panic-path",
rule_id: "PA002",
rule_name: "Potential panic path",
triangle_tier: TriangleTier::Substitute,
default_confidence: 0.70,
fixability: Fixability::Partial,
}),
"CommandInjection" => Some(CategoryMapping {
fleet_category: "static-analysis/command-injection",
rule_id: "PA003",
rule_name: "Command injection risk",
triangle_tier: TriangleTier::Control,
default_confidence: 0.80,
fixability: Fixability::No,
}),
"HardcodedSecret" => Some(CategoryMapping {
fleet_category: "static-analysis/hardcoded-secret",
rule_id: "PA004",
rule_name: "Hardcoded secret or credential",
triangle_tier: TriangleTier::Eliminate,
default_confidence: 0.88,
fixability: Fixability::Yes,
}),
"UnsafeDeserialization" => Some(CategoryMapping {
fleet_category: "static-analysis/unsafe-deser",
rule_id: "PA005",
rule_name: "Unsafe deserialization",
triangle_tier: TriangleTier::Eliminate,
default_confidence: 0.87,
fixability: Fixability::Yes,
}),
"UncheckedError" => Some(CategoryMapping {
fleet_category: "static-analysis/unchecked-error",
rule_id: "PA006",
rule_name: "Unchecked error / unwrap",
triangle_tier: TriangleTier::Eliminate,
default_confidence: 0.75,
fixability: Fixability::Yes,
}),
"UnsafeFFI" => Some(CategoryMapping {
fleet_category: "static-analysis/unsafe-ffi",
rule_id: "PA007",
rule_name: "Unsafe FFI boundary",
triangle_tier: TriangleTier::Control,
default_confidence: 0.75,
fixability: Fixability::No,
}),
"RaceCondition" => Some(CategoryMapping {
fleet_category: "static-analysis/race-condition",
rule_id: "PA008",
rule_name: "Potential race condition",
triangle_tier: TriangleTier::Control,
default_confidence: 0.60,
fixability: Fixability::No,
}),
"ResourceLeak" => Some(CategoryMapping {
fleet_category: "static-analysis/resource-leak",
rule_id: "PA009",
rule_name: "Resource leak",
triangle_tier: TriangleTier::Substitute,
default_confidence: 0.78,
fixability: Fixability::Partial,
}),
"PathTraversal" => Some(CategoryMapping {
fleet_category: "static-analysis/path-traversal",
rule_id: "PA010",
rule_name: "Path traversal risk",
triangle_tier: TriangleTier::Substitute,
default_confidence: 0.78,
fixability: Fixability::Partial,
}),
"AtomExhaustion" => Some(CategoryMapping {
fleet_category: "static-analysis/atom-exhaustion",
rule_id: "PA011",
rule_name: "Atom table exhaustion",
triangle_tier: TriangleTier::Eliminate,
default_confidence: 0.93,
fixability: Fixability::Yes,
}),
"ExcessivePermissions" => Some(CategoryMapping {
fleet_category: "static-analysis/excessive-perms",
rule_id: "PA012",
rule_name: "Excessive permissions",
triangle_tier: TriangleTier::Eliminate,
default_confidence: 0.88,
fixability: Fixability::Yes,
}),
"UnsafeTypeCoercion" => Some(CategoryMapping {
fleet_category: "static-analysis/unsafe-coercion",
rule_id: "PA013",
rule_name: "Unsafe type coercion",
triangle_tier: TriangleTier::Control,
default_confidence: 0.70,
fixability: Fixability::No,
}),
// Original panic-attack categories not in the primary mapping table
// but still valid findings:
"UncheckedAllocation" => Some(CategoryMapping {
fleet_category: "static-analysis/unchecked-alloc",
rule_id: "PA014",
rule_name: "Unchecked memory allocation",
triangle_tier: TriangleTier::Control,
default_confidence: 0.72,
fixability: Fixability::No,
}),
"UnboundedLoop" => Some(CategoryMapping {
fleet_category: "static-analysis/unbounded-loop",
rule_id: "PA015",
rule_name: "Unbounded loop",
triangle_tier: TriangleTier::Control,
default_confidence: 0.68,
fixability: Fixability::No,
}),
"BlockingIO" => Some(CategoryMapping {
fleet_category: "static-analysis/blocking-io",
rule_id: "PA016",
rule_name: "Blocking I/O in async context",
triangle_tier: TriangleTier::Substitute,
default_confidence: 0.72,
fixability: Fixability::Partial,
}),
"DeadlockPotential" => Some(CategoryMapping {
fleet_category: "static-analysis/deadlock",
rule_id: "PA017",
rule_name: "Deadlock potential",
triangle_tier: TriangleTier::Control,
default_confidence: 0.55,
fixability: Fixability::No,
}),
"DynamicCodeExecution" => Some(CategoryMapping {
fleet_category: "static-analysis/dynamic-exec",
rule_id: "PA018",
rule_name: "Dynamic code execution",
triangle_tier: TriangleTier::Control,
default_confidence: 0.82,
fixability: Fixability::No,
}),
"InsecureProtocol" => Some(CategoryMapping {
fleet_category: "static-analysis/insecure-proto",
rule_id: "PA019",
rule_name: "Insecure protocol usage",
triangle_tier: TriangleTier::Substitute,
default_confidence: 0.85,
fixability: Fixability::Yes,
}),
"InfiniteRecursion" => Some(CategoryMapping {
fleet_category: "static-analysis/infinite-recursion",
rule_id: "PA020",
rule_name: "Infinite recursion risk",
triangle_tier: TriangleTier::Control,
default_confidence: 0.65,
fixability: Fixability::No,
}),
// PA021 — formal verification drift: banned proof escape hatches (sorry, Admitted,
// believe_me, oops, trustMe, assert_total, %partial) or Julia mirror files that
// substitute `@test x isa Y` assertions for formally-proven theorems.
// Confidence is high because these keywords have essentially no false positives
// in proof assistant files — they exist only to bypass the checker.
"ProofDrift" => Some(CategoryMapping {
fleet_category: "static-analysis/proof-drift",
rule_id: "PA021",
rule_name: "Formal verification drift",
triangle_tier: TriangleTier::Control,
default_confidence: 0.92,
fixability: Fixability::No,
}),
// PA022 — cryptographic primitive misuse: MD5/SHA-1 in security contexts
// (password, secret, token, auth, key, credential, hash, sign, verify, encrypt),
// and == comparisons on secret-named variables (timing side-channel).
// Confidence 0.75 — the context-window heuristic works well but has a modest
// false-positive rate when security vocabulary appears nearby for unrelated reasons.
"CryptoMisuse" => Some(CategoryMapping {
fleet_category: "static-analysis/crypto-misuse",
rule_id: "PA022",
rule_name: "Cryptographic primitive misuse",
triangle_tier: TriangleTier::Eliminate,
default_confidence: 0.75,
fixability: Fixability::Partial,
}),
// PA023 — supply chain integrity: unpinned or unverified dependencies and absent
// lock files. Cargo.toml git deps without rev=, absent Cargo.lock for lib/bin crates,
// Julia Manifest.toml without git-tree-sha1 entries, flake.nix inputs without narHash,
// deno.json import map entries without version pin. These are fixable by adding pins.
"SupplyChain" => Some(CategoryMapping {
fleet_category: "static-analysis/supply-chain",
rule_id: "PA023",
rule_name: "Supply chain integrity gap",
triangle_tier: TriangleTier::Eliminate,
default_confidence: 0.85,
fixability: Fixability::Yes,
}),
// PA024 — input boundary: unchecked deserialization of CBOR/MessagePack (serde_cbor,
// ciborium, rmp_serde in Rust), JSON.parse without try-catch (JavaScript), JSON3.read
// without error handling (Julia). Confidence 0.72 — per-file heuristics have false
// positives when error handling is in the call site rather than the same file.
"InputBoundary" => Some(CategoryMapping {
fleet_category: "static-analysis/input-boundary",
rule_id: "PA024",
rule_name: "Unguarded input boundary",
triangle_tier: TriangleTier::Control,
default_confidence: 0.72,
fixability: Fixability::Partial,
}),
// PA025 — mutation gap: test suites with no mutation-test tooling or no assertion
// diversity. Rust projects without cargo-mutants config, Elixir without StreamData/
// ExUnitProperties, Julia @testset with only type-check assertions. Confidence 0.80 —
// absent tooling is factual; assertion diversity heuristic has modest FP rate.
"MutationGap" => Some(CategoryMapping {
fleet_category: "static-analysis/mutation-gap",
rule_id: "PA025",
rule_name: "Mutation coverage gap",
triangle_tier: TriangleTier::Substitute,
default_confidence: 0.80,
fixability: Fixability::Partial,
}),
_ => None,
}
}
/// Map a panic-attack severity string to a fleet Severity enum.
fn map_severity(panic_attack_severity: &str) -> Severity {
match panic_attack_severity.to_lowercase().as_str() {
"critical" => Severity::Error,
"high" => Severity::Warning,
"medium" => Severity::Info,
"low" => Severity::Suggestion,
_ => Severity::Info,
}
}
/// Parse a panic-attack location string ("src/lib.rs:42") into (PathBuf, Option<usize>).
fn parse_location(location: &str) -> (PathBuf, Option<usize>) {
// Format: "path/to/file.rs:line" or just "path/to/file.rs"
if let Some(colon_pos) = location.rfind(':') {
let (path_str, line_str) = location.split_at(colon_pos);
let line_str = &line_str[1..]; // skip the ':'
if let Ok(line) = line_str.parse::<usize>() {
return (PathBuf::from(path_str), Some(line));
}
}
(PathBuf::from(location), None)
}
/// Translate a single panic-attack WeakPoint into a fleet Finding.
///
/// Uses the category mapping table for fleet category, rule ID, triangle tier,
/// and confidence. If the category is unrecognised, produces a generic finding
/// with conservative defaults.
pub fn translate_weak_point(wp: &WeakPoint, config: &PanicbotConfig) -> Finding {
let mapping = category_mapping(&wp.category);
let (fleet_category, rule_id, rule_name, triangle_tier, default_confidence, fixability) =
match &mapping {
Some(m) => (
m.fleet_category,
m.rule_id,
m.rule_name,
m.triangle_tier,
m.default_confidence,
m.fixability,
),
None => {
tracing::warn!(
"Unknown WeakPoint category '{}', using conservative defaults",
wp.category
);
(
"static-analysis/unknown",
"PA000",
"Unknown static analysis finding",
TriangleTier::Control,
0.50,
Fixability::No,
)
}
};
// Apply confidence override from config if present
let confidence = config
.confidence_for(&wp.category)
.unwrap_or(default_confidence);
let severity = map_severity(&wp.severity);
let mut finding = Finding::new(BotId::Panicbot, rule_id, severity, &wp.description)
.with_rule_name(rule_name)
.with_category(fleet_category)
.with_triangle_tier(triangle_tier)
.with_confidence(confidence);
// Set fixable flag based on fixability classification
if matches!(fixability, Fixability::Yes) {
finding = finding.fixable();
}
// Parse and set location if present
if let Some(ref loc) = wp.location {
let (file, line) = parse_location(loc);
finding = finding.with_file(file);
if let Some(l) = line {
finding = finding.with_line(l);
}
}
// Add panic-attack category as metadata for traceability
finding = finding.with_metadata(serde_json::json!({
"panic_attack_category": wp.category,
"panic_attack_severity": wp.severity,
"recommended_attacks": wp.recommended_attack,
}));
finding
}
/// Translate all weak points from an AssailReport into a Vec of Findings.
///
/// Applies the configured minimum severity filter — findings below the
/// threshold are silently dropped.
pub fn translate_all(
weak_points: &[WeakPoint],
config: &PanicbotConfig,
) -> Vec<Finding> {
let min_threshold = config.min_severity.threshold();
weak_points
.iter()
.filter_map(|wp| {
// Skip weak points suppressed by panic-attack's context-aware FP engine.
// Suppressed = the logic engine found a defensive pattern (e.g. mutex guard,
// RAII, schema validation) that makes this finding likely a false positive.
//
// v2.5.5+ classifications (test_context field):
// * `"test_only"` / `"doc"` → typically also `suppressed: true`
// (set by `apply_v255_context_suppression` in panic-attack
// after the kanren rule pass). Defensive: even if a future
// scanner version preserves `suppressed: false` while
// classifying as TestOnly, drop the finding here so test code
// never reaches the fleet.
// * `"production"` → forwarded normally.
// * `None` → predates v2.5.5; treat as production.
if wp.suppressed {
return None;
}
if matches!(
wp.test_context.as_deref(),
Some("test_only") | Some("doc")
) {
return None;
}
// Apply severity filter
let severity_value = match wp.severity.to_lowercase().as_str() {
"low" => 0u8,
"medium" => 1,
"high" => 2,
"critical" => 3,
_ => 0,
};
if severity_value < min_threshold {
return None;
}
Some(translate_weak_point(wp, config))
})
.collect()
}
/// Classify findings into fixable and unfixable buckets.
///
/// Fixable findings are routed to the fleet pipeline for automated remediation.
/// Unfixable findings are written to the A2ML debt register.
pub fn classify_fixability(findings: &[Finding]) -> (Vec<&Finding>, Vec<&Finding>) {
let mut fixable = Vec::new();
let mut unfixable = Vec::new();
for finding in findings {
if finding.fixable {
fixable.push(finding);
} else {
unfixable.push(finding);
}
}
(fixable, unfixable)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_category_mapping_known() {
let m = category_mapping("UnsafeCode").unwrap();
assert_eq!(m.fleet_category, "static-analysis/unsafe-code");
assert_eq!(m.rule_id, "PA001");
assert_eq!(m.triangle_tier, TriangleTier::Control);
assert!((m.default_confidence - 0.70).abs() < f64::EPSILON);
assert_eq!(m.fixability, Fixability::No);
}
#[test]
fn test_category_mapping_unknown() {
assert!(category_mapping("SomethingNew").is_none());
}
#[test]
fn test_map_severity() {
assert_eq!(map_severity("Critical"), Severity::Error);
assert_eq!(map_severity("High"), Severity::Warning);
assert_eq!(map_severity("Medium"), Severity::Info);
assert_eq!(map_severity("Low"), Severity::Suggestion);
assert_eq!(map_severity("unknown"), Severity::Info);
}
#[test]
fn test_parse_location_with_line() {
let (path, line) = parse_location("src/lib.rs:42");
assert_eq!(path, PathBuf::from("src/lib.rs"));
assert_eq!(line, Some(42));
}
#[test]
fn test_parse_location_without_line() {
let (path, line) = parse_location("src/lib.rs");
assert_eq!(path, PathBuf::from("src/lib.rs"));
assert_eq!(line, None);
}
#[test]
fn test_parse_location_windows_path() {
// Ensure we handle paths with colons correctly (e.g., C:\foo)
let (path, line) = parse_location("C:\\src\\lib.rs:10");
assert_eq!(path, PathBuf::from("C:\\src\\lib.rs"));
assert_eq!(line, Some(10));
}
#[test]
fn test_translate_weak_point_known_category() {
let wp = WeakPoint {
category: "HardcodedSecret".to_string(),
location: Some("config.py:15".to_string()),
severity: "Critical".to_string(),
description: "AWS_SECRET_KEY found in source".to_string(),
recommended_attack: vec![],
suppressed: false,
test_context: None,
};
let config = PanicbotConfig::default();
let finding = translate_weak_point(&wp, &config);
assert_eq!(finding.source, BotId::Panicbot);
assert_eq!(finding.rule_id, "PA004");
assert_eq!(finding.category, "static-analysis/hardcoded-secret");
assert_eq!(finding.severity, Severity::Error);
assert!(finding.fixable);
assert_eq!(finding.triangle_tier, Some(TriangleTier::Eliminate));
assert!((finding.confidence.unwrap() - 0.88).abs() < f64::EPSILON);
assert_eq!(finding.file, Some(PathBuf::from("config.py")));
assert_eq!(finding.line, Some(15));
}
#[test]
fn test_translate_weak_point_unknown_category() {
let wp = WeakPoint {
category: "BrandNewCategory".to_string(),
location: None,
severity: "Medium".to_string(),
description: "Something new".to_string(),
recommended_attack: vec![],
suppressed: false,
test_context: None,
};
let config = PanicbotConfig::default();
let finding = translate_weak_point(&wp, &config);
assert_eq!(finding.rule_id, "PA000");
assert_eq!(finding.category, "static-analysis/unknown");
assert_eq!(finding.triangle_tier, Some(TriangleTier::Control));
assert!(!finding.fixable);
}
#[test]
fn test_translate_with_confidence_override() {
let wp = WeakPoint {
category: "UnsafeCode".to_string(),
location: Some("src/ffi.rs:10".to_string()),
severity: "High".to_string(),
description: "unsafe block".to_string(),
recommended_attack: vec![],
suppressed: false,
test_context: None,
};
let config = PanicbotConfig {
confidence_overrides: vec![crate::config::ConfidenceOverride {
category: "UnsafeCode".to_string(),
confidence: 0.55,
}],
..Default::default()
};
let finding = translate_weak_point(&wp, &config);
assert!((finding.confidence.unwrap() - 0.55).abs() < f64::EPSILON);
}
#[test]
fn test_translate_all_with_severity_filter() {
let weak_points = vec![
WeakPoint {
category: "UnsafeCode".to_string(),
location: None,
severity: "Low".to_string(),
description: "low severity".to_string(),
recommended_attack: vec![],
suppressed: false,
test_context: None,
},
WeakPoint {
category: "CommandInjection".to_string(),
location: None,
severity: "Critical".to_string(),
description: "critical severity".to_string(),
recommended_attack: vec![],
suppressed: false,
test_context: None,
},
];
let config = PanicbotConfig {
min_severity: crate::config::MinSeverity::High,
..Default::default()
};
let findings = translate_all(&weak_points, &config);
// Only the Critical finding should pass the High filter
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].rule_id, "PA003");
}
#[test]
fn test_classify_fixability() {
let config = PanicbotConfig::default();
let findings: Vec<Finding> = vec![
translate_weak_point(
&WeakPoint {
category: "HardcodedSecret".to_string(),
location: None,
severity: "High".to_string(),
description: "fixable".to_string(),
recommended_attack: vec![],
suppressed: false,
test_context: None,
},
&config,
),
translate_weak_point(
&WeakPoint {
category: "UnsafeCode".to_string(),
location: None,
severity: "High".to_string(),
description: "not fixable".to_string(),
recommended_attack: vec![],
suppressed: false,
test_context: None,
},
&config,
),
];
let (fixable, unfixable) = classify_fixability(&findings);
assert_eq!(fixable.len(), 1);
assert_eq!(unfixable.len(), 1);
assert_eq!(fixable[0].rule_id, "PA004"); // HardcodedSecret is fixable
assert_eq!(unfixable[0].rule_id, "PA001"); // UnsafeCode is not
}
#[test]
fn test_all_categories_have_unique_rule_ids() {
let categories = [
"UnsafeCode", "PanicPath", "CommandInjection", "HardcodedSecret",
"UnsafeDeserialization", "UncheckedError", "UnsafeFFI", "RaceCondition",
"ResourceLeak", "PathTraversal", "AtomExhaustion", "ExcessivePermissions",
"UnsafeTypeCoercion", "UncheckedAllocation", "UnboundedLoop", "BlockingIO",
"DeadlockPotential", "DynamicCodeExecution", "InsecureProtocol",
"InfiniteRecursion", "ProofDrift", "CryptoMisuse", "SupplyChain",
"InputBoundary", "MutationGap",
];
let mut rule_ids = std::collections::HashSet::new();
for cat in &categories {
let mapping = category_mapping(cat).unwrap_or_else(|| panic!("Missing mapping for {}", cat));
assert!(
rule_ids.insert(mapping.rule_id),
"Duplicate rule_id {} for category {}",
mapping.rule_id,
cat
);
}
assert_eq!(rule_ids.len(), 25);
}
// ─────────────────────────────────────────────────────────────────────
// v2.5.5 test_context tests
// ─────────────────────────────────────────────────────────────────────
fn make_wp(category: &str, test_context: Option<&str>, suppressed: bool) -> WeakPoint {
WeakPoint {
category: category.to_string(),
location: Some("src/foo.rs:1".to_string()),
severity: "Critical".to_string(),
description: "test".to_string(),
recommended_attack: vec![],
suppressed,
test_context: test_context.map(String::from),
}
}
#[test]
fn translate_all_drops_test_only_findings_even_if_not_suppressed() {
// Defensive: even when `suppressed: false`, a `test_context: test_only`
// finding should not reach the fleet.
let wps = vec![
make_wp("UnsafeCode", Some("test_only"), false),
make_wp("UnsafeCode", Some("production"), false),
];
let config = PanicbotConfig::default();
let findings = translate_all(&wps, &config);
assert_eq!(
findings.len(),
1,
"test_only finding must be dropped regardless of suppressed flag"
);
}
#[test]
fn translate_all_drops_doc_findings_even_if_not_suppressed() {
let wps = vec![
make_wp("PanicPath", Some("doc"), false),
make_wp("PanicPath", Some("production"), false),
];
let config = PanicbotConfig::default();
let findings = translate_all(&wps, &config);
assert_eq!(findings.len(), 1, "doc finding must be dropped");
}
#[test]
fn translate_all_keeps_production_test_context() {
let wps = vec![make_wp("UnsafeCode", Some("production"), false)];
let config = PanicbotConfig::default();
let findings = translate_all(&wps, &config);
assert_eq!(findings.len(), 1);
}
#[test]
fn translate_all_treats_none_test_context_as_production() {
// Pre-v2.5.5 panic-attack reports don't have the field; they should
// still be routed.
let wps = vec![make_wp("UnsafeCode", None, false)];
let config = PanicbotConfig::default();
let findings = translate_all(&wps, &config);
assert_eq!(findings.len(), 1);
}
#[test]
fn translate_all_respects_suppressed_independently() {
// `suppressed: true` should drop regardless of test_context.
let wps = vec![make_wp("UnsafeCode", Some("production"), true)];
let config = PanicbotConfig::default();
let findings = translate_all(&wps, &config);
assert_eq!(findings.len(), 0);
}
}