-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanalyzer.rs
More file actions
7766 lines (7110 loc) · 300 KB
/
Copy pathanalyzer.rs
File metadata and controls
7766 lines (7110 loc) · 300 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
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MPL-2.0
//! Core Assail analyzer implementation
//!
//! Language-specific static analysis for 40+ programming languages.
//! Detects weak points, unsafe patterns, and security anti-patterns
//! across BEAM, ML, Lisp, proof assistant, logic programming,
//! systems, functional, config, scripting, and custom DSL families.
use crate::types::*;
use anyhow::Result;
use regex::Regex;
use std::cell::RefCell;
use std::collections::{HashMap, HashSet};
use std::fs;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::OnceLock;
/// Upper bound on source-file reads during per-file scanning. Source
/// files are almost always well under 16 MiB; capping at 64 MiB bounds
/// a pathological/malicious input without losing realistic content.
const SOURCE_FILE_READ_LIMIT: u64 = 64 * 1024 * 1024;
/// Upper bound on manifest / config file reads (Cargo.toml, pyproject.toml,
/// flake.nix, deno.json, mix.exs, rebar.config, etc). Manifests are short
/// curated documents; 4 MiB is far beyond realistic sizes.
const MANIFEST_FILE_READ_LIMIT: u64 = 4 * 1024 * 1024;
/// Bounded replacement for `fs::read_to_string(path).ok()` — returns
/// `Some(content)` on success (up to `limit` bytes), `None` on I/O error
/// or if the file is absent. Used by the analyzer to cap every file read
/// against an explicit byte ceiling rather than trusting the filesystem.
fn read_bounded(path: &Path, limit: u64) -> Option<String> {
let mut buf = String::new();
fs::File::open(path)
.ok()?
.take(limit)
.read_to_string(&mut buf)
.ok()?;
Some(buf)
}
// ═══════════════════════════════════════════════════════════════════════
// UnboundedAllocation detector — word-boundary keyword matchers
// ═══════════════════════════════════════════════════════════════════════
//
// Historical context: the detector originally did substring matches like
// `code_only.contains("unbounded")`. This fires on any identifier
// containing those letters — including the detector's own variable names
// (`has_unbounded_allocations`, `unbounded_vec_patterns`) and normal
// tokio usage (`tokio::sync::mpsc::unbounded_channel`). On a self-scan,
// analyzer.rs was the last residual Critical after the `.take(LIMIT)`
// sweep closed the real unbounded reads.
//
// Fix: word-boundary regex matches. `\bunbounded\b` does NOT match
// `unbounded_channel` or `unbounded_vec_patterns` because `_` is a word
// character in regex, so the trailing `_` blocks the closing boundary.
// It DOES match bare `unbounded` (e.g., `fn unbounded()`, `type T = Unbounded;`),
// which is what we actually want the alarm for.
//
// The regexes are compiled once via OnceLock and reused across every
// file in a scan — per-call overhead is a single pointer read.
/// Match the unbounded-allocation alarm keywords as whole words only.
/// Keywords: unbounded, no_bound, no_limit, boundless, unlimited, unconstrained.
static UNBOUNDED_KEYWORDS_RE: OnceLock<Regex> = OnceLock::new();
/// Match `infinite` as a whole word (not part of `is_infinite`, `infinite_loop_v2`, etc.).
static INFINITE_WORD_RE: OnceLock<Regex> = OnceLock::new();
/// Match `recursion` as a whole word.
static RECURSION_WORD_RE: OnceLock<Regex> = OnceLock::new();
/// Match `limit` as a word prefix, case-insensitively, to disarm
/// read_to_* checks when the file has explicit bounds. Matches `limit`,
/// `Limit`, `LIMIT`, `READ_LIMIT`, `limit_bytes`, `limits`; does NOT match
/// `unlimited` or `sublimit` (those start inside a word).
static LIMIT_WORD_RE: OnceLock<Regex> = OnceLock::new();
fn has_unbounded_keyword(code: &str) -> bool {
UNBOUNDED_KEYWORDS_RE
.get_or_init(|| {
Regex::new(r"\b(unbounded|no_bound|no_limit|boundless|unlimited|unconstrained)\b")
.expect("static regex is valid")
})
.is_match(code)
}
fn has_infinite_word(code: &str) -> bool {
INFINITE_WORD_RE
.get_or_init(|| Regex::new(r"\binfinite\b").expect("static regex is valid"))
.is_match(code)
}
fn has_recursion_word(code: &str) -> bool {
RECURSION_WORD_RE
.get_or_init(|| Regex::new(r"\brecursion\b").expect("static regex is valid"))
.is_match(code)
}
fn has_limit_word(code: &str) -> bool {
LIMIT_WORD_RE
.get_or_init(|| Regex::new(r"(?i)\blimit").expect("static regex is valid"))
.is_match(code)
}
// Thread-local accumulators for migration analysis.
// These collect deprecated/modern API counts across all files during a single
// analyze() run, then get consumed by build_migration_metrics().
thread_local! {
static MIGRATION_DEPRECATED: RefCell<Vec<DeprecatedPattern>> = const { RefCell::new(Vec::new()) };
static MIGRATION_DEPRECATED_COUNT: RefCell<usize> = const { RefCell::new(0) };
static MIGRATION_MODERN_COUNT: RefCell<usize> = const { RefCell::new(0) };
static MIGRATION_FILE_COUNT: RefCell<usize> = const { RefCell::new(0) };
static MIGRATION_LINE_COUNT: RefCell<usize> = const { RefCell::new(0) };
}
/// Reset migration thread-local accumulators before a new scan
pub fn reset_migration_accumulators() {
MIGRATION_DEPRECATED.with(|cell| cell.borrow_mut().clear());
MIGRATION_DEPRECATED_COUNT.with(|cell| *cell.borrow_mut() = 0);
MIGRATION_MODERN_COUNT.with(|cell| *cell.borrow_mut() = 0);
MIGRATION_FILE_COUNT.with(|cell| *cell.borrow_mut() = 0);
MIGRATION_LINE_COUNT.with(|cell| *cell.borrow_mut() = 0);
}
/// Increment migration file/line counters (called per-file during scan)
pub fn record_migration_file(line_count: usize) {
MIGRATION_FILE_COUNT.with(|cell| *cell.borrow_mut() += 1);
MIGRATION_LINE_COUNT.with(|cell| *cell.borrow_mut() += line_count);
}
/// Build MigrationMetrics from accumulated thread-local data
pub fn build_migration_metrics(target: &Path) -> MigrationMetrics {
let deprecated_count = MIGRATION_DEPRECATED_COUNT.with(|cell| *cell.borrow());
let modern_count = MIGRATION_MODERN_COUNT.with(|cell| *cell.borrow());
let deprecated_patterns = MIGRATION_DEPRECATED.with(|cell| cell.borrow().clone());
let file_count = MIGRATION_FILE_COUNT.with(|cell| *cell.borrow());
let line_count = MIGRATION_LINE_COUNT.with(|cell| *cell.borrow());
let total = deprecated_count + modern_count;
let api_migration_ratio = if total > 0 {
modern_count as f64 / total as f64
} else {
1.0 // No API usage detected = fully migrated (or no code)
};
let config_format = Analyzer::detect_rescript_config(target);
// Read config for version detection
let config_path = if target.is_dir() {
if target.join("rescript.json").exists() {
Some(target.join("rescript.json"))
} else if target.join("bsconfig.json").exists() {
Some(target.join("bsconfig.json"))
} else {
None
}
} else {
let parent = target.parent().unwrap_or(target);
if parent.join("rescript.json").exists() {
Some(parent.join("rescript.json"))
} else if parent.join("bsconfig.json").exists() {
Some(parent.join("bsconfig.json"))
} else {
None
}
};
let config_content = config_path.and_then(|p| read_bounded(&p, MANIFEST_FILE_READ_LIMIT));
let version_bracket = Analyzer::detect_rescript_version(
config_format,
deprecated_count,
modern_count,
config_content.as_deref(),
);
// Detect JSX version, uncurried mode, module format from config
let (jsx_version, uncurried, module_format) = if let Some(ref content) = config_content {
let jsx = if content.contains("\"version\": 4") || content.contains("\"version\":4") {
Some(4u8)
} else if content.contains("\"version\": 3") || content.contains("\"version\":3") {
Some(3u8)
} else {
None
};
let uncurried = content.contains("\"uncurried\"");
let module = if content.contains("\"esmodule\"") {
Some("esmodule".to_string())
} else if content.contains("\"commonjs\"") {
Some("commonjs".to_string())
} else {
None
};
(jsx, uncurried, module)
} else {
(None, false, None)
};
// Health score: weighted combination of factors
let config_score = match config_format {
ReScriptConfigFormat::RescriptJson => 1.0,
ReScriptConfigFormat::Both => 0.5,
ReScriptConfigFormat::BsConfig => 0.0,
ReScriptConfigFormat::None => 0.5,
};
let jsx_score = match jsx_version {
Some(4) => 1.0,
Some(3) => 0.3,
_ => 0.5,
};
let uncurried_score = if uncurried { 1.0 } else { 0.3 };
let health_score = (api_migration_ratio * 0.5)
+ (config_score * 0.2)
+ (jsx_score * 0.15)
+ (uncurried_score * 0.15);
MigrationMetrics {
deprecated_api_count: deprecated_count,
modern_api_count: modern_count,
api_migration_ratio,
health_score: (health_score * 100.0).round() / 100.0,
config_format,
version_bracket,
build_time_ms: None,
bundle_size_bytes: None,
file_count,
rescript_lines: line_count,
deprecated_patterns,
jsx_version,
uncurried,
module_format,
}
}
/// Pre-compiled regexes for hot-path pattern matching.
/// Using OnceLock avoids recompiling on every file analyzed.
static RE_UNCHECKED_MALLOC: OnceLock<Regex> = OnceLock::new();
static RE_ELIXIR_APPLY: OnceLock<Regex> = OnceLock::new();
static RE_PONY_FFI: OnceLock<Regex> = OnceLock::new();
static RE_SHELL_UNQUOTED_VAR: OnceLock<Regex> = OnceLock::new();
static RE_HTTP_URL: OnceLock<Regex> = OnceLock::new();
static RE_HTTP_LOCALHOST: OnceLock<Regex> = OnceLock::new();
static RE_HTTP_JSONLD_IDENTIFIER: OnceLock<Regex> = OnceLock::new();
static RE_HARDCODED_SECRET: OnceLock<Regex> = OnceLock::new();
/// Match TODO/FIXME/HACK/XXX markers only when preceded by a
/// comment-starter on the same line. Excludes string-literal matches
/// like `.expect("TODO: handle error")` which were previously
/// inflating the UncheckedError count for every `.expect(...)` call
/// that mentioned TODO in its message (observed on 007-lang:
/// parser.rs has 155 `.expect("TODO: ...")` patterns, each of which
/// was being double-counted as both PanicPath (correct) and
/// UncheckedError (FP).
///
/// Comment-starters handled: `//` (Rust/C/JS/...), `/*` (block),
/// `#` (Python/Ruby/Shell/Nix/Elixir-preamble), `--` (Haskell/Ada/
/// SQL/Lua/Idris), `;;` (Lisp/Scheme/Racket), `%%` (Erlang/Matlab).
/// Does not handle OCaml `(* *)` or Forth `\` — edge cases for later.
static RE_TODO_COMMENT: OnceLock<Regex> = OnceLock::new();
pub struct Analyzer {
target: PathBuf,
language: Language,
verbose: bool,
browser_extension: bool,
}
impl Analyzer {
pub fn new(target: &Path) -> Result<Self> {
Self::build(target, false, false)
}
pub fn new_verbose(target: &Path) -> Result<Self> {
Self::build(target, true, false)
}
pub fn new_browser_extension(target: &Path) -> Result<Self> {
Self::build(target, false, true)
}
pub fn new_verbose_browser_extension(target: &Path) -> Result<Self> {
Self::build(target, true, true)
}
fn build(target: &Path, verbose: bool, browser_extension: bool) -> Result<Self> {
if !target.exists() {
anyhow::bail!("Target does not exist: {}", target.display());
}
let language = if target.is_file() {
Language::detect(target.to_str().unwrap_or(""))
} else {
Self::detect_directory_language(target)?
};
Ok(Self {
target: target.to_path_buf(),
language,
verbose,
browser_extension,
})
}
/// Run analysis with an optional evidence accumulator for attestation.
///
/// When `accumulator` is `Some`, each successfully read file and each
/// traversed directory are recorded into the accumulator for the
/// attestation chain. When `None`, this behaves identically to
/// [`analyze()`].
pub fn analyze_with_accumulator(
&self,
accumulator: Option<&mut crate::attestation::EvidenceAccumulator>,
) -> Result<AssailReport> {
self.analyze_inner(accumulator)
}
pub fn analyze(&self) -> Result<AssailReport> {
self.analyze_inner(None)
}
fn analyze_inner(
&self,
mut accumulator: Option<&mut crate::attestation::EvidenceAccumulator>,
) -> Result<AssailReport> {
// Reset migration accumulators for a clean scan
reset_migration_accumulators();
// Global aggregates are intentionally maintained alongside per-file analysis
// so output can support both campaign-level scoring and local triage.
let mut global_stats = ProgramStatistics {
total_lines: 0,
unsafe_blocks: 0,
panic_sites: 0,
unwrap_calls: 0,
safe_unwrap_calls: 0,
allocation_sites: 0,
io_operations: 0,
threading_constructs: 0,
};
let mut all_weak_points = Vec::new();
let mut file_statistics = Vec::new();
let files = self.collect_source_files()?;
let base = if self.target.is_dir() {
self.target.clone()
} else {
self.target.parent().unwrap_or(Path::new(".")).to_path_buf()
};
// Record traversed directories into the attestation accumulator
if let Some(ref mut acc) = accumulator {
let mut seen_dirs: HashSet<String> = HashSet::new();
for file in &files {
if let Some(parent) = file.parent() {
let dir_str = parent.to_string_lossy().to_string();
if seen_dirs.insert(dir_str.clone()) {
acc.record_directory(&dir_str);
}
}
}
}
// Each source file is analyzed independently; this keeps weak-point attribution precise.
for file in &files {
let raw_bytes = match fs::read(file) {
Ok(b) => b,
Err(e) => {
if self.verbose {
log::debug!("Skipping unreadable file: {} ({})", file.display(), e);
}
continue;
}
};
// Try UTF-8 first, then Latin-1 fallback.
// Use str::from_utf8 to borrow rather than cloning raw_bytes.
let content = match std::str::from_utf8(&raw_bytes) {
Ok(s) => s.to_owned(),
Err(_) => {
let (cow, _, had_errors) = encoding_rs::WINDOWS_1252.decode(&raw_bytes);
if had_errors {
if self.verbose {
log::debug!(
"Skipping non-text file: {} (neither UTF-8 nor Latin-1)",
file.display()
);
}
continue;
}
cow.into_owned()
}
};
let rel_path = file
.strip_prefix(&base)
.unwrap_or(file)
.to_string_lossy()
.to_string();
let mut file_stats = ProgramStatistics {
total_lines: 0,
unsafe_blocks: 0,
panic_sites: 0,
unwrap_calls: 0,
safe_unwrap_calls: 0,
allocation_sites: 0,
io_operations: 0,
threading_constructs: 0,
};
file_stats.total_lines = content.lines().count();
let mut file_weak_points = Vec::new();
// Dispatch to language-specific analyzer
let file_lang = Language::detect(file.to_str().unwrap_or(""));
// Record this file into the attestation accumulator (zero-cost when None)
if let Some(ref mut acc) = accumulator {
acc.record_file(&rel_path, &raw_bytes, &format!("{:?}", file_lang));
}
match file_lang {
Language::Rust => {
self.analyze_rust(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::C | Language::Cpp => {
self.analyze_c_cpp(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Go => {
self.analyze_go(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::Python => {
self.analyze_python(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::JavaScript => {
self.analyze_javascript(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Ruby => {
self.analyze_ruby(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
// BEAM family
Language::Elixir => {
self.analyze_elixir(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Erlang => {
self.analyze_erlang(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Gleam => {
self.analyze_gleam(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
// ML family
Language::ReScript => {
record_migration_file(file_stats.total_lines);
self.analyze_rescript(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::OCaml => {
self.analyze_ocaml(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::StandardML => {
self.analyze_sml(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
// Lisp family
Language::Scheme | Language::Racket => {
self.analyze_lisp(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
// Functional
Language::Haskell => {
self.analyze_haskell(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::PureScript => {
self.analyze_purescript(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
// Proof assistants
Language::Idris => {
self.analyze_idris(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Lean => {
self.analyze_lean(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::Agda => {
self.analyze_agda(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::Isabelle => {
self.analyze_isabelle(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Coq => {
self.analyze_coq(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
// Logic programming
Language::Prolog | Language::Logtalk | Language::Datalog => {
self.analyze_logic(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
// Systems languages
Language::Zig => {
self.analyze_zig(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::Ada => {
self.analyze_ada(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::Odin => {
self.analyze_odin(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::Nim => {
self.analyze_nim(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::Pony => {
self.analyze_pony(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
Language::DLang => {
self.analyze_dlang(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
// Config languages
Language::Nickel | Language::Nix => {
self.analyze_config(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
// Scripting
Language::Shell => {
self.analyze_shell(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Julia => {
self.analyze_julia(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Lua => {
self.analyze_lua(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
// Nextgen DSLs - shared analyzer
Language::WokeLang
| Language::Eclexia
| Language::MyLang
| Language::JuliaTheViper
| Language::Oblibeny
| Language::Anvomidav
| Language::AffineScript
| Language::Ephapax
| Language::BetLang
| Language::ErrorLang
| Language::VCL
| Language::FBQL => {
self.analyze_nextgen_dsl(
&content,
&mut file_stats,
&mut file_weak_points,
&rel_path,
)?;
}
Language::Java => {
self.analyze_java(&content, &mut file_stats, &mut file_weak_points, &rel_path)?;
}
_ => {
self.analyze_generic(&content, &mut file_stats, &rel_path)?;
}
}
// Cross-language security checks (run on all files)
self.analyze_cross_language(&content, &mut file_weak_points, &rel_path)?;
// Accumulate global stats
global_stats.total_lines += file_stats.total_lines;
global_stats.unsafe_blocks += file_stats.unsafe_blocks;
global_stats.panic_sites += file_stats.panic_sites;
global_stats.unwrap_calls += file_stats.unwrap_calls;
global_stats.allocation_sites += file_stats.allocation_sites;
global_stats.io_operations += file_stats.io_operations;
global_stats.threading_constructs += file_stats.threading_constructs;
all_weak_points.extend(file_weak_points);
let has_findings = file_stats.unsafe_blocks > 0
|| file_stats.panic_sites > 0
|| file_stats.unwrap_calls > 0
|| file_stats.allocation_sites > 0
|| file_stats.io_operations > 0
|| file_stats.threading_constructs > 0;
// Rust-only structural signal: is this an FFI safe-wrapper
// around an `extern "C"` boundary? Computed once per file
// here because the per-language analyzers don't have the
// FileStatistics container in scope. See
// `is_rust_ffi_safe_wrapper` for the four detection criteria.
let ffi_safe_wrapper =
matches!(file_lang, Language::Rust) && Self::is_rust_ffi_safe_wrapper(&content);
if has_findings {
file_statistics.push(FileStatistics {
file_path: rel_path,
lines: file_stats.total_lines,
unsafe_blocks: file_stats.unsafe_blocks,
panic_sites: file_stats.panic_sites,
unwrap_calls: file_stats.unwrap_calls,
safe_unwrap_calls: file_stats.safe_unwrap_calls,
allocation_sites: file_stats.allocation_sites,
io_operations: file_stats.io_operations,
threading_constructs: file_stats.threading_constructs,
ffi_safe_wrapper,
});
}
}
// Project-level supply-chain integrity checks (manifest/lockfile checks).
self.analyze_supply_chain_manifests(&mut all_weak_points)?;
// Project-level mutation coverage gap checks (tooling presence, not coverage %).
self.analyze_mutation_gaps(&mut all_weak_points)?;
// Secondary synthesis stages derive framework hints and relational overlays.
let frameworks = self.detect_frameworks(&files)?;
let recommended_attacks = self.generate_recommendations(&all_weak_points, &global_stats);
let dependency_graph = Self::build_dependency_graph(&file_statistics, &frameworks);
let taint_matrix = Self::build_taint_matrix(&all_weak_points, &frameworks);
// Build migration metrics for ReScript projects
let migration_metrics = if self.language == Language::ReScript {
Some(build_migration_metrics(&self.target))
} else {
None
};
// Post-process weak points to populate file/line fields from location
// strings, ensuring GitHub Actions annotations and gitbot-fleet fix scripts
// can access structured file paths.
let all_weak_points: Vec<_> = all_weak_points
.into_iter()
.map(|wp| wp.with_parsed_location())
.collect();
let mut report = AssailReport {
schema_version: "2.5".to_string(),
program_path: self.target.clone(),
language: self.language,
frameworks,
weak_points: all_weak_points,
statistics: global_stats,
file_statistics,
recommended_attacks,
dependency_graph,
taint_matrix,
migration_metrics,
suppressed_count: 0,
};
// Apply context-aware FP suppression rules.
// Marks WeakPoints with suppressed=true where defensive patterns
// make the finding likely a false positive.
super::apply_suppression(&mut report);
// Apply user classifications from a project-local registry
// (`<target>/audits/assail-classifications.a2ml` or
// `<target>/.panic-attack-classifications.a2ml`). Entries in the
// registry flip matching findings to `suppressed = true` after
// the structural suppression pass, letting repositories record
// audited residuals alongside their source audit documents.
super::apply_user_classifications(&mut report, &base);
Ok(report)
}
fn collect_source_files(&self) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
if self.target.is_file() {
files.push(self.target.clone());
} else {
// Directory mode performs a conservative recursive walk with language filtering.
self.walk_directory(&self.target, &mut files)?;
}
Ok(files)
}
fn walk_directory(&self, dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
// Skip build artifacts, hidden dirs, dependency dirs, and
// generated runtime artifacts (e.g. amuck mutation runs).
if ![
"target",
"build",
"node_modules",
".git",
"vendor",
"_build",
"_opam",
".stack-work",
"dist-newstyle",
"deps",
"_deps",
"zig-cache",
".zig-cache",
"zig-out",
".elixir_ls",
".lexical",
"__pycache__",
"ebin",
"_checkouts",
".fetch",
".hex",
".nimble",
".dub",
"obj",
"runtime",
]
.contains(&name)
{
self.walk_directory(&path, files)?;
}
} else if path.is_file() {
let lang = Language::detect(path.to_str().unwrap_or(""));
if lang != Language::Unknown {
files.push(path);
}
}
}
Ok(())
}
fn detect_directory_language(dir: &Path) -> Result<Language> {
let mut counts = std::collections::HashMap::new();
// Cap recursion depth for responsiveness on very large trees.
Self::count_languages_recursive(dir, &mut counts, 0)?;
counts.remove(&Language::Unknown);
counts
.into_iter()
.max_by_key(|(_, count)| *count)
.map(|(lang, _)| lang)
.ok_or_else(|| anyhow::anyhow!("Could not detect language"))
}
fn count_languages_recursive(
dir: &Path,
counts: &mut std::collections::HashMap<Language, usize>,
depth: usize,
) -> Result<()> {
if depth > 10 {
return Ok(());
}
for entry in fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
let name = entry.file_name();
let name_str = name.to_str().unwrap_or("");
if path.is_dir() {
if name_str.starts_with('.')
|| [
"target",
"node_modules",
"vendor",
"build",
"_build",
"_opam",
".stack-work",
"dist-newstyle",
"deps",
"zig-cache",
".zig-cache",
"zig-out",
"ebin",
"external_corpora",
"third_party",
"testdata",
"test_fixtures",
"fixtures",
"corpus",
"corpora",
"runtime",
]
.contains(&name_str)
{
continue;
}
Self::count_languages_recursive(&path, counts, depth + 1)?;
} else if path.is_file() {
let lang = Language::detect(path.to_str().unwrap_or(""));
*counts.entry(lang).or_insert(0) += 1;
}
}
Ok(())
}
// ============================================================
// Original language analyzers
// ============================================================
fn analyze_rust(
&self,
content: &str,
stats: &mut ProgramStatistics,
weak_points: &mut Vec<WeakPoint>,
file_path: &str,
) -> Result<()> {
// Detect if this is a test file - Expanded patterns
let is_test_file = file_path.contains("_tests.")
|| file_path.contains("/tests/")
|| file_path.ends_with("_test.rs")
|| file_path.starts_with("tests/")
|| file_path.contains("/test_")
|| file_path.contains("_spec.") // RSpec, Jest patterns
|| file_path.contains("_bench.") // Benchmark files
|| file_path.contains("/benches/") // Rust bench directory
|| file_path.ends_with("_bench.rs")
|| file_path.contains("__tests__/") // JavaScript
|| file_path.contains("/__tests__/")
|| file_path.ends_with(".test.") // Generic test files
|| file_path.ends_with(".spec.")
|| file_path.contains("_integration.") // Integration tests
|| file_path.contains("_e2e.") // End-to-end tests
|| file_path.contains("_unit.") // Unit tests
|| file_path.contains("/examples/") // Example code (often test-like)
|| file_path.contains("/samples/") // Sample code
|| file_path.contains("_mock.") // Mock files
|| file_path.contains("_stub."); // Stub files
// Strip string literal contents AND comments before counting so that
// detection-tool source files (which embed patterns as string literals)
// do not trigger their own rules, and so that rule names quoted in
// `// ...` or `/* ... */` doc comments — meta-tests, audit prose,
// architectural headers — do not falsely fire. See
// `007-lang/audits/audit-ffi-unsafe.md` §3 for the motivating case
// (a meta-test whose stated purpose is "the absence of `unsafe` in
// this file IS the assertion" was flagged as containing 1 unsafe
// block because comments discussed the word "unsafe").
//
// Stats that measure code structure rather than dangerous patterns
// (allocation sites, I/O, threading) still use the raw content
// because those patterns are safe to count in any context.
let without_strings = Self::strip_string_literals_rs(content);
let without_comments = strip_proof_comments(&without_strings, "//", Some(("/*", "*/")));
// Apply inline-test-mod stripping globally so `#[cfg(test)] mod
// tests { … }` is treated as test context by every substring-based
// dangerous-pattern check below — the Rust analogue of Zig's
// `count_unsafe_in_test_blocks`. See
// `Analyzer::strip_cfg_test_modules_rs` doc-comment for the
// recognised attribute forms. Previously scoped only to the
// unbounded-allocation check; widened 2026-04-17 after the same
// FP class was projected to affect unsafe / panic / unwrap /
// crypto counts too (a `#[test] fn exercises_unsafe_wrapper()`
// inside a production file would otherwise count toward that
// file's unsafe-block total).
let code_only = Self::strip_cfg_test_modules_rs(&without_comments);
stats.unsafe_blocks += code_only.matches("unsafe {").count();
stats.unsafe_blocks += code_only.matches("unsafe fn").count();
// Count panic sites, but suppress them in test files
let panic_sites =
code_only.matches("panic!(").count() + code_only.matches("unreachable!(").count();
// Unsafe unwrap: .unwrap() and .expect( — both can panic. Counted toward PA006.
// Safe unwrap: .unwrap_or(, .unwrap_or_default(), .unwrap_or_else( — fallback, never panic.
// Subtract safe variants from the raw .unwrap() count so ".unwrap_or(" isn't
// double-counted (it contains ".unwrap(").
let raw_unwrap = code_only.matches(".unwrap()").count();
let safe_unwrap = code_only.matches(".unwrap_or(").count()
+ code_only.matches(".unwrap_or_default()").count()
+ code_only.matches(".unwrap_or_else(").count();
let unwrap_calls = raw_unwrap + code_only.matches(".expect(").count();
let safe_unwrap_calls = safe_unwrap;
// Apply test file suppression. In test files, normal
// assert-macro use pushes panic/unwrap counts high with no
// production-code signal, so we suppress the counts unless they
// exceed a "clearly excessive" threshold — only the delta above
// the threshold is attributed to the file's statistics.
//
// Panic and unwrap thresholds are evaluated independently: a
// test file with 30 panics + 5 unwraps should report 10 panics
// (30 − 20) and 0 unwraps, not suppress everything because the
// unwrap count is normal. The previous version declared both
// thresholds but only compared panics, silently dropping any
// excessive unwrap signal.
let (effective_panic_sites, effective_unwrap_calls) = if is_test_file {
let panic_threshold = 20;
let unwrap_threshold = 10;
let eff_panics = panic_sites.saturating_sub(panic_threshold);
let eff_unwraps = unwrap_calls.saturating_sub(unwrap_threshold);
(eff_panics, eff_unwraps)
} else {
(panic_sites, unwrap_calls) // Production code: count all
};
stats.panic_sites += effective_panic_sites;
stats.unwrap_calls += effective_unwrap_calls;
stats.safe_unwrap_calls += safe_unwrap_calls;
// Enhanced allocation analysis - detect unbounded allocation patterns
let vec_new_count = content.matches("Vec::new()").count();
let box_new_count = content.matches("Box::new(").count();
let string_new_count = content.matches("String::new()").count();
// Count allocations; unbounded-pattern *classification* (tiny
// with_capacity, unlimited-read keywords, etc.) happens in the
// `has_unbounded_allocations` block below — not as a per-site
// counter. The previous `unbounded_*_patterns` locals duplicated
// the count without feeding into any finding and have been
// removed to clear dead-code warnings.
stats.allocation_sites += vec_new_count + box_new_count + string_new_count;
// Flag unbounded allocation patterns as high-risk. `code_only`
// already has string literals, comments, and `#[cfg(test)] mod
// tests` bodies stripped, so keyword substring checks below do
// not fire on doc comments, generated source strings, or
// test-mod identifiers.
//
// The earlier version also paired bare `for` / `while let` /
// `loop` tokens with `push(` or `Vec::new` as standalone