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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
//! JWT Weak Algorithm Detector
//!
//! Graph-enhanced detection of JWT security issues:
//! - Detect algorithm 'none' attacks
//! - Warn about symmetric algorithms (HS256) when asymmetric needed
//! - Check for algorithm confusion vulnerabilities
//! - Use graph to trace JWT handling through auth flows
//!
//! # False-positive guard at the legacy (non-dual-branch) entry point
//!
//! The legacy line-regex pass below uses three pattern probes
//! (`NONE_ALG`, `HS256_ALG`, `ALG_PARAM`) to short-list lines that look
//! JWT-vuln-shaped. `ALG_PARAM` matches `verify\s*=\s*False` because
//! disabling verification on a JWT call is a critical bug — but the
//! same pattern matches non-JWT TLS calls such as
//! `requests.get(url, verify=False)` or `httpx.get(url, verify=False)`.
//! Without an additional JWT-context gate, those lines became false
//! `VerificationDisabled` JWT findings (audit reproduction:
//! `vulnerable_app/app.py:33` in the post-v0.7.0 QA pass — the
//! `InsecureTlsDetector` already flags this correctly).
//!
//! The fix is `JWT_API_CALL` below: a single positive-context gate
//! applied before `analyze_vulnerability` so a line that does not
//! mention a JWT API surface (`jwt.decode`, `jose.jwt`, `pyjwt`,
//! `verify_jwt`, `verifyToken`, `JWTVerifier`) cannot be misclassified
//! as a JWT vuln by the line scanner. The dual-branch Python path
//! (`scan_python_file_dual_branch`) is AST-driven and never hit this
//! FP class.
// Phase 2g dual-branch submodules. Wired through `detect()` below
// when the `jwt-weak` dual-branch flag is on for `.py` files.
mod annotation;
mod evidence;
mod predict;
use crate::detectors::base::{Detector, DetectorConfig};
use crate::graph::GraphQueryExt;
use crate::models::{deterministic_finding_id, Finding, Severity};
use anyhow::Result;
use regex::Regex;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use tracing::info;
static NONE_ALG: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"(?i)(algorithm\s*[=:]\s*["']?none["']?|alg["']?\s*:\s*["']?none)"#)
.expect("valid regex")
});
static HS256_ALG: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r#"(?i)(algorithm\s*[=:]\s*["']?HS256["']?|alg["']?\s*:\s*["']?HS256)"#)
.expect("valid regex")
});
/// JWT-API-surface call-site gate.
///
/// Matches the call expressions / library symbols that mean "this
/// line is a JWT-decoding/encoding/verifying call." Every legacy
/// scanner finding now requires this to match the same line — without
/// this gate, `requests.get(url, verify=False)` looks identical to a
/// disabled-JWT-signature-verification call to the `verify=False`
/// pattern probe.
///
/// Includes:
/// - `jwt.decode` / `jwt.encode` / `jwt.verify` (PyJWT, node jsonwebtoken)
/// - `jose.*`, `jose.jwt.*` (python-jose, node jose)
/// - `pyjwt.*` (occasionally aliased)
/// - `verify_jwt`, `verifyToken`, `JWTVerifier` (common helper names)
/// - `authlib.jose.*`
///
/// Bare `jwt` substrings in identifiers (e.g. `jwt_secret`) are
/// intentionally NOT matched: the `\.` / `(` boundary forces an API
/// shape.
static JWT_API_CALL: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?i)(\bjwt\s*\.\s*(?:decode|encode|verify|sign)\b|\bjose\s*\.|\bpyjwt\s*\.|\bauthlib\s*\.\s*jose\b|\bverify_jwt\s*\(|\bverifyToken\s*\(|\bJWTVerifier\b)",
)
.expect("valid regex")
});
static ALG_PARAM: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)(algorithms?\s*[=:]\s*\[|verify\s*=\s*False|options.*verify)")
.expect("valid regex")
});
pub struct JwtWeakDetector {
#[allow(dead_code)] // Part of detector pattern, used for file scanning
repository_path: PathBuf,
max_findings: usize,
}
impl JwtWeakDetector {
crate::detectors::detector_new!(50);
/// Phase 2g dual-branch scan path (Python only).
///
/// Parses the file once, collects every JWT decode/verify call
/// site via [`evidence::collect_python_jwt_sites`], extracts
/// evidence, runs [`predict::predict`], and builds a dual-branch
/// finding per site. Replaces the legacy line-regex pass for
/// `.py` files when the `jwt-weak` dual-branch flag is on.
///
/// Returns an empty vec when the file has no JWT-library imports
/// (fast path in the collector) or fails to parse. Honors
/// `# repotoire: ignore` suppressions on the call line, mirroring
/// the legacy scanner.
fn scan_python_file_dual_branch(&self, path: &Path, content: &str) -> Vec<Finding> {
if content.contains('\0') {
return Vec::new();
}
let Some(tree) = crate::detectors::ast_fingerprint::parse_root_ext(
content,
crate::parsers::lightweight::Language::Python,
"py",
) else {
return Vec::new();
};
let root = tree.root_node();
let source = content.as_bytes();
let lines: Vec<&str> = content.lines().collect();
let mut findings = Vec::new();
for site in evidence::collect_python_jwt_sites(root, source) {
let line_idx = site.call_node.start_position().row;
// Honor `# repotoire: ignore` / inline suppressions same
// as the legacy path. Without this, users who suppressed
// a legacy finding would see a new dual-branch finding
// appear when they flip the flag on — a regression.
if let Some(line) = lines.get(line_idx) {
let prev = if line_idx > 0 {
Some(lines[line_idx - 1])
} else {
None
};
if crate::detectors::is_line_suppressed(line, prev) {
continue;
}
}
let snippet = lines.get(line_idx).map(|s| s.trim()).unwrap_or("");
let line_num = (line_idx + 1) as u32;
findings.push(self.build_dual_branch_jwt_finding(
path,
line_num,
site.api,
snippet,
site.call_node,
root,
source,
&lines,
));
}
findings
}
/// Build a dual-branch [`Finding`] for a single Python JWT call.
///
/// Mirrors `ssrf::build_dual_branch_ssrf_finding` (Phase 2f):
/// pull evidence, run the predictor, pick a
/// title/description/fix per predicted branch label, attach the
/// alternative branch + every prediction reason + every
/// resolution signal. The result is a single `Finding` with the
/// dual-branch shape that `--show-alternatives` knows how to
/// render.
#[allow(clippy::too_many_arguments)]
fn build_dual_branch_jwt_finding(
&self,
path: &Path,
line_num: u32,
api: predict::JwtApi,
snippet: &str,
call_node: tree_sitter::Node<'_>,
module_root: tree_sitter::Node<'_>,
source: &[u8],
lines: &[&str],
) -> Finding {
let api_label = api.callee_label();
let path_str = path.to_string_lossy().to_string();
let ev = evidence::extract_python_evidence(
call_node,
module_root,
source,
lines,
Some(path_str),
);
let prediction = predict::predict(&ev);
let predicted_label = prediction.predicted;
let predicted_severity = prediction.predicted_severity;
let predicted_title = match predicted_label {
crate::dual_branch::BranchLabel::RealBug => {
format!("Potential JWT weakness via {api_label}")
}
crate::dual_branch::BranchLabel::Benign => {
format!("Hardened JWT decode via {api_label} (informational)")
}
};
let predicted_description = format!(
"**JWT Weakness (dual-branch, CWE-327)**\n\n\
**API**: `{}`\n\n\
**Location**: {}:{}\n\n\
**Code**:\n```python\n{}\n```\n\n\
{}",
api_label,
path.display(),
line_num,
snippet,
match predicted_label {
crate::dual_branch::BranchLabel::RealBug => format!(
"The `{api_label}` call site shows evidence of unsafe \
JWT verification — e.g. `algorithm='none'`, an \
omitted `algorithms=` allowlist, `verify=False`, or \
HS256 used with a public-key-named argument. The \
predictor leans RealBug for this call site (see \
`prediction_reasons`); the alternative Benign \
interpretation is carried in `alternative_branch`."
),
crate::dual_branch::BranchLabel::Benign => format!(
"The `{api_label}` call site uses an explicit \
`algorithms=` allowlist (typically with an \
asymmetric algorithm), does not pass `verify=False`, \
and does not show other JWT-weakness signals. The \
predictor leans Benign (see `prediction_reasons`); \
the original RealBug interpretation is preserved in \
`alternative_branch`."
),
},
);
let predicted_fix = match predicted_label {
crate::dual_branch::BranchLabel::RealBug => Some(
"Always pass an explicit `algorithms=[...]` allowlist of \
asymmetric algorithms (RS256, ES256, EdDSA) to \
`jwt.decode` / `jose.jwt.decode` / `authlib.jose`. \
Never use `algorithm='none'` and never set \
`verify=False` outside test code. If HS256 is \
unavoidable, use a strong randomly-generated 32+ byte \
secret and ensure it is not also published as a public \
key.\n\n\
```python\n\
# Safe (asymmetric, explicit allowlist):\n\
jwt.decode(token, public_key, algorithms=['RS256'])\n\
```\n\n\
If this is a false positive (the call site IS safe via \
a path the v0 predictor doesn't see), annotate the call \
site with `# repotoire: jwt-safe[<reason>]` to collapse \
the finding to Info."
.to_string(),
),
crate::dual_branch::BranchLabel::Benign => Some(
"If this decode IS in an attacker-reachable auth flow \
(the alternative branch), verify that:\n\
• The `algorithms=` list never contains `'none'`.\n\
• The key argument matches the algorithm family \
(HS* with a long secret, RS*/ES*/EdDSA with the \
matching public key).\n\
• `verify_signature` is never `False` in `options=`.\n\n\
If the predictor is correct that this call is \
hardened, no action is needed."
.to_string(),
),
};
let mut finding = Finding {
id: String::new(),
detector: "JwtWeakDetector".to_string(),
severity: predicted_severity,
title: predicted_title,
description: predicted_description,
affected_files: vec![path.to_path_buf()],
line_start: Some(line_num),
line_end: Some(line_num),
suggested_fix: predicted_fix,
estimated_effort: Some("30 minutes".to_string()),
category: Some("security".to_string()),
cwe_id: Some("CWE-327".to_string()),
why_it_matters: Some(
"JWT vulnerabilities can allow attackers to forge authentication tokens, \
impersonate users, escalate privileges, or bypass authorization entirely."
.to_string(),
),
..Default::default()
};
finding = finding.with_alternative_branch(prediction.alternative_branch);
for reason in prediction.reasons {
finding = finding.with_prediction_reason(reason);
}
for resolution in prediction.resolutions {
finding = finding.with_resolution_signal(resolution);
}
finding
}
/// Analyze JWT vulnerability type
fn analyze_vulnerability(line: &str, context: &str) -> JwtVulnerability {
let lower = line.to_lowercase();
let ctx_lower = context.to_lowercase();
// Check for 'none' algorithm (CVE-2015-2951)
if lower.contains("none") && (lower.contains("algorithm") || lower.contains("alg")) {
return JwtVulnerability::NoneAlgorithm;
}
// Check for disabled verification
if lower.contains("verify") && (lower.contains("false") || lower.contains("skip")) {
return JwtVulnerability::VerificationDisabled;
}
// Check for algorithm confusion (accepting header alg)
if ctx_lower.contains("header") && ctx_lower.contains("alg") {
return JwtVulnerability::AlgorithmConfusion;
}
// Check for HS256 with public key (JWT confusion attack)
if lower.contains("hs256") {
if ctx_lower.contains("public") || ctx_lower.contains("rsa") {
return JwtVulnerability::KeyConfusion;
}
return JwtVulnerability::WeakSymmetric;
}
JwtVulnerability::Other
}
/// Check if function is in auth flow
fn is_auth_flow(func_name: &str, file_path: &str) -> bool {
let name_lower = func_name.to_lowercase();
let path_lower = file_path.to_lowercase();
name_lower.contains("auth")
|| name_lower.contains("login")
|| name_lower.contains("verify")
|| name_lower.contains("token")
|| name_lower.contains("session")
|| name_lower.contains("middleware")
|| path_lower.contains("auth")
|| path_lower.contains("security")
|| path_lower.contains("middleware")
}
}
#[derive(Debug, Clone)]
enum JwtVulnerability {
NoneAlgorithm, // Algorithm 'none' allows unsigned tokens
VerificationDisabled, // Verification explicitly disabled
AlgorithmConfusion, // Accepting algorithm from header
KeyConfusion, // HS256 with RSA public key
WeakSymmetric, // HS256 when asymmetric recommended
Other,
}
impl JwtVulnerability {
fn severity(&self) -> Severity {
match self {
JwtVulnerability::NoneAlgorithm => Severity::Critical,
JwtVulnerability::VerificationDisabled => Severity::Critical,
JwtVulnerability::AlgorithmConfusion => Severity::Critical,
JwtVulnerability::KeyConfusion => Severity::Critical,
JwtVulnerability::WeakSymmetric => Severity::Medium,
JwtVulnerability::Other => Severity::Low,
}
}
fn title(&self) -> &'static str {
match self {
JwtVulnerability::NoneAlgorithm => "JWT algorithm 'none' allows unsigned tokens",
JwtVulnerability::VerificationDisabled => "JWT verification is disabled",
JwtVulnerability::AlgorithmConfusion => "JWT algorithm confusion vulnerability",
JwtVulnerability::KeyConfusion => "JWT key confusion (HS256 with RSA key)",
JwtVulnerability::WeakSymmetric => "JWT using symmetric algorithm (HS256)",
JwtVulnerability::Other => "Potential JWT security issue",
}
}
fn description(&self) -> &'static str {
match self {
JwtVulnerability::NoneAlgorithm => {
"Using algorithm 'none' means tokens aren't signed. \
Any attacker can forge valid tokens."
}
JwtVulnerability::VerificationDisabled => {
"Signature verification is disabled. \
Tokens are accepted without validation."
}
JwtVulnerability::AlgorithmConfusion => {
"The algorithm is read from the token header instead of being enforced. \
Attackers can switch algorithms to bypass verification."
}
JwtVulnerability::KeyConfusion => {
"Using HS256 (symmetric) with an RSA public key allows attackers \
to sign tokens with the public key."
}
JwtVulnerability::WeakSymmetric => {
"HS256 uses a shared secret. If the secret is weak or leaked, \
attackers can forge tokens. Consider RS256/ES256."
}
JwtVulnerability::Other => "Potential JWT security concern detected.",
}
}
fn fix(&self) -> &'static str {
match self {
JwtVulnerability::NoneAlgorithm => {
"Never allow 'none' algorithm in production:\n\n\
```python\n\
# Python (PyJWT)\n\
jwt.decode(token, key, algorithms=['RS256']) # Explicit whitelist\n\
```\n\n\
```javascript\n\
// Node.js\n\
jwt.verify(token, publicKey, { algorithms: ['RS256'] });\n\
```"
}
JwtVulnerability::VerificationDisabled => {
"Always verify JWT signatures:\n\n\
```python\n\
# Never do this:\n\
# jwt.decode(token, options={'verify_signature': False})\n\
\n\
# Always verify:\n\
jwt.decode(token, key, algorithms=['RS256'])\n\
```"
}
JwtVulnerability::AlgorithmConfusion => {
"Always specify allowed algorithms explicitly:\n\n\
```python\n\
# Don't trust the token's 'alg' header\n\
jwt.decode(token, key, algorithms=['RS256']) # Whitelist\n\
```"
}
JwtVulnerability::KeyConfusion => {
"Use asymmetric algorithms (RS256/ES256) with proper key pairs:\n\n\
```python\n\
# Sign with private key\n\
jwt.encode(payload, private_key, algorithm='RS256')\n\
\n\
# Verify with public key\n\
jwt.decode(token, public_key, algorithms=['RS256'])\n\
```"
}
JwtVulnerability::WeakSymmetric => {
"Consider using asymmetric algorithms:\n\n\
```python\n\
# RS256 (RSA) or ES256 (ECDSA) recommended\n\
jwt.encode(payload, private_key, algorithm='RS256')\n\
\n\
# If using HS256, ensure secret is:\n\
# - At least 256 bits (32 bytes)\n\
# - Cryptographically random\n\
# - Never hardcoded\n\
```"
}
JwtVulnerability::Other => "Review JWT implementation for security best practices.",
}
}
}
impl Detector for JwtWeakDetector {
fn name(&self) -> &'static str {
"jwt-weak"
}
fn description(&self) -> &'static str {
"Detects weak JWT algorithms and configurations"
}
fn bypass_postprocessor(&self) -> bool {
true
}
fn file_extensions(&self) -> &'static [&'static str] {
&["py", "js", "ts", "jsx", "tsx", "rb", "java", "go"]
}
fn content_requirements(&self) -> crate::detectors::detector_context::ContentFlags {
crate::detectors::detector_context::ContentFlags::HAS_CRYPTO
}
fn detect(
&self,
ctx: &crate::detectors::analysis_context::AnalysisContext,
) -> Result<Vec<Finding>> {
let graph = ctx.graph;
let files = &ctx.as_file_provider();
let mut findings = vec![];
// Phase 2g dual-branch gate. When `true`, Python `.py` files
// go through the AST-driven predictor path
// (`scan_python_file_dual_branch`) and skip the legacy line
// scanner. Other languages and the flag-off path are
// unchanged. Symmetric with ssrf's `flag_on` (Phase 2f).
let flag_on = ctx.dual_branch.is_enabled_for("jwt-weak");
for path in files.files_with_extensions(&["py", "js", "ts", "java", "go", "rb", "php"]) {
if findings.len() >= self.max_findings {
break;
}
let path_str = path.to_string_lossy().to_string();
// Skip test files
if crate::detectors::base::is_test_path(&path_str) {
continue;
}
let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
// Phase 2g: AST-driven predictor path for Python when the
// dual-branch flag is on. Replaces the legacy regex pass
// for `.py` files; other languages and the flag-off path
// fall through to the regex scanner below.
if flag_on && ext == "py" {
if let Some(content) = files.content(path) {
let dual = self.scan_python_file_dual_branch(path, &content);
for finding in dual {
findings.push(finding);
if findings.len() >= self.max_findings {
break;
}
}
}
continue;
}
if let Some(content) = files.content(path) {
let lines: Vec<&str> = content.lines().collect();
for (i, line) in lines.iter().enumerate() {
let prev_line = if i > 0 { Some(lines[i - 1]) } else { None };
if crate::detectors::is_line_suppressed(line, prev_line) {
continue;
}
// Skip comments
let trimmed = line.trim();
if trimmed.starts_with("//") || trimmed.starts_with("#") {
continue;
}
// Check for JWT-related patterns
let has_none = NONE_ALG.is_match(line);
let has_hs256 = HS256_ALG.is_match(line);
let has_verify_issue = ALG_PARAM.is_match(line)
&& (line.to_lowercase().contains("false") || line.contains("none"));
if !has_none && !has_hs256 && !has_verify_issue {
continue;
}
// Get surrounding context
let start = i.saturating_sub(5);
let end = (i + 5).min(lines.len());
let context = lines[start..end].join(" ");
// JWT-context gate: a probe match alone is not enough.
// `ALG_PARAM` matches `verify=False`, which is also the
// standard way to disable TLS verification on
// `requests`/`httpx` (`InsecureTlsDetector`'s job). We
// require a JWT API call site (see `JWT_API_CALL`) on
// the same line OR within the ±5-line context window
// so multi-line `jwt.decode(...)` calls still match.
// `NONE_ALG` and `HS256_ALG` already encode "algorithm
// = none/HS256" which is unambiguously a JWT shape, so
// they are exempt from the gate.
if !has_none && !has_hs256 {
let has_jwt_context =
JWT_API_CALL.is_match(line) || JWT_API_CALL.is_match(&context);
if !has_jwt_context {
continue;
}
}
let vuln = Self::analyze_vulnerability(line, &context);
if matches!(vuln, JwtVulnerability::Other) {
continue;
}
let containing_func = graph.find_function_at(&path_str, (i + 1) as u32);
let containing_info = containing_func.as_ref().map(|f| {
let callers = graph
.get_callers(f.qn(crate::graph::interner::global_interner()))
.len();
(
f.node_name(crate::graph::interner::global_interner())
.to_string(),
callers,
)
});
let is_auth = containing_info
.as_ref()
.map(|(name, _)| Self::is_auth_flow(name, &path_str))
.unwrap_or(false);
// Build notes
let mut notes = Vec::new();
if let Some((func_name, callers)) = &containing_info {
notes.push(format!(
"📦 In function: `{}` ({} callers)",
func_name, callers
));
}
if is_auth {
notes.push("🔐 Part of authentication flow".to_string());
}
let context_notes = if notes.is_empty() {
String::new()
} else {
format!("\n\n**Context:**\n{}", notes.join("\n"))
};
findings.push(Finding {
id: String::new(),
detector: "JwtWeakDetector".to_string(),
severity: vuln.severity(),
title: vuln.title().to_string(),
description: format!("{}{}", vuln.description(), context_notes),
affected_files: vec![path.to_path_buf()],
line_start: Some((i + 1) as u32),
line_end: Some((i + 1) as u32),
suggested_fix: Some(vuln.fix().to_string()),
estimated_effort: Some("30 minutes".to_string()),
category: Some("security".to_string()),
cwe_id: Some("CWE-327".to_string()),
why_it_matters: Some(
"JWT vulnerabilities can allow attackers to forge authentication tokens, \
impersonate users, escalate privileges, or bypass authorization entirely.".to_string()
),
..Default::default()
});
}
}
}
info!(
"JwtWeakDetector found {} findings (graph-aware)",
findings.len()
);
Ok(findings)
}
}
impl crate::detectors::RegisteredDetector for JwtWeakDetector {
fn create(init: &crate::detectors::DetectorInit) -> std::sync::Arc<dyn Detector> {
std::sync::Arc::new(Self::new(init.repo_path))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graph::builder::GraphBuilder;
#[test]
fn test_detects_none_algorithm() {
let store = GraphBuilder::new().freeze();
let detector = JwtWeakDetector::new("/mock/repo");
let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
("auth.py", "import jwt\n\ndef decode_token(token):\n payload = jwt.decode(token, algorithm=\"none\")\n return payload\n"),
]);
let findings = detector.detect(&ctx).expect("detection should succeed");
assert!(!findings.is_empty(), "Should detect JWT algorithm='none'");
assert!(
findings.iter().any(|f| f.title.contains("none")),
"Finding should mention 'none' algorithm. Titles: {:?}",
findings.iter().map(|f| &f.title).collect::<Vec<_>>()
);
assert!(
findings.iter().any(|f| f.severity == Severity::Critical),
"JWT none algorithm should be Critical severity"
);
}
#[test]
fn test_no_finding_for_secure_jwt() {
let store = GraphBuilder::new().freeze();
let detector = JwtWeakDetector::new("/mock/repo");
let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(&store, vec![
("auth.py", "import jwt\n\ndef decode_token(token, public_key):\n payload = jwt.decode(token, public_key, algorithms=[\"RS256\"])\n return payload\n"),
]);
let findings = detector.detect(&ctx).expect("detection should succeed");
assert!(
findings.is_empty(),
"Secure JWT with RS256 should produce no findings, but got: {:?}",
findings.iter().map(|f| &f.title).collect::<Vec<_>>()
);
}
/// Regression: `requests.get(url, verify=False)` is a TLS-cert
/// validation bug owned by `InsecureTlsDetector`, not a JWT bug.
/// Before the `JWT_API_CALL` context gate, the legacy line scanner
/// matched `ALG_PARAM` (which contains `verify\s*=\s*False`),
/// then `analyze_vulnerability` returned `VerificationDisabled`,
/// and the line was emitted as a Critical
/// "JWT verification is disabled" finding. Reproduced in the
/// post-v0.7.0 QA audit on `vulnerable_app/app.py:33`.
///
/// The expected behavior is zero JWT findings on this file. We
/// intentionally include `requests` but no `jwt`/`jose`/`pyjwt`
/// API call anywhere in the file so the gate forces a skip.
#[test]
fn tls_verify_false_is_not_a_jwt_finding() {
let store = GraphBuilder::new().freeze();
let detector = JwtWeakDetector::new("/mock/repo");
let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
&store,
vec![(
"tls_call.py",
"import requests\n\
\n\
def fetch(url):\n\
\x20\x20\x20\x20resp = requests.get(url, verify=False)\n\
\x20\x20\x20\x20return resp.json()\n",
)],
);
let findings = detector.detect(&ctx).expect("detection should succeed");
assert!(
findings.is_empty(),
"TLS `verify=False` on a non-JWT call must not be flagged by JwtWeakDetector. Got: {:?}",
findings
.iter()
.map(|f| format!("L{:?}: {}", f.line_start, f.title))
.collect::<Vec<_>>()
);
}
/// Positive pin: when `verify=False` IS on a real JWT API call
/// (`jwt.decode(..., verify=False)`), the legacy scanner still
/// fires. Guards against the gate accidentally being too tight.
#[test]
fn jwt_decode_verify_false_still_flagged() {
let store = GraphBuilder::new().freeze();
let detector = JwtWeakDetector::new("/mock/repo");
let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
&store,
vec![(
"auth.py",
"import jwt\n\
\n\
def decode_token(token):\n\
\x20\x20\x20\x20return jwt.decode(token, verify=False)\n",
)],
);
let findings = detector.detect(&ctx).expect("detection should succeed");
assert!(
!findings.is_empty(),
"jwt.decode(..., verify=False) is the canonical JWT-verification-disabled bug and must still be flagged"
);
}
/// Multi-line `jwt.decode(...)` call where `verify=False` is on a
/// separate line from the `jwt.decode` token. The ±5-line context
/// window check in the gate must keep this finding.
#[test]
fn multiline_jwt_decode_verify_false_still_flagged() {
let store = GraphBuilder::new().freeze();
let detector = JwtWeakDetector::new("/mock/repo");
let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
&store,
vec![(
"auth.py",
"import jwt\n\
\n\
def decode_token(token):\n\
\x20\x20\x20\x20return jwt.decode(\n\
\x20\x20\x20\x20\x20\x20\x20\x20token,\n\
\x20\x20\x20\x20\x20\x20\x20\x20verify=False,\n\
\x20\x20\x20\x20)\n",
)],
);
let findings = detector.detect(&ctx).expect("detection should succeed");
assert!(
!findings.is_empty(),
"Multi-line jwt.decode with verify=False must still be flagged (context window gate)"
);
}
// ─────────────────────────────────────────────────────────────────
// Phase 2g dual-branch integration tests.
//
// Pinning the wire-up that `scan_python_file_dual_branch` plus
// `build_dual_branch_jwt_finding` produce the right shape end-to-
// end for the decisions-doc Cases A-E, plus the flag-off pin and
// the non-Python pin.
//
// Honest review note (2026-05-11): Phase 2g introduces the FIRST
// RealBug-direction Step 1.5 collapse in the dual-branch series.
// Where 2e (defusedxml) and 2f (advocate) collapse to **Benign**
// by virtue of safe-by-construction transports, 2g collapses to
// **RealBug / Critical** when `'none'` appears in the algorithm
// slot — because `algorithm='none'` is, by RFC 7518 §3.6, the
// cryptographically unsigned shape and there is no scope in
// which it can be safe. The asymmetry is principled, not a
// workaround: 2e/2f had a "transport that cannot fail" to
// collapse on; 2g has a "value that cannot succeed" to collapse
// on. Without this collapse, decisions-doc Case D (`'none'` in
// the algorithms list alongside HS256, with all the additive
// Benign signals firing) would compute to a Medium-Benign result
// — an obvious mis-rank. The D1 amendment encodes this in the
// predictor; the test `case_d_algorithms_list_with_none_realbug`
// below pins it end-to-end.
// ─────────────────────────────────────────────────────────────────
fn run_dual_branch(file: &str, content: &str) -> Vec<Finding> {
use crate::config::DualBranchConfig;
use std::collections::HashMap;
let store = GraphBuilder::new().freeze();
let detector = JwtWeakDetector::new("/mock/repo");
let mut detectors = HashMap::new();
detectors.insert("jwt-weak".to_string(), true);
let cfg = DualBranchConfig {
enabled: true,
detectors,
};
let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
&store,
vec![(file, content)],
)
.with_dual_branch(cfg);
detector.detect(&ctx).expect("detection should succeed")
}
#[test]
fn flag_off_jwt_emits_single_branch_unchanged() {
// Sanity: with flag off (default), Python JWT sites emit no
// `alternative_branch` and no predictor-contributed
// (weight ≠ 0) reasons. Pins the opt-in promise.
let store = GraphBuilder::new().freeze();
let detector = JwtWeakDetector::new("/mock/repo");
let ctx = crate::detectors::analysis_context::AnalysisContext::test_with_mock_files(
&store,
vec![(
"auth.py",
"import jwt\n\
def login_handler(token):\n\
\x20 return jwt.decode(token, algorithm='none')\n",
)],
);
let findings = detector.detect(&ctx).expect("detection should succeed");
assert!(!findings.is_empty(), "must still fire single-branch");
for f in &findings {
assert!(
f.alternative_branch.is_none(),
"no alternative_branch when flag off: {:?}",
f.title
);
assert!(
f.prediction_reasons.iter().all(|r| r.weight == 0.0),
"no weight-bearing predictor reasons when flag off; \
graph-enrichment weight-0 reasons are allowed. reasons: {:?}",
f.prediction_reasons
.iter()
.map(|r| (&r.kind, r.weight))
.collect::<Vec<_>>()
);
}
}
#[test]
fn case_a_flag_on_explicit_rs256_in_auth_handler_classifies_benign() {
// Decisions doc Case A: explicit `algorithms=['RS256']` in a
// login handler. algorithms+ (0.50) + asymmetric (0.10) +
// auth_flow (-0.20) = +0.40 → Benign / Info.
let findings = run_dual_branch(
"auth.py",
"import jwt\n\
def login_handler(token, key):\n\
\x20 return jwt.decode(token, key, algorithms=['RS256'])\n",
);
assert!(!findings.is_empty(), "must surface even when Benign");
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("must have a dual-branch finding");
assert_eq!(
f.severity,
Severity::Info,
"Case A predicted Benign → Info, got {:?}",
f.severity
);
let alt = f.alternative_branch.as_ref().unwrap();
assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
}
#[test]
fn case_b_flag_on_naked_decode_in_handler_classifies_realbug() {
// Decisions doc Case B: `jwt.decode(token, key)` with NO
// `algorithms=` kwarg in a handler. algorithms_omitted (-0.40)
// + auth_flow (-0.20) = -0.60 → High RealBug.
let findings = run_dual_branch(
"auth.py",
"import jwt\n\
def login_handler(token, key):\n\
\x20 return jwt.decode(token, key)\n",
);
assert!(!findings.is_empty());
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("must have a dual-branch finding");
assert!(
matches!(f.severity, Severity::High | Severity::Critical),
"Case B predicted RealBug; got {:?}",
f.severity
);
let alt = f.alternative_branch.as_ref().unwrap();
assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
}
#[test]
fn case_c_flag_on_algorithm_none_singular_collapses_to_critical() {
// Decisions doc Case C — D1 amendment trigger.
// `algorithm='none'` collapses to RealBug / Critical
// regardless of any Benign signals (the "value that cannot
// succeed" Step 1.5 collapse).
let findings = run_dual_branch(
"decode.py",
"import jwt\n\
def decode_token(token):\n\
\x20 return jwt.decode(token, 'supersecret', algorithm='none')\n",
);
assert!(!findings.is_empty());
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("must have a dual-branch finding");
assert_eq!(
f.severity,
Severity::Critical,
"D1 amendment: 'none' collapses to Critical regardless of other signals"
);
let alt = f.alternative_branch.as_ref().unwrap();
assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
}
#[test]
fn case_d_algorithms_list_with_none_realbug() {
// Decisions doc Case D — the case that motivates the D1
// amendment. `algorithms=['none', 'HS256']` inside a handler
// alongside +0.50 (algorithms= present) + +0.10 (verify=True)
// would compute Medium-Benign under pure additive scoring —
// but `'none'` in the list is, by RFC 7518, an unsafe value
// and must collapse to RealBug/Critical.
let findings = run_dual_branch(
"auth.py",
"import jwt\n\
def login_handler(token, key):\n\
\x20 return jwt.decode(token, key, algorithms=['none', 'HS256'], verify=True)\n",
);
assert!(!findings.is_empty());
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("must have a dual-branch finding");
assert_eq!(
f.severity,
Severity::Critical,
"D1 amendment: 'none' in algorithms list collapses to Critical"
);
let alt = f.alternative_branch.as_ref().unwrap();
assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
}
#[test]
fn case_e_hs256_with_public_key_classifies_realbug() {
// Decisions doc Case E: HS256 + public-key argument name →
// JWT key-confusion attack. algorithms+ (+0.50) +
// hs256_pubkey (-0.50) + no auth flow = 0.0 → tiebreak
// RealBug / Medium.
let findings = run_dual_branch(
"verify.py",
"import jwt\n\
def verify(token, public_key):\n\
\x20 return jwt.decode(token, public_key, algorithms=['HS256'])\n",
);
assert!(!findings.is_empty());
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("must have a dual-branch finding");
assert!(
matches!(
f.severity,
Severity::Medium | Severity::High | Severity::Critical
),
"Case E RealBug, got {:?}",
f.severity
);
}
#[test]
fn flag_on_jwt_safe_annotation_collapses_to_info() {
// The escape hatch (Step 1 hard collapse on user annotation).
// `# repotoire: jwt-safe[verified-at-edge]` on the line MUST
// collapse the finding to Info — even when the call is
// `algorithm='none'` (the D1 amendment trigger). Annotation
// is Step 1; the 'none' collapse is Step 1.5; Step 1 wins.
let findings = run_dual_branch(
"auth.py",
"import jwt\n\
def login_handler(token):\n\
\x20 return jwt.decode(token, key, algorithm='none') # repotoire: jwt-safe[verified-at-edge]\n",
);
assert!(!findings.is_empty(), "annotation still surfaces a finding");
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("must have a dual-branch finding");
assert_eq!(
f.severity,
Severity::Info,
"jwt-safe annotation collapses to Info even over 'none' collapse"
);
}
#[test]
fn flag_on_non_python_unchanged() {
// D4: per-language scope. The dual-branch predictor is
// Python-only in v0. JS JWT still flows through the legacy
// regex scanner — no `alternative_branch`.
let findings = run_dual_branch(
"auth.js",
"const jwt = require('jsonwebtoken');\n\
function login(token) {\n\
\x20 return jwt.verify(token, 'k', { algorithm: 'none' });\n\
}\n",
);
// We don't assert non-empty here because the legacy scanner
// may or may not flag JS; the contract is that IF it does,
// there's no alternative_branch.
for f in &findings {
assert!(
f.alternative_branch.is_none(),
"JS JWT must not have alternative_branch in v0; \
got finding: {:?}",
f.title
);
}
}
// ─────────────────────────────────────────────────────────────────
// Phase 2g real-world signature tests.
//
// Pinning the predictor's behavior on minimized but recognizable
// shapes from real Python JWT codebases / CVEs. Mirrors the
// 2e (XXE) and 2f (SSRF) real-world tests: catch the day when an
// evidence-extractor refactor accidentally breaks a known-correct
// verdict on a real-world idiom.
//
// Three signatures pinned:
//
// 1. `real_cve_2015_2951_algorithm_none_pattern` — the textbook
// CVE: PyJWT pre-1.0.0 accepted `algorithm='none'` from the
// token header, allowing unsigned-token forgery. The
// remediated codebase that still uses `algorithm='none'` in
// a misguided "we already verified" comment must classify
// Critical RealBug via the D1 Step 1.5 collapse.
// 2. `real_pyjwt_recommended_rs256_pattern` — the PyJWT docs
// recommended usage (`jwt.decode(token, pub, algorithms=
// ['RS256'])`). Production auth handlers across Django/Flask
// codebases match this shape. Must classify Benign/Info.
// 3. `real_jwt_key_confusion_cve_2016_10555_pattern` — the
// auth0/node-jsonwebtoken key-confusion attack ported to
// Python (PyJWT had the same shape pre-1.5): HS256
// verification with an RSA public key, allowing forgery via
// HMAC-of-public-key. Must classify RealBug.
//
// The shapes are simplified to fit a single-file mock context.
// The minimization is documented inline so a future contributor
// can re-validate against upstream when the API drifts.
// ─────────────────────────────────────────────────────────────────
#[test]
fn real_cve_2015_2951_algorithm_none_pattern() {
// CVE-2015-2951 (PyJWT). Pre-1.0.0, `jwt.decode(token,
// verify=False)` AND `jwt.decode(token, algorithm='none')`
// both accepted unsigned tokens. The textbook "I'll verify
// it myself, trust me bro" anti-pattern from that era still
// appears in CTF writeups and pre-2016 codebases:
//
// import jwt
// def get_user_from_token(token):
// # "we already verified upstream, just decode"
// payload = jwt.decode(token, algorithm='none')
// return User.objects.get(id=payload['sub'])
//
// Real-world appearance: pre-1.0.0 PyJWT consumers, some
// OAuth-bridge libraries that copied PyJWT's signature
// verbatim. The D1 Step 1.5 collapse MUST fire here and
// produce Critical/RealBug regardless of any Benign signals
// the code might otherwise carry.
let findings = run_dual_branch(
"real_cve_2015_2951.py",
"import jwt\n\
def get_user_from_token(token):\n\
\x20 payload = jwt.decode(token, algorithm='none')\n\
\x20 return payload\n",
);
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("dual-branch finding expected for algorithm='none'");
assert_eq!(
f.severity,
Severity::Critical,
"CVE-2015-2951 shape must classify Critical via D1 \
amendment collapse; got {:?}, reasons={:?}",
f.severity,
f.prediction_reasons
.iter()
.map(|r| (&r.kind, r.weight))
.collect::<Vec<_>>()
);
let alt = f.alternative_branch.as_ref().unwrap();
assert_eq!(
alt.label,
crate::dual_branch::BranchLabel::Benign,
"alternative carries the Benign interpretation for user \
inspection (e.g. if the code path is dead)"
);
}
#[test]
fn real_pyjwt_recommended_rs256_pattern() {
// The PyJWT documentation's recommended shape for asymmetric
// verification (from https://pyjwt.readthedocs.io examples,
// mirrored in Auth0, Okta, and Cognito client integrations).
// Real shape:
//
// import jwt
// PUBLIC_KEY = open('/etc/auth/jwt_public.pem').read()
// def authenticate(request):
// token = request.headers['Authorization'].split()[1]
// payload = jwt.decode(token, PUBLIC_KEY,
// algorithms=['RS256'])
// return payload
//
// Net score (decisions doc Case A): algorithms+ (+0.50) +
// asymmetric (+0.10) + auth_flow (-0.20) = +0.40 → Benign /
// Info. The function name `authenticate` IS in the auth-
// flow lexicon (negative weight), but the +0.60 of explicit-
// algorithms+asymmetric overcomes it. This is the principled
// path to a Benign verdict: explicit allowlist of asymmetric
// algorithms beats the auth-flow heuristic.
let findings = run_dual_branch(
"real_pyjwt_rs256.py",
"import jwt\n\
PUBLIC_KEY = open('/etc/auth/jwt_public.pem').read()\n\
def authenticate(request):\n\
\x20 token = request.headers['Authorization'].split()[1]\n\
\x20 payload = jwt.decode(token, PUBLIC_KEY, algorithms=['RS256'])\n\
\x20 return payload\n",
);
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("dual-branch finding expected for jwt.decode site");
assert_eq!(
f.severity,
Severity::Info,
"PyJWT-recommended RS256 shape must classify Benign/Info; \
got {:?}, reasons={:?}",
f.severity,
f.prediction_reasons
.iter()
.map(|r| (&r.kind, r.weight))
.collect::<Vec<_>>()
);
let alt = f.alternative_branch.as_ref().unwrap();
assert_eq!(alt.label, crate::dual_branch::BranchLabel::RealBug);
}
#[test]
fn real_jwt_key_confusion_cve_2016_10555_pattern() {
// CVE-2016-10555 (auth0/node-jsonwebtoken) was the original
// JWT key-confusion CVE. The Python equivalent (same shape in
// PyJWT pre-1.5) is:
//
// import jwt
// def verify_token(token):
// public_key = load_public_key()
// # BUG: HS256 with an RSA public key. The attacker can
// # sign tokens with HMAC-SHA256 of the public key
// # bytes (which they can fetch from a /jwks endpoint).
// return jwt.decode(token, public_key,
// algorithms=['HS256'])
//
// Real-world appearance: forum posts, CTF writeups, the
// CVE-2016-10555 PoC port to Python. The predictor sees
// algorithms+ (+0.50) + hs256_with_public_key (-0.50) +
// no auth flow path = 0.0 → tiebreak RealBug, Medium severity.
let findings = run_dual_branch(
"real_key_confusion.py",
"import jwt\n\
def verify_token(token, public_key):\n\
\x20 return jwt.decode(token, public_key, algorithms=['HS256'])\n",
);
let f = findings
.iter()
.find(|f| f.is_dual_branch())
.expect("dual-branch finding expected");
assert!(
matches!(
f.severity,
Severity::Medium | Severity::High | Severity::Critical
),
"CVE-2016-10555 shape (HS256 + RSA public key) must \
classify RealBug; got {:?}, reasons={:?}",
f.severity,
f.prediction_reasons
.iter()
.map(|r| (&r.kind, r.weight))
.collect::<Vec<_>>()
);
let alt = f.alternative_branch.as_ref().unwrap();
assert_eq!(alt.label, crate::dual_branch::BranchLabel::Benign);
}
}