dart-decimate 0.0.28 → 0.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/Cargo.lock +1 -1
  2. package/Cargo.toml +1 -1
  3. package/README.md +36 -60
  4. package/npm/bin/runner.js +26 -14
  5. package/npm/scripts/postinstall.js +89 -63
  6. package/package.json +6 -5
  7. package/src/baseline.rs +38 -0
  8. package/src/cli/health_args.rs +36 -7
  9. package/src/cli/html_open.rs +4 -0
  10. package/src/cli/issue_filter_args.rs +1 -0
  11. package/src/cli/security_summary_run.rs +1 -0
  12. package/src/config/health.rs +22 -2
  13. package/src/config/rule_aliases.rs +43 -0
  14. package/src/config/rules.rs +46 -1
  15. package/src/config.rs +2 -1
  16. package/src/dart_parser/test_support.rs +51 -0
  17. package/src/dart_parser.rs +8 -0
  18. package/src/dependencies/analyze.rs +3 -1
  19. package/src/dependencies/tests.rs +111 -7
  20. package/src/dependencies/usage.rs +5 -1
  21. package/src/dependencies.rs +7 -3
  22. package/src/explain/flutter_style.rs +43 -0
  23. package/src/explain/misc.rs +72 -0
  24. package/src/explain.rs +23 -67
  25. package/src/flutter_style/scanner.rs +883 -0
  26. package/src/flutter_style/types.rs +90 -0
  27. package/src/flutter_style/usage.rs +349 -0
  28. package/src/flutter_style.rs +72 -0
  29. package/src/generated.rs +154 -0
  30. package/src/health/large_units.rs +49 -0
  31. package/src/health/tests.rs +212 -1
  32. package/src/health/threshold_types.rs +31 -1
  33. package/src/health/thresholds.rs +49 -0
  34. package/src/health/types.rs +35 -0
  35. package/src/health.rs +72 -6
  36. package/src/inspect.rs +8 -0
  37. package/src/lib.rs +17 -5
  38. package/src/manifest.rs +7 -3
  39. package/src/output/dependency_findings.rs +14 -1
  40. package/src/output/flutter_style.rs +189 -0
  41. package/src/output/health_findings.rs +93 -10
  42. package/src/output/health_inventory.rs +121 -0
  43. package/src/output/html/tests.rs +20 -0
  44. package/src/output/html.rs +10 -1
  45. package/src/output/human.rs +85 -1
  46. package/src/output/human_details.rs +93 -12
  47. package/src/output/scope.rs +62 -2
  48. package/src/output/security_findings.rs +101 -76
  49. package/src/output/security_sarif.rs +24 -13
  50. package/src/output/suppressions.rs +4 -0
  51. package/src/output/types.rs +38 -2
  52. package/src/output/verdict.rs +12 -0
  53. package/src/output.rs +77 -74
  54. package/src/report_schema/inventory.rs +268 -4
  55. package/src/report_schema.rs +94 -60
  56. package/src/security/catalogue.rs +103 -0
  57. package/src/security/detect/weak_randomness.rs +762 -0
  58. package/src/security/detect.rs +1535 -221
  59. package/src/security/security_matchers.toml +172 -0
  60. package/src/security/tests.rs +336 -2
  61. package/src/security.rs +292 -56
  62. package/src/security_gate.rs +28 -0
  63. package/src/semantic.rs +276 -0
  64. package/src/symbols/semantic_evidence.rs +342 -0
  65. package/src/symbols.rs +20 -10
  66. package/src/trace/rendering.rs +54 -0
  67. package/src/trace/semantic.rs +126 -0
  68. package/src/trace.rs +54 -62
  69. package/src/widgets/inheritance.rs +63 -0
  70. package/src/widgets.rs +33 -3
@@ -3,22 +3,34 @@ use std::path::Path;
3
3
 
4
4
  use tree_sitter::Node;
5
5
 
6
- use super::{DetectedSecurityCandidate, SecurityCategory, SecurityConfidence, SecurityOccurrence};
6
+ use super::catalogue::MatcherCatalogue;
7
+ use super::{
8
+ DetectedSecurityCandidate, DetectionResult, LibraryImportContext, SecurityBlindSpot,
9
+ SecurityBlindSpotReason, SecurityCategory, SecurityConfidence, SecurityOccurrence,
10
+ };
7
11
  use crate::Location;
8
12
  use crate::dart_parser::parse_dart_source_lossy;
9
13
  use crate::generated::{is_flutterfire_options_path, is_generated_dart_path};
10
14
 
11
- pub(super) fn detect_in_source(path: &Path, source: &str) -> Vec<DetectedSecurityCandidate> {
12
- let mut candidates = Vec::new();
13
- detect_firebase_api_keys(path, source, &mut candidates);
14
- detect_hardcoded_secrets(path, source, &mut candidates);
15
- detect_insecure_transport(path, source, &mut candidates);
16
- detect_tls_bypass(path, source, &mut candidates);
17
- detect_webview_risk(path, source, &mut candidates);
18
- detect_process_execution(path, source, &mut candidates);
19
- detect_raw_sql(path, source, &mut candidates);
20
- detect_plain_secret_storage(path, source, &mut candidates);
21
- candidates
15
+ mod weak_randomness;
16
+
17
+ pub(super) fn detect_in_source(
18
+ path: &Path,
19
+ source: &str,
20
+ catalogue: &MatcherCatalogue,
21
+ inherited_imports: Option<&LibraryImportContext>,
22
+ ) -> DetectionResult {
23
+ let mut result = DetectionResult::default();
24
+ detect_firebase_api_keys(path, source, &mut result.candidates);
25
+ detect_hardcoded_secrets(path, source, &mut result.candidates);
26
+ detect_insecure_transport(path, source, &mut result.candidates);
27
+ detect_tls_bypass(path, source, catalogue, &mut result);
28
+ detect_webview_risk(path, source, catalogue, &mut result.candidates);
29
+ detect_process_execution(path, source, catalogue, inherited_imports, &mut result);
30
+ detect_raw_sql(path, source, catalogue, &mut result);
31
+ detect_plain_secret_storage(path, source, catalogue, &mut result.candidates);
32
+ weak_randomness::detect(path, source, catalogue, &mut result);
33
+ result
22
34
  }
23
35
 
24
36
  pub(super) fn is_ignored_path(path: &Path) -> bool {
@@ -62,18 +74,23 @@ fn detect_hardcoded_secrets(
62
74
  continue;
63
75
  }
64
76
  let line = line_at(source, literal.index);
77
+ let binding_name = literal_binding_name(source, literal.index);
65
78
  let secret_value = has_secret_shape(&literal.value);
66
79
  let firebase_options_literal = firebase_options_context(source, literal.index);
67
80
  let secret_name = if firebase_options_literal {
68
81
  firebase_secret_name_context(source, literal.index)
69
82
  } else {
70
- has_secret_like_name(line)
71
- };
72
- let secret_binding_name = if firebase_options_literal {
73
- secret_name
74
- } else {
75
- literal_secret_binding_context(source, literal.index)
83
+ binding_name
84
+ .as_deref()
85
+ .is_some_and(secret_binding_identifier)
76
86
  };
87
+ let secret_binding_name = secret_name;
88
+ let digest_literal = binding_name
89
+ .as_deref()
90
+ .is_some_and(non_secret_digest_identifier)
91
+ && long_hex(&literal.value);
92
+ let oauth_endpoint_credential = binding_name.as_deref().is_some_and(oauth_endpoint_name)
93
+ && literal_has_embedded_url_credentials(&literal.value);
77
94
  if stripe_secret && !is_module_uri_directive_line(line) {
78
95
  candidates.push(detected(
79
96
  path,
@@ -98,6 +115,7 @@ fn detect_hardcoded_secrets(
98
115
  || (!secret_value && literal_looks_like_storage_key(&literal.value))
99
116
  || (!secret_value && diagnostic_context(source, literal.index))
100
117
  || (!secret_value && literal.value.contains('$'))
118
+ || digest_literal
101
119
  {
102
120
  continue;
103
121
  }
@@ -106,6 +124,9 @@ fn detect_hardcoded_secrets(
106
124
  && (literal_has_concrete_token_like_segment(&literal.value)
107
125
  || literal_has_embedded_url_credentials(&literal.value))))
108
126
  && literal.value.len() >= 12)
127
+ || (literal_looks_like_operational_copy(&literal.value)
128
+ && literal_has_concrete_token_like_segment(&literal.value))
129
+ || oauth_endpoint_credential
109
130
  || secret_value
110
131
  {
111
132
  candidates.push(detected(
@@ -180,25 +201,95 @@ fn detect_insecure_transport(
180
201
  ));
181
202
  }
182
203
  }
204
+ for index in segment_indices(source, "Uri.http") {
205
+ if debug_or_local_only_http_context(source, index) {
206
+ continue;
207
+ }
208
+ let Some(open) = call_open_after(source, index + "Uri.http".len()) else {
209
+ continue;
210
+ };
211
+ let Some(call) = call_inside_after(source, open + 1) else {
212
+ continue;
213
+ };
214
+ let Some(authority) = top_level_call_arguments(&call)
215
+ .first()
216
+ .map(|value| value.trim())
217
+ else {
218
+ continue;
219
+ };
220
+ if fixed_literal_value(authority)
221
+ .is_some_and(|value| value.is_empty() || is_local_http_authority(&value))
222
+ {
223
+ continue;
224
+ }
225
+ candidates.push(detected(
226
+ path,
227
+ source,
228
+ index,
229
+ SecurityCategory::InsecureTransport,
230
+ "cleartext-http",
231
+ SecurityConfidence::High,
232
+ "Uri.http",
233
+ ));
234
+ }
235
+ for index in segment_indices(source, "Uri") {
236
+ if source[index + "Uri".len()..].starts_with('.') {
237
+ continue;
238
+ }
239
+ let Some(open) = call_open_after(source, index + "Uri".len()) else {
240
+ continue;
241
+ };
242
+ let Some(call) = call_inside_after(source, open + 1) else {
243
+ continue;
244
+ };
245
+ if named_call_argument(&call, "scheme")
246
+ .and_then(fixed_literal_value)
247
+ .as_deref()
248
+ != Some("http")
249
+ {
250
+ continue;
251
+ }
252
+ let Some(host) = named_call_argument(&call, "host") else {
253
+ continue;
254
+ };
255
+ if fixed_literal_value(host)
256
+ .is_some_and(|value| value.is_empty() || is_local_http_authority(&value))
257
+ {
258
+ continue;
259
+ }
260
+ candidates.push(detected(
261
+ path,
262
+ source,
263
+ index,
264
+ SecurityCategory::InsecureTransport,
265
+ "cleartext-http",
266
+ SecurityConfidence::High,
267
+ "Uri",
268
+ ));
269
+ }
183
270
  }
184
271
 
185
- fn detect_tls_bypass(path: &Path, source: &str, candidates: &mut Vec<DetectedSecurityCandidate>) {
186
- for pattern in [
187
- "badCertificateCallback",
188
- "HttpOverrides.global",
189
- "SecurityContext(withTrustedRoots: false",
190
- "validateCertificate",
191
- ] {
192
- for index in match_indices(source, pattern) {
193
- let window = following_window(source, index, 4);
194
- let risky = match pattern {
195
- "badCertificateCallback" | "validateCertificate" => {
196
- returns_true(window) && !returns_false(window)
197
- }
198
- _ => true,
272
+ fn detect_tls_bypass(
273
+ path: &Path,
274
+ source: &str,
275
+ catalogue: &MatcherCatalogue,
276
+ result: &mut DetectionResult,
277
+ ) {
278
+ let Ok(parsed) = parse_dart_source_lossy(path, source) else {
279
+ return;
280
+ };
281
+ let root = parsed.tree().root_node();
282
+ let mut seen = BTreeSet::new();
283
+ for pattern in &catalogue.by_detector("tls-bypass").callees {
284
+ for index in segment_indices(source, pattern) {
285
+ let Some((value, assignment)) = tls_callback_value(root, source, index, pattern) else {
286
+ continue;
199
287
  };
200
- if risky {
201
- candidates.push(detected(
288
+ if !seen.insert((pattern.as_str(), assignment)) {
289
+ continue;
290
+ }
291
+ match tls_callback_verdict(root, value, source) {
292
+ TlsCallbackVerdict::Risky => result.candidates.push(detected(
202
293
  path,
203
294
  source,
204
295
  index,
@@ -206,21 +297,312 @@ fn detect_tls_bypass(path: &Path, source: &str, candidates: &mut Vec<DetectedSec
206
297
  pattern,
207
298
  SecurityConfidence::High,
208
299
  pattern,
209
- ));
300
+ )),
301
+ TlsCallbackVerdict::Unknown => result.blind_spots.push(blind_spot(
302
+ path,
303
+ source,
304
+ index,
305
+ SecurityCategory::TlsBypass,
306
+ pattern,
307
+ SecurityBlindSpotReason::AmbiguousTlsCallback,
308
+ )),
309
+ TlsCallbackVerdict::AlwaysFalse => {}
310
+ }
311
+ }
312
+ }
313
+ }
314
+
315
+ #[derive(Clone, Copy, PartialEq, Eq)]
316
+ enum TlsCallbackVerdict {
317
+ AlwaysFalse,
318
+ Risky,
319
+ Unknown,
320
+ }
321
+
322
+ fn tls_callback_value<'tree>(
323
+ root: Node<'tree>,
324
+ source: &str,
325
+ index: usize,
326
+ pattern: &str,
327
+ ) -> Option<(Node<'tree>, usize)> {
328
+ let mut node = root.descendant_for_byte_range(index, index.saturating_add(pattern.len()))?;
329
+ loop {
330
+ if node.kind() == "assignment_expression" {
331
+ let left = node.child_by_field_name("left")?;
332
+ let operator = node
333
+ .child_by_field_name("operator")?
334
+ .utf8_text(source.as_bytes())
335
+ .ok()?;
336
+ if operator == "="
337
+ && segment_indices(left.utf8_text(source.as_bytes()).ok()?, pattern)
338
+ .into_iter()
339
+ .next()
340
+ .is_some()
341
+ {
342
+ return node
343
+ .child_by_field_name("right")
344
+ .map(|value| (value, node.start_byte()));
210
345
  }
211
346
  }
347
+ if node.kind() == "named_argument"
348
+ && named_argument_label(node, source).as_deref() == Some(pattern)
349
+ {
350
+ return named_argument_value(node).map(|value| (value, node.start_byte()));
351
+ }
352
+ if node.kind() == "cascade_section" {
353
+ let mut cursor = node.walk();
354
+ return node
355
+ .named_children(&mut cursor)
356
+ .filter(|child| child.kind() != "cascade_selector")
357
+ .last()
358
+ .map(|value| (value, node.start_byte()));
359
+ }
360
+ node = node.parent()?;
361
+ }
362
+ }
363
+
364
+ fn tls_callback_verdict(root: Node<'_>, value: Node<'_>, source: &str) -> TlsCallbackVerdict {
365
+ let text = value
366
+ .utf8_text(source.as_bytes())
367
+ .unwrap_or_default()
368
+ .trim();
369
+ if text == "null" {
370
+ return TlsCallbackVerdict::AlwaysFalse;
371
+ }
372
+ if value.kind() == "function_expression" {
373
+ return callable_boolean_verdict(root, value, source);
374
+ }
375
+ if is_identifier(text) {
376
+ return resolved_callable_boolean_verdict(root, value, text, source);
377
+ }
378
+ let mut callbacks = Vec::new();
379
+ collect_direct_descendants(value, "function_expression", &mut callbacks);
380
+ if !callbacks.is_empty() {
381
+ return combine_tls_verdicts(
382
+ callbacks
383
+ .into_iter()
384
+ .map(|callback| callable_boolean_verdict(root, callback, source)),
385
+ );
386
+ }
387
+ TlsCallbackVerdict::Unknown
388
+ }
389
+
390
+ fn resolved_callable_boolean_verdict(
391
+ root: Node<'_>,
392
+ value: Node<'_>,
393
+ name: &str,
394
+ source: &str,
395
+ ) -> TlsCallbackVerdict {
396
+ if let Some(callable) = enclosing_node(
397
+ value,
398
+ &[
399
+ "function_declaration",
400
+ "local_function_declaration",
401
+ "method_declaration",
402
+ ],
403
+ ) && let Some(body) = direct_descendant(callable, &["function_body"])
404
+ {
405
+ let mut local = Vec::new();
406
+ collect_named_callables(
407
+ body,
408
+ &["local_function_declaration"],
409
+ name,
410
+ source,
411
+ &mut local,
412
+ );
413
+ if !local.is_empty() {
414
+ return single_callable_boolean_verdict(root, &local, source);
415
+ }
416
+ }
417
+ if let Some(class) = enclosing_node(value, &["class_declaration"]) {
418
+ let mut methods = Vec::new();
419
+ collect_named_callables(class, &["method_declaration"], name, source, &mut methods);
420
+ if !methods.is_empty() {
421
+ return single_callable_boolean_verdict(root, &methods, source);
422
+ }
212
423
  }
424
+ let mut top_level = Vec::new();
425
+ let mut cursor = root.walk();
426
+ for child in root.named_children(&mut cursor) {
427
+ if child.kind() == "function_declaration"
428
+ && member_signature_name(child, source).as_deref() == Some(name)
429
+ {
430
+ top_level.push(child);
431
+ }
432
+ }
433
+ single_callable_boolean_verdict(root, &top_level, source)
213
434
  }
214
435
 
215
- fn detect_webview_risk(path: &Path, source: &str, candidates: &mut Vec<DetectedSecurityCandidate>) {
216
- for pattern in [
217
- "JavaScriptMode.unrestricted",
218
- "javaScriptEnabled: true",
219
- "allowFileAccess: true",
220
- "allowFileAccessFromFileURLs: true",
221
- "allowUniversalAccessFromFileURLs: true",
222
- ] {
223
- for index in match_indices(source, pattern) {
436
+ fn single_callable_boolean_verdict(
437
+ root: Node<'_>,
438
+ declarations: &[Node<'_>],
439
+ source: &str,
440
+ ) -> TlsCallbackVerdict {
441
+ let [declaration] = declarations else {
442
+ return TlsCallbackVerdict::Unknown;
443
+ };
444
+ callable_boolean_verdict(root, *declaration, source)
445
+ }
446
+
447
+ fn collect_named_callables<'tree>(
448
+ node: Node<'tree>,
449
+ kinds: &[&str],
450
+ name: &str,
451
+ source: &str,
452
+ declarations: &mut Vec<Node<'tree>>,
453
+ ) {
454
+ if matches!(
455
+ node.kind(),
456
+ "function_declaration" | "local_function_declaration" | "method_declaration"
457
+ ) {
458
+ if kinds.contains(&node.kind())
459
+ && member_signature_name(node, source).as_deref() == Some(name)
460
+ {
461
+ declarations.push(node);
462
+ }
463
+ return;
464
+ }
465
+ let mut cursor = node.walk();
466
+ for child in node.named_children(&mut cursor) {
467
+ collect_named_callables(child, kinds, name, source, declarations);
468
+ }
469
+ }
470
+
471
+ fn enclosing_node<'tree>(mut node: Node<'tree>, kinds: &[&str]) -> Option<Node<'tree>> {
472
+ while let Some(parent) = node.parent() {
473
+ if kinds.contains(&parent.kind()) {
474
+ return Some(parent);
475
+ }
476
+ node = parent;
477
+ }
478
+ None
479
+ }
480
+
481
+ fn callable_boolean_verdict(
482
+ root: Node<'_>,
483
+ callable: Node<'_>,
484
+ source: &str,
485
+ ) -> TlsCallbackVerdict {
486
+ let Some(body) = direct_descendant(callable, &["function_body", "function_expression_body"])
487
+ else {
488
+ return TlsCallbackVerdict::Unknown;
489
+ };
490
+ let mut returns = Vec::new();
491
+ collect_callable_returns(body, &mut returns);
492
+ if !returns.is_empty() {
493
+ return combine_tls_verdicts(returns.into_iter().map(|statement| {
494
+ let mut cursor = statement.walk();
495
+ let expression = statement.named_children(&mut cursor).next();
496
+ expression.map_or(TlsCallbackVerdict::Unknown, |expression| {
497
+ boolean_expression_verdict(root, expression, source)
498
+ })
499
+ }));
500
+ }
501
+ let mut cursor = body.walk();
502
+ body.named_children(&mut cursor)
503
+ .last()
504
+ .map_or(TlsCallbackVerdict::Unknown, |expression| {
505
+ boolean_expression_verdict(root, expression, source)
506
+ })
507
+ }
508
+
509
+ fn boolean_expression_verdict(
510
+ root: Node<'_>,
511
+ expression: Node<'_>,
512
+ source: &str,
513
+ ) -> TlsCallbackVerdict {
514
+ let value = expression
515
+ .utf8_text(source.as_bytes())
516
+ .unwrap_or_default()
517
+ .trim();
518
+ match resolved_boolean_value(root, source, expression.start_byte(), value) {
519
+ Some(false) => TlsCallbackVerdict::AlwaysFalse,
520
+ Some(true) | None => TlsCallbackVerdict::Risky,
521
+ }
522
+ }
523
+
524
+ fn collect_callable_returns<'tree>(node: Node<'tree>, returns: &mut Vec<Node<'tree>>) {
525
+ if node.kind() == "return_statement" {
526
+ returns.push(node);
527
+ return;
528
+ }
529
+ if matches!(
530
+ node.kind(),
531
+ "function_declaration"
532
+ | "function_expression"
533
+ | "local_function_declaration"
534
+ | "method_declaration"
535
+ ) {
536
+ return;
537
+ }
538
+ let mut cursor = node.walk();
539
+ for child in node.named_children(&mut cursor) {
540
+ collect_callable_returns(child, returns);
541
+ }
542
+ }
543
+
544
+ fn collect_direct_descendants<'tree>(
545
+ node: Node<'tree>,
546
+ kind: &str,
547
+ descendants: &mut Vec<Node<'tree>>,
548
+ ) {
549
+ if node.kind() == kind {
550
+ descendants.push(node);
551
+ return;
552
+ }
553
+ let mut cursor = node.walk();
554
+ for child in node.named_children(&mut cursor) {
555
+ collect_direct_descendants(child, kind, descendants);
556
+ }
557
+ }
558
+
559
+ fn direct_descendant<'tree>(node: Node<'tree>, kinds: &[&str]) -> Option<Node<'tree>> {
560
+ let mut cursor = node.walk();
561
+ node.named_children(&mut cursor).find_map(|child| {
562
+ kinds
563
+ .contains(&child.kind())
564
+ .then_some(child)
565
+ .or_else(|| direct_descendant(child, kinds))
566
+ })
567
+ }
568
+
569
+ fn combine_tls_verdicts(
570
+ verdicts: impl IntoIterator<Item = TlsCallbackVerdict>,
571
+ ) -> TlsCallbackVerdict {
572
+ let mut saw_value = false;
573
+ let mut saw_unknown = false;
574
+ for verdict in verdicts {
575
+ saw_value = true;
576
+ match verdict {
577
+ TlsCallbackVerdict::Risky => return TlsCallbackVerdict::Risky,
578
+ TlsCallbackVerdict::Unknown => saw_unknown = true,
579
+ TlsCallbackVerdict::AlwaysFalse => {}
580
+ }
581
+ }
582
+ if !saw_value || saw_unknown {
583
+ TlsCallbackVerdict::Unknown
584
+ } else {
585
+ TlsCallbackVerdict::AlwaysFalse
586
+ }
587
+ }
588
+
589
+ fn detect_webview_risk(
590
+ path: &Path,
591
+ source: &str,
592
+ catalogue: &MatcherCatalogue,
593
+ candidates: &mut Vec<DetectedSecurityCandidate>,
594
+ ) {
595
+ for pattern in catalogue
596
+ .by_detector("webview-risk")
597
+ .callees
598
+ .iter()
599
+ .filter(|pattern| !matches!(pattern.as_str(), "loadUrl" | "loadRequest"))
600
+ {
601
+ for index in segment_indices(source, pattern) {
602
+ let line = line_at(source, index);
603
+ if pattern != "JavaScriptMode.unrestricted" && !setting_is_true(line, pattern) {
604
+ continue;
605
+ }
224
606
  candidates.push(detected(
225
607
  path,
226
608
  source,
@@ -253,97 +635,329 @@ fn detect_webview_risk(path: &Path, source: &str, candidates: &mut Vec<DetectedS
253
635
  fn detect_process_execution(
254
636
  path: &Path,
255
637
  source: &str,
256
- candidates: &mut Vec<DetectedSecurityCandidate>,
638
+ catalogue: &MatcherCatalogue,
639
+ inherited_imports: Option<&LibraryImportContext>,
640
+ result: &mut DetectionResult,
257
641
  ) {
258
- let parsed = [
259
- "Process.run(",
260
- "Process.start(",
261
- "processManager.run(",
262
- "processManager.start(",
263
- ]
264
- .iter()
265
- .any(|pattern| source.contains(pattern))
266
- .then(|| parse_dart_source_lossy(path, source))
267
- .and_then(Result::ok);
268
- let syntax = parsed
269
- .as_ref()
270
- .map(|parsed| (parsed.tree().root_node(), parsed.source()));
271
- for pattern in [
272
- "Process.run(",
273
- "Process.start(",
274
- "processManager.run(",
275
- "processManager.start(",
276
- ] {
277
- for index in match_indices(source, pattern) {
278
- let args = call_inside_after(source, index + pattern.len());
279
- let run_in_shell_disabled = syntax.as_ref().is_some_and(|(root, parsed_source)| {
280
- parsed_run_in_shell_is_disabled(*root, parsed_source, index)
281
- });
282
- let safe_dart_runtime_start = run_in_shell_disabled
283
- && pattern == "Process.start("
284
- && args
285
- .as_deref()
286
- .is_some_and(|call| resolved_dart_runtime_start(syntax, index, call));
287
- let risky = args.as_deref().is_some_and(|call| {
288
- syntax.as_ref().is_some_and(|(root, parsed_source)| {
289
- call_invokes_command_shell(*root, parsed_source, index, call)
290
- })
291
- }) || !run_in_shell_disabled
292
- || args.as_deref().is_some_and(|call| {
293
- !safe_dart_runtime_start
294
- && (!first_call_arg_is_fixed_literal(call) || has_dynamic_text(call))
295
- });
296
- if risky {
297
- candidates.push(detected(
298
- path,
299
- source,
300
- index,
301
- SecurityCategory::ProcessExecution,
302
- "process-exec",
303
- SecurityConfidence::High,
304
- pattern.trim_end_matches('('),
305
- ));
306
- }
642
+ let matcher = catalogue.by_detector("process-execution");
643
+ let Ok(parsed) = parse_dart_source_lossy(path, source) else {
644
+ return;
645
+ };
646
+ let root = parsed.tree().root_node();
647
+ let parsed_source = parsed.source();
648
+ visit_named(root, &mut |node| {
649
+ detect_process_call(
650
+ path,
651
+ root,
652
+ parsed_source,
653
+ matcher,
654
+ inherited_imports,
655
+ node,
656
+ result,
657
+ );
658
+ });
659
+ }
660
+
661
+ fn detect_process_call(
662
+ path: &Path,
663
+ root: Node<'_>,
664
+ source: &str,
665
+ matcher: &super::catalogue::SecurityMatcher,
666
+ inherited_imports: Option<&LibraryImportContext>,
667
+ node: Node<'_>,
668
+ result: &mut DetectionResult,
669
+ ) {
670
+ if node.kind() != "call_expression" {
671
+ return;
672
+ }
673
+ let Some(function_node) = node.child_by_field_name("function") else {
674
+ return;
675
+ };
676
+ let Ok(function) = function_node.utf8_text(source.as_bytes()) else {
677
+ return;
678
+ };
679
+ let index = function_node.start_byte();
680
+ let pattern = matcher
681
+ .callees
682
+ .iter()
683
+ .find(|pattern| process_callee_matches(function, pattern))
684
+ .map(String::as_str)
685
+ .or_else(|| {
686
+ resolved_package_process_pattern(root, source, index, function, inherited_imports)
687
+ });
688
+ let Some(pattern) = pattern else {
689
+ if resolved_process_tearoff_pattern(
690
+ root,
691
+ source,
692
+ index,
693
+ function,
694
+ matcher,
695
+ inherited_imports,
696
+ )
697
+ .is_some()
698
+ {
699
+ push_process_blind_spot(
700
+ path,
701
+ source,
702
+ index,
703
+ SecurityBlindSpotReason::UnflattenedCall,
704
+ result,
705
+ );
307
706
  }
707
+ return;
708
+ };
709
+ if !process_call_has_provenance(root, source, index, function, pattern, inherited_imports) {
710
+ if is_part_file(root) || pattern.starts_with("processManager.") {
711
+ push_process_blind_spot(
712
+ path,
713
+ source,
714
+ index,
715
+ SecurityBlindSpotReason::AmbiguousCallProvenance,
716
+ result,
717
+ );
718
+ }
719
+ return;
720
+ }
721
+ let Some((call, arguments)) = flattened_process_arguments(node, source) else {
722
+ push_process_blind_spot(
723
+ path,
724
+ source,
725
+ index,
726
+ SecurityBlindSpotReason::UnflattenedCall,
727
+ result,
728
+ );
729
+ return;
730
+ };
731
+ let package_process = pattern.starts_with("processManager.");
732
+ let minimum_arguments = if package_process { 1 } else { 2 };
733
+ if arguments.len() < minimum_arguments {
734
+ push_process_blind_spot(
735
+ path,
736
+ source,
737
+ index,
738
+ SecurityBlindSpotReason::UnflattenedCall,
739
+ result,
740
+ );
741
+ return;
742
+ }
743
+ let risky = if package_process {
744
+ !parsed_run_in_shell_is_disabled(root, source, index)
745
+ || process_manager_invokes_command_shell(root, source, index, arguments[0])
746
+ || !fixed_argument_list(root, source, index, arguments[0])
747
+ } else {
748
+ let fixed_executable =
749
+ resolved_fixed_literal_value(root, source, index, arguments[0]).is_some();
750
+ let fixed_arguments = fixed_argument_list(root, source, index, arguments[1]);
751
+ let fixed_dart_runtime = pattern == "Process.start"
752
+ && resolved_dart_runtime_start(Some((root, source)), index, call, inherited_imports);
753
+ !parsed_run_in_shell_is_disabled(root, source, index)
754
+ || call_invokes_command_shell(root, source, index, call)
755
+ || (!fixed_executable && !fixed_dart_runtime)
756
+ || !fixed_arguments
757
+ };
758
+ if risky {
759
+ result.candidates.push(detected(
760
+ path,
761
+ source,
762
+ index,
763
+ SecurityCategory::ProcessExecution,
764
+ "process-exec",
765
+ SecurityConfidence::High,
766
+ pattern,
767
+ ));
308
768
  }
309
769
  }
310
770
 
311
- fn detect_raw_sql(path: &Path, source: &str, candidates: &mut Vec<DetectedSecurityCandidate>) {
312
- for pattern in [
313
- ".rawQuery(",
314
- ".rawInsert(",
315
- ".rawUpdate(",
316
- ".rawDelete(",
317
- ".execute(",
318
- ".customSelect(",
319
- ".customStatement(",
320
- ] {
321
- for index in match_indices(source, pattern) {
322
- let Some(call) = call_inside_after(source, index + pattern.len()) else {
771
+ fn flattened_process_arguments<'source>(
772
+ node: Node<'_>,
773
+ source: &'source str,
774
+ ) -> Option<(&'source str, Vec<&'source str>)> {
775
+ let arguments = node
776
+ .child_by_field_name("arguments")?
777
+ .utf8_text(source.as_bytes())
778
+ .ok()?
779
+ .strip_prefix('(')?
780
+ .strip_suffix(')')?;
781
+ Some((arguments, top_level_call_arguments(arguments)))
782
+ }
783
+
784
+ fn push_process_blind_spot(
785
+ path: &Path,
786
+ source: &str,
787
+ index: usize,
788
+ reason: SecurityBlindSpotReason,
789
+ result: &mut DetectionResult,
790
+ ) {
791
+ result.blind_spots.push(blind_spot(
792
+ path,
793
+ source,
794
+ index,
795
+ SecurityCategory::ProcessExecution,
796
+ "process-exec",
797
+ reason,
798
+ ));
799
+ }
800
+
801
+ fn resolved_process_tearoff_pattern(
802
+ root: Node<'_>,
803
+ source: &str,
804
+ index: usize,
805
+ function: &str,
806
+ matcher: &super::catalogue::SecurityMatcher,
807
+ inherited_imports: Option<&LibraryImportContext>,
808
+ ) -> Option<String> {
809
+ if !is_identifier(function) {
810
+ return None;
811
+ }
812
+ let value = lexical_binding_value(root, source, index, function)?.trim();
813
+ let pattern = matcher
814
+ .callees
815
+ .iter()
816
+ .find(|pattern| process_callee_matches(value, pattern))
817
+ .map(String::as_str)
818
+ .or_else(|| {
819
+ resolved_package_process_pattern(root, source, index, value, inherited_imports)
820
+ })?;
821
+ process_call_has_provenance(root, source, index, value, pattern, inherited_imports)
822
+ .then(|| pattern.to_owned())
823
+ }
824
+
825
+ fn process_callee_matches(function: &str, pattern: &str) -> bool {
826
+ function == pattern
827
+ || pattern.starts_with("Process.")
828
+ && function
829
+ .strip_suffix(pattern)
830
+ .is_some_and(|prefix| prefix.ends_with('.'))
831
+ }
832
+
833
+ fn resolved_package_process_pattern(
834
+ root: Node<'_>,
835
+ source: &str,
836
+ index: usize,
837
+ function: &str,
838
+ inherited_imports: Option<&LibraryImportContext>,
839
+ ) -> Option<&'static str> {
840
+ let (receiver, method) = function.rsplit_once('.')?;
841
+ if !is_identifier(receiver) || !matches!(method, "run" | "runSync" | "start") {
842
+ return None;
843
+ }
844
+ let declared_type = lexical_binding_declared_type(root, source, index, receiver);
845
+ let initializer_type =
846
+ lexical_binding_value(root, source, index, receiver).and_then(constructor_reference);
847
+ let process_manager = declared_type
848
+ .as_deref()
849
+ .or(initializer_type)
850
+ .is_some_and(|type_name| {
851
+ is_package_process_type_reference(root, source, index, type_name, inherited_imports)
852
+ });
853
+ if !process_manager {
854
+ return None;
855
+ }
856
+ match method {
857
+ "run" => Some("processManager.run"),
858
+ "runSync" => Some("processManager.runSync"),
859
+ "start" => Some("processManager.start"),
860
+ _ => None,
861
+ }
862
+ }
863
+
864
+ fn constructor_reference(value: &str) -> Option<&str> {
865
+ let value = value.trim();
866
+ let value = value
867
+ .strip_prefix("const ")
868
+ .or_else(|| value.strip_prefix("new "))
869
+ .unwrap_or(value)
870
+ .trim_start();
871
+ let constructor = value.split_once('(')?.0.trim();
872
+ (!constructor.is_empty()).then_some(constructor)
873
+ }
874
+
875
+ fn process_call_has_provenance(
876
+ root: Node<'_>,
877
+ source: &str,
878
+ index: usize,
879
+ function: &str,
880
+ pattern: &str,
881
+ inherited_imports: Option<&LibraryImportContext>,
882
+ ) -> bool {
883
+ if pattern.starts_with("Process.") {
884
+ let Some(method) = pattern.strip_prefix("Process") else {
885
+ return false;
886
+ };
887
+ let Some(process) = function.strip_suffix(method) else {
888
+ return false;
889
+ };
890
+ return is_dart_io_type_reference(
891
+ root,
892
+ source,
893
+ index,
894
+ process,
895
+ "Process",
896
+ inherited_imports,
897
+ );
898
+ }
899
+ pattern.starts_with("processManager.")
900
+ && resolved_package_process_pattern(root, source, index, function, inherited_imports)
901
+ == Some(pattern)
902
+ }
903
+
904
+ fn detect_raw_sql(
905
+ path: &Path,
906
+ source: &str,
907
+ catalogue: &MatcherCatalogue,
908
+ result: &mut DetectionResult,
909
+ ) {
910
+ let matcher = catalogue.by_detector("raw-sql");
911
+ let parsed = parse_dart_source_lossy(path, source).ok();
912
+ let root = parsed.as_ref().map(|parsed| parsed.tree().root_node());
913
+ for pattern in matcher
914
+ .callees
915
+ .iter()
916
+ .filter(|pattern| pattern.as_str() != "where:")
917
+ {
918
+ for index in segment_indices(source, pattern) {
919
+ let Some(open) = call_open_after(source, index + pattern.len()) else {
920
+ continue;
921
+ };
922
+ let Some(call) = call_inside_after(source, open + 1) else {
923
+ result.blind_spots.push(blind_spot(
924
+ path,
925
+ source,
926
+ index,
927
+ SecurityCategory::RawSql,
928
+ "raw-sql",
929
+ SecurityBlindSpotReason::UnflattenedCall,
930
+ ));
323
931
  continue;
324
932
  };
325
- if sql_call_is_parameterized(&call) {
933
+ let dynamic_text = root.map_or_else(
934
+ || has_dynamic_text(&call),
935
+ |root| sql_text_has_dynamic_input(root, source, index, &call),
936
+ );
937
+ if sql_call_is_parameterized(&call) && !dynamic_text {
326
938
  continue;
327
939
  }
328
- let risky = has_dynamic_text(&call) || !first_call_arg_is_fixed_literal(&call);
329
- let broad_execute = pattern == ".execute(";
940
+ let risky = dynamic_text || !first_call_arg_is_fixed_literal(&call);
941
+ let broad_execute = pattern == ".execute";
330
942
  if risky && (!broad_execute || sql_like_text(&call)) {
331
- candidates.push(detected(
943
+ result.candidates.push(detected(
332
944
  path,
333
945
  source,
334
946
  index,
335
947
  SecurityCategory::RawSql,
336
948
  "raw-sql",
337
949
  SecurityConfidence::High,
338
- pattern.trim_start_matches('.').trim_end_matches('('),
950
+ pattern.trim_start_matches('.'),
339
951
  ));
340
952
  }
341
953
  }
342
954
  }
343
- for index in match_indices(source, "where:") {
955
+ for index in segment_indices(source, "where:") {
344
956
  let line = line_at(source, index);
345
- if (line.contains('$') || line.contains('+')) && !line.contains("whereArgs") {
346
- candidates.push(detected(
957
+ let has_where_args =
958
+ root.is_some_and(|root| call_has_named_argument(root, source, index, "whereArgs"));
959
+ if has_dynamic_text(line) && !line.contains("whereArgs") && !has_where_args {
960
+ result.candidates.push(detected(
347
961
  path,
348
962
  source,
349
963
  index,
@@ -359,26 +973,42 @@ fn detect_raw_sql(path: &Path, source: &str, candidates: &mut Vec<DetectedSecuri
359
973
  fn detect_plain_secret_storage(
360
974
  path: &Path,
361
975
  source: &str,
976
+ catalogue: &MatcherCatalogue,
362
977
  candidates: &mut Vec<DetectedSecurityCandidate>,
363
978
  ) {
364
- for pattern in [
365
- ".setString(",
366
- ".setStringList(",
367
- ".put(",
368
- ".writeAsString(",
369
- ".writeAsBytes(",
370
- ] {
371
- for index in match_indices(source, pattern) {
979
+ for pattern in &catalogue.by_detector("plain-secret-storage").callees {
980
+ for index in segment_indices(source, pattern) {
372
981
  let line = line_at(source, index);
373
982
  if line.contains("FlutterSecureStorage") || line.contains(".write(") {
374
983
  continue;
375
984
  }
376
- let storage_context = match pattern {
377
- ".setString(" | ".setStringList(" => true,
378
- ".put(" => line.contains("Hive") || line.contains("box."),
985
+ let storage_context = match pattern.as_str() {
986
+ ".setString" | ".setStringList" => plain_string_storage_receiver(source, index),
987
+ ".put" => line.contains("Hive") || line.contains("box."),
379
988
  _ => line.contains("File(") || line.contains(".writeAs"),
380
989
  };
381
- if storage_context && has_secret_like_name(line) && !line.contains("HiveAesCipher") {
990
+ let Some(open) = call_open_after(source, index + pattern.len()) else {
991
+ continue;
992
+ };
993
+ let Some(call) = call_inside_after(source, open + 1) else {
994
+ continue;
995
+ };
996
+ let arguments = top_level_call_arguments(&call);
997
+ let (key, value) = match pattern.as_str() {
998
+ ".writeAsString" | ".writeAsBytes" => {
999
+ ("", arguments.first().copied().unwrap_or(""))
1000
+ }
1001
+ _ => (
1002
+ arguments.first().copied().unwrap_or(""),
1003
+ arguments.get(1).copied().unwrap_or(""),
1004
+ ),
1005
+ };
1006
+ let secret_context = has_secret_like_name(key) || has_secret_like_name(value);
1007
+ if storage_context
1008
+ && secret_context
1009
+ && !benign_secret_storage_metadata(key, value)
1010
+ && !line.contains("HiveAesCipher")
1011
+ {
382
1012
  candidates.push(detected(
383
1013
  path,
384
1014
  source,
@@ -386,7 +1016,7 @@ fn detect_plain_secret_storage(
386
1016
  SecurityCategory::PlainSecretStorage,
387
1017
  "plain-local-storage",
388
1018
  SecurityConfidence::Medium,
389
- pattern.trim_start_matches('.').trim_end_matches('('),
1019
+ pattern.trim_start_matches('.'),
390
1020
  ));
391
1021
  }
392
1022
  }
@@ -416,6 +1046,24 @@ fn detected(
416
1046
  }
417
1047
  }
418
1048
 
1049
+ fn blind_spot(
1050
+ path: &Path,
1051
+ source: &str,
1052
+ index: usize,
1053
+ category: SecurityCategory,
1054
+ sink: &str,
1055
+ reason: SecurityBlindSpotReason,
1056
+ ) -> SecurityBlindSpot {
1057
+ SecurityBlindSpot {
1058
+ category,
1059
+ path: path.to_path_buf(),
1060
+ location: location_for_index(source, index),
1061
+ sink: sink.to_owned(),
1062
+ reason,
1063
+ evidence: redact_line(line_at(source, index)),
1064
+ }
1065
+ }
1066
+
419
1067
  #[derive(Debug, Clone, PartialEq, Eq)]
420
1068
  struct StringLiteral {
421
1069
  index: usize,
@@ -494,6 +1142,48 @@ fn match_indices(source: &str, pattern: &str) -> Vec<usize> {
494
1142
  matches
495
1143
  }
496
1144
 
1145
+ fn segment_indices(source: &str, pattern: &str) -> Vec<usize> {
1146
+ match_indices(source, pattern)
1147
+ .into_iter()
1148
+ .filter(|index| {
1149
+ let before = index
1150
+ .checked_sub(1)
1151
+ .and_then(|position| source.as_bytes().get(position))
1152
+ .copied();
1153
+ let after = source.as_bytes().get(index + pattern.len()).copied();
1154
+ let starts_with_member = pattern.starts_with('.');
1155
+ let begins_with_identifier = pattern
1156
+ .as_bytes()
1157
+ .first()
1158
+ .is_some_and(u8::is_ascii_alphanumeric);
1159
+ let ends_with_identifier = pattern
1160
+ .as_bytes()
1161
+ .last()
1162
+ .is_some_and(|byte| byte.is_ascii_alphanumeric() || *byte == b'_');
1163
+ (starts_with_member
1164
+ || !begins_with_identifier
1165
+ || before.is_none_or(|byte| !is_identifier_byte(byte)))
1166
+ && (!ends_with_identifier || after.is_none_or(|byte| !is_identifier_byte(byte)))
1167
+ })
1168
+ .collect()
1169
+ }
1170
+
1171
+ fn call_open_after(source: &str, start: usize) -> Option<usize> {
1172
+ let relative = source
1173
+ .get(start..)?
1174
+ .find(|character: char| !character.is_whitespace())?;
1175
+ let index = start + relative;
1176
+ (source.as_bytes().get(index) == Some(&b'(')).then_some(index)
1177
+ }
1178
+
1179
+ fn setting_is_true(line: &str, pattern: &str) -> bool {
1180
+ line.find(pattern).is_some_and(|index| {
1181
+ line[index + pattern.len()..]
1182
+ .trim_start()
1183
+ .starts_with(": true")
1184
+ })
1185
+ }
1186
+
497
1187
  fn call_inside_after(source: &str, start: usize) -> Option<String> {
498
1188
  let bytes = source.as_bytes();
499
1189
  let mut depth = 1usize;
@@ -519,15 +1209,27 @@ fn call_inside_after(source: &str, start: usize) -> Option<String> {
519
1209
  }
520
1210
 
521
1211
  fn first_call_arg_is_fixed_literal(call: &str) -> bool {
522
- let trimmed = call.trim_start();
523
- if !matches!(trimmed.as_bytes().first(), Some(b'\'' | b'"')) {
524
- return false;
1212
+ let mut rest = call.trim_start();
1213
+ let mut saw_literal = false;
1214
+ loop {
1215
+ let raw = rest
1216
+ .as_bytes()
1217
+ .get(0..2)
1218
+ .is_some_and(|prefix| matches!(prefix, [b'r' | b'R', b'\'' | b'"']));
1219
+ let quote_index = usize::from(raw);
1220
+ if !matches!(rest.as_bytes().get(quote_index), Some(b'\'' | b'"')) {
1221
+ return saw_literal
1222
+ && (rest.is_empty() || rest.starts_with(',') || rest.starts_with(')'));
1223
+ }
1224
+ let Some((_, _, end)) = read_string(rest, quote_index) else {
1225
+ return false;
1226
+ };
1227
+ saw_literal = true;
1228
+ rest = rest[end..].trim_start();
1229
+ if rest.is_empty() || rest.starts_with(',') || rest.starts_with(')') {
1230
+ return true;
1231
+ }
525
1232
  }
526
- let Some((_, _, end)) = read_string(trimmed, 0) else {
527
- return false;
528
- };
529
- let rest = trimmed[end..].trim_start();
530
- matches!(rest.as_bytes().first(), Some(b',' | b')'))
531
1233
  }
532
1234
 
533
1235
  fn call_invokes_command_shell(root: Node<'_>, source: &str, index: usize, call: &str) -> bool {
@@ -538,17 +1240,45 @@ fn call_invokes_command_shell(root: Node<'_>, source: &str, index: usize, call:
538
1240
  else {
539
1241
  return false;
540
1242
  };
541
- let executable = executable
542
- .rsplit(['/', '\\'])
543
- .next()
544
- .unwrap_or(&executable)
545
- .to_ascii_lowercase();
546
1243
  let Some(shell_arguments) = arguments
547
1244
  .get(1)
548
1245
  .and_then(|value| resolved_list_arguments(root, source, index, value))
549
1246
  else {
550
1247
  return false;
551
1248
  };
1249
+ fixed_command_invokes_shell(root, source, index, &executable, &shell_arguments)
1250
+ }
1251
+
1252
+ fn process_manager_invokes_command_shell(
1253
+ root: Node<'_>,
1254
+ source: &str,
1255
+ index: usize,
1256
+ command: &str,
1257
+ ) -> bool {
1258
+ let Some(command) = resolved_list_arguments(root, source, index, command) else {
1259
+ return false;
1260
+ };
1261
+ let Some((executable, arguments)) = command.split_first() else {
1262
+ return false;
1263
+ };
1264
+ let Some(executable) = resolved_fixed_literal_value(root, source, index, executable) else {
1265
+ return false;
1266
+ };
1267
+ fixed_command_invokes_shell(root, source, index, &executable, arguments)
1268
+ }
1269
+
1270
+ fn fixed_command_invokes_shell(
1271
+ root: Node<'_>,
1272
+ source: &str,
1273
+ index: usize,
1274
+ executable: &str,
1275
+ shell_arguments: &[String],
1276
+ ) -> bool {
1277
+ let executable = executable
1278
+ .rsplit(['/', '\\'])
1279
+ .next()
1280
+ .unwrap_or(executable)
1281
+ .to_ascii_lowercase();
552
1282
  let posix_executable = executable.strip_suffix(".exe").unwrap_or(&executable);
553
1283
  if !matches!(
554
1284
  executable.as_str(),
@@ -558,7 +1288,7 @@ fn call_invokes_command_shell(root: Node<'_>, source: &str, index: usize, call:
558
1288
  return false;
559
1289
  }
560
1290
  for argument in shell_arguments {
561
- let Some(flag) = resolved_fixed_literal_value(root, source, index, &argument)
1291
+ let Some(flag) = resolved_fixed_literal_value(root, source, index, argument)
562
1292
  .map(|value| value.to_ascii_lowercase())
563
1293
  else {
564
1294
  return true;
@@ -628,7 +1358,12 @@ fn fixed_literal_value(value: &str) -> Option<String> {
628
1358
  .map(|(literal, _, _)| literal)
629
1359
  }
630
1360
 
631
- fn resolved_dart_runtime_start(syntax: Option<(Node<'_>, &str)>, index: usize, call: &str) -> bool {
1361
+ fn resolved_dart_runtime_start(
1362
+ syntax: Option<(Node<'_>, &str)>,
1363
+ index: usize,
1364
+ call: &str,
1365
+ inherited_imports: Option<&LibraryImportContext>,
1366
+ ) -> bool {
632
1367
  let Some((root, source)) = syntax else {
633
1368
  return false;
634
1369
  };
@@ -639,22 +1374,84 @@ fn resolved_dart_runtime_start(syntax: Option<(Node<'_>, &str)>, index: usize, c
639
1374
  let Some(arguments) = args.get(1).map(|arg| arg.trim()) else {
640
1375
  return false;
641
1376
  };
642
- (is_dart_io_platform_reference(root, source, index, executable)
1377
+ (is_dart_io_platform_reference(root, source, index, executable, inherited_imports)
643
1378
  || is_identifier(executable)
644
1379
  && lexical_binding_value(root, source, index, executable).is_some_and(|value| {
645
1380
  value == "Platform.resolvedExecutable"
646
- && is_dart_io_platform_reference(root, source, index, value)
1381
+ && is_dart_io_platform_reference(root, source, index, value, inherited_imports)
647
1382
  }))
648
1383
  && fixed_argument_list(root, source, index, arguments)
649
1384
  }
650
1385
 
651
- fn is_dart_io_platform_reference(root: Node<'_>, source: &str, index: usize, value: &str) -> bool {
652
- if library_scope_has_parts(root) {
1386
+ fn is_dart_io_platform_reference(
1387
+ root: Node<'_>,
1388
+ source: &str,
1389
+ index: usize,
1390
+ value: &str,
1391
+ inherited_imports: Option<&LibraryImportContext>,
1392
+ ) -> bool {
1393
+ if library_declares_parts(root) && inherited_imports.is_none() {
653
1394
  return false;
654
1395
  }
655
- let qualifier = if value == "Platform.resolvedExecutable" {
1396
+ let Some(platform) = value.strip_suffix(".resolvedExecutable") else {
1397
+ return false;
1398
+ };
1399
+ is_dart_io_type_reference(root, source, index, platform, "Platform", inherited_imports)
1400
+ }
1401
+
1402
+ fn is_dart_io_type_reference(
1403
+ root: Node<'_>,
1404
+ source: &str,
1405
+ index: usize,
1406
+ value: &str,
1407
+ type_name: &str,
1408
+ inherited_imports: Option<&LibraryImportContext>,
1409
+ ) -> bool {
1410
+ is_imported_type_reference(
1411
+ root,
1412
+ source,
1413
+ index,
1414
+ value,
1415
+ type_name,
1416
+ "dart:io",
1417
+ inherited_imports,
1418
+ )
1419
+ }
1420
+
1421
+ fn is_package_process_type_reference(
1422
+ root: Node<'_>,
1423
+ source: &str,
1424
+ index: usize,
1425
+ value: &str,
1426
+ inherited_imports: Option<&LibraryImportContext>,
1427
+ ) -> bool {
1428
+ ["ProcessManager", "LocalProcessManager"]
1429
+ .into_iter()
1430
+ .any(|type_name| {
1431
+ is_imported_type_reference(
1432
+ root,
1433
+ source,
1434
+ index,
1435
+ value.trim_end_matches('?'),
1436
+ type_name,
1437
+ "package:process/process.dart",
1438
+ inherited_imports,
1439
+ )
1440
+ })
1441
+ }
1442
+
1443
+ fn is_imported_type_reference(
1444
+ root: Node<'_>,
1445
+ source: &str,
1446
+ index: usize,
1447
+ value: &str,
1448
+ type_name: &str,
1449
+ import_uri: &str,
1450
+ inherited_imports: Option<&LibraryImportContext>,
1451
+ ) -> bool {
1452
+ let qualifier = if value == type_name {
656
1453
  ""
657
- } else if let Some(qualifier) = value.strip_suffix(".Platform.resolvedExecutable") {
1454
+ } else if let Some(qualifier) = value.strip_suffix(&format!(".{type_name}")) {
658
1455
  qualifier
659
1456
  } else {
660
1457
  return false;
@@ -664,10 +1461,9 @@ fn is_dart_io_platform_reference(root: Node<'_>, source: &str, index: usize, val
664
1461
  return false;
665
1462
  }
666
1463
  if prefix.is_none()
667
- && (top_level_declares_name(root, "Platform", source)
668
- || lexical_name_shadowed(root, source, index, "Platform")
669
- || import_prefix_declares_name(root, source, "Platform")
670
- || imported_library_may_expose_name(root, source, "Platform"))
1464
+ && (top_level_declares_name(root, type_name, source)
1465
+ || lexical_name_shadowed(root, source, index, type_name)
1466
+ || import_prefix_declares_name(root, source, type_name))
671
1467
  {
672
1468
  return false;
673
1469
  }
@@ -677,6 +1473,17 @@ fn is_dart_io_platform_reference(root: Node<'_>, source: &str, index: usize, val
677
1473
  }) {
678
1474
  return false;
679
1475
  }
1476
+ if let Some(inherited) = inherited_imports {
1477
+ if prefix.is_none()
1478
+ && (inherited.declared_names.contains(type_name)
1479
+ || inherited.import_prefixes.contains(type_name))
1480
+ {
1481
+ return false;
1482
+ }
1483
+ if prefix.is_some_and(|prefix| inherited.declared_names.contains(prefix)) {
1484
+ return false;
1485
+ }
1486
+ }
680
1487
  let mut found = false;
681
1488
  visit_named(root, &mut |node| {
682
1489
  if found || node.kind() != "library_import" {
@@ -692,7 +1499,7 @@ fn is_dart_io_platform_reference(root: Node<'_>, source: &str, index: usize, val
692
1499
  else {
693
1500
  return;
694
1501
  };
695
- if uri != "dart:io" {
1502
+ if uri != import_uri {
696
1503
  return;
697
1504
  }
698
1505
  let alias = specification
@@ -701,11 +1508,17 @@ fn is_dart_io_platform_reference(root: Node<'_>, source: &str, index: usize, val
701
1508
  if alias != prefix {
702
1509
  return;
703
1510
  }
704
- if import_exposes_name(node, "Platform", source) {
1511
+ if import_exposes_name(node, type_name, source) {
705
1512
  found = true;
706
1513
  }
707
1514
  });
708
- found
1515
+ if found {
1516
+ return true;
1517
+ }
1518
+ let Some(inherited) = inherited_imports else {
1519
+ return false;
1520
+ };
1521
+ inherited.exposes(import_uri, type_name, prefix)
709
1522
  }
710
1523
 
711
1524
  fn import_exposes_name(node: Node<'_>, name: &str, source: &str) -> bool {
@@ -806,37 +1619,20 @@ fn top_level_declaration_name(node: Node<'_>, source: &str) -> Option<String> {
806
1619
  .map(str::to_owned)
807
1620
  }
808
1621
 
809
- fn imported_library_may_expose_name(root: Node<'_>, source: &str, name: &str) -> bool {
810
- let mut may_expose = false;
1622
+ fn is_part_file(root: Node<'_>) -> bool {
1623
+ let mut is_part = false;
811
1624
  visit_named(root, &mut |node| {
812
- if may_expose || node.kind() != "library_import" {
813
- return;
814
- }
815
- let Some(specification) = first_named_descendant(node, "import_specification") else {
816
- return;
817
- };
818
- if specification.child_by_field_name("alias").is_some() {
819
- return;
820
- }
821
- let uri = specification
822
- .child_by_field_name("uri")
823
- .and_then(|uri| uri.utf8_text(source.as_bytes()).ok())
824
- .and_then(fixed_literal_value);
825
- if uri.as_deref() != Some("dart:io") && import_exposes_name(node, name, source) {
826
- may_expose = true;
827
- }
1625
+ is_part |= node.kind() == "part_of_directive";
828
1626
  });
829
- may_expose
1627
+ is_part
830
1628
  }
831
1629
 
832
- fn library_scope_has_parts(root: Node<'_>) -> bool {
833
- let mut has_parts = false;
1630
+ fn library_declares_parts(root: Node<'_>) -> bool {
1631
+ let mut declares_parts = false;
834
1632
  visit_named(root, &mut |node| {
835
- if matches!(node.kind(), "part_directive" | "part_of_directive") {
836
- has_parts = true;
837
- }
1633
+ declares_parts |= node.kind() == "part_directive";
838
1634
  });
839
- has_parts
1635
+ declares_parts
840
1636
  }
841
1637
 
842
1638
  fn import_prefix_declares_name(root: Node<'_>, source: &str, name: &str) -> bool {
@@ -915,6 +1711,29 @@ fn top_level_call_arguments(call: &str) -> Vec<&str> {
915
1711
  arguments
916
1712
  }
917
1713
 
1714
+ fn named_call_argument<'call>(call: &'call str, name: &str) -> Option<&'call str> {
1715
+ top_level_call_arguments(call)
1716
+ .into_iter()
1717
+ .find_map(|argument| {
1718
+ let (label, value) = argument.split_once(':')?;
1719
+ (label.trim() == name).then_some(value.trim())
1720
+ })
1721
+ }
1722
+
1723
+ fn call_has_named_argument(root: Node<'_>, source: &str, index: usize, name: &str) -> bool {
1724
+ let Some(call) = call_expression_at(root, index) else {
1725
+ return false;
1726
+ };
1727
+ let Some(arguments) = call.child_by_field_name("arguments") else {
1728
+ return false;
1729
+ };
1730
+ let mut cursor = arguments.walk();
1731
+ arguments.named_children(&mut cursor).any(|argument| {
1732
+ argument.kind() == "named_argument"
1733
+ && named_argument_label(argument, source).as_deref() == Some(name)
1734
+ })
1735
+ }
1736
+
918
1737
  fn parsed_run_in_shell_is_disabled(root: Node<'_>, source: &str, index: usize) -> bool {
919
1738
  let Some(call) = call_expression_at(root, index) else {
920
1739
  return false;
@@ -931,11 +1750,28 @@ fn parsed_run_in_shell_is_disabled(root: Node<'_>, source: &str, index: usize) -
931
1750
  }
932
1751
  return named_argument_value(argument)
933
1752
  .and_then(|value| value.utf8_text(source.as_bytes()).ok())
934
- .is_some_and(|value| value.trim() == "false");
1753
+ .is_some_and(|value| {
1754
+ resolved_boolean_value(root, source, index, value) == Some(false)
1755
+ });
935
1756
  }
936
1757
  true
937
1758
  }
938
1759
 
1760
+ fn resolved_boolean_value(root: Node<'_>, source: &str, index: usize, value: &str) -> Option<bool> {
1761
+ let mut value = value.trim();
1762
+ let mut visited = BTreeSet::new();
1763
+ loop {
1764
+ match value {
1765
+ "false" => return Some(false),
1766
+ "true" => return Some(true),
1767
+ _ if is_identifier(value) && visited.insert(value.to_owned()) => {
1768
+ value = lexical_binding_value(root, source, index, value)?.trim();
1769
+ }
1770
+ _ => return None,
1771
+ }
1772
+ }
1773
+ }
1774
+
939
1775
  fn call_expression_at(root: Node<'_>, index: usize) -> Option<Node<'_>> {
940
1776
  let mut node = root.descendant_for_byte_range(index, index.saturating_add(1))?;
941
1777
  loop {
@@ -1095,6 +1931,109 @@ fn lexical_binding_value<'source>(
1095
1931
  None
1096
1932
  }
1097
1933
 
1934
+ fn lexical_binding_declared_type(
1935
+ root: Node<'_>,
1936
+ source: &str,
1937
+ index: usize,
1938
+ name: &str,
1939
+ ) -> Option<String> {
1940
+ let mut child = root.descendant_for_byte_range(index, index.saturating_add(1))?;
1941
+ while let Some(parent) = child.parent() {
1942
+ if let Some(type_name) = parameter_binding_type(parent, name, source) {
1943
+ return Some(type_name);
1944
+ }
1945
+ if parent.kind() == "class_body" {
1946
+ let mut cursor = parent.walk();
1947
+ return parent
1948
+ .named_children(&mut cursor)
1949
+ .filter(|member| member.start_byte() != child.start_byte())
1950
+ .find_map(|member| direct_declared_binding_type(member, name, source));
1951
+ }
1952
+ if parent.parent().is_none() {
1953
+ let mut cursor = parent.walk();
1954
+ return parent
1955
+ .named_children(&mut cursor)
1956
+ .find_map(|node| direct_declared_binding_type(node, name, source));
1957
+ }
1958
+ let mut cursor = parent.walk();
1959
+ let mut siblings = parent
1960
+ .named_children(&mut cursor)
1961
+ .take_while(|sibling| sibling.start_byte() < child.start_byte())
1962
+ .collect::<Vec<_>>();
1963
+ while let Some(sibling) = siblings.pop() {
1964
+ if let Some(type_name) = direct_declared_binding_type(sibling, name, source) {
1965
+ return Some(type_name);
1966
+ }
1967
+ if direct_binding(sibling, name, source, false).is_some() {
1968
+ return None;
1969
+ }
1970
+ }
1971
+ child = parent;
1972
+ }
1973
+ None
1974
+ }
1975
+
1976
+ fn parameter_binding_type(node: Node<'_>, name: &str, source: &str) -> Option<String> {
1977
+ let parameter_lists = match node.kind() {
1978
+ "function_expression" => parameter_field_lists(node),
1979
+ "method_declaration" => node
1980
+ .child_by_field_name("signature")
1981
+ .map_or_else(Vec::new, collect_parameter_lists),
1982
+ "declaration" | "function_declaration" | "local_function_declaration" => {
1983
+ direct_parameterized_signature(node).map_or_else(Vec::new, collect_parameter_lists)
1984
+ }
1985
+ _ => Vec::new(),
1986
+ };
1987
+ for parameters in parameter_lists {
1988
+ let mut candidates = Vec::new();
1989
+ collect_named_descendants(parameters, "formal_parameter", &mut candidates);
1990
+ for parameter in candidates {
1991
+ if formal_parameter_name(parameter, source).as_deref() == Some(name) {
1992
+ return declared_type_before_binding(
1993
+ parameter.utf8_text(source.as_bytes()).ok()?,
1994
+ name,
1995
+ );
1996
+ }
1997
+ }
1998
+ }
1999
+ None
2000
+ }
2001
+
2002
+ fn direct_declared_binding_type(node: Node<'_>, name: &str, source: &str) -> Option<String> {
2003
+ direct_binding(node, name, source, false)?;
2004
+ declared_type_before_binding(node.utf8_text(source.as_bytes()).ok()?, name)
2005
+ }
2006
+
2007
+ fn declared_type_before_binding(text: &str, name: &str) -> Option<String> {
2008
+ let name_index = segment_indices(text, name).into_iter().next()?;
2009
+ let before_name = text[..name_index].trim();
2010
+ before_name
2011
+ .split_whitespace()
2012
+ .map(|token| {
2013
+ token.trim_matches(|character: char| {
2014
+ !character.is_ascii_alphanumeric()
2015
+ && !matches!(character, '_' | '$' | '.' | '<' | '>' | '?' | ',')
2016
+ })
2017
+ })
2018
+ .rfind(|token| {
2019
+ !token.is_empty()
2020
+ && !matches!(
2021
+ *token,
2022
+ "const"
2023
+ | "covariant"
2024
+ | "external"
2025
+ | "final"
2026
+ | "late"
2027
+ | "required"
2028
+ | "static"
2029
+ | "super"
2030
+ | "this"
2031
+ | "var"
2032
+ )
2033
+ })
2034
+ .map(str::to_owned)
2035
+ }
2036
+
1098
2037
  fn top_level_binding<'source>(
1099
2038
  root: Node<'_>,
1100
2039
  name: &str,
@@ -1135,6 +2074,9 @@ fn class_binding<'source>(
1135
2074
  let mut visited = BTreeSet::new();
1136
2075
  let root = root_node(class);
1137
2076
  inherited_class_binding(root, class, name, source, &mut visited).or_else(|| {
2077
+ if name.starts_with('_') && !is_part_file(root) && !library_declares_parts(root) {
2078
+ return None;
2079
+ }
1138
2080
  let mut visited = BTreeSet::new();
1139
2081
  class_hierarchy_is_unresolved(root, class, source, &mut visited)
1140
2082
  .then_some(LexicalBinding::Unknown)
@@ -1609,11 +2551,191 @@ fn is_identifier(value: &str) -> bool {
1609
2551
  }
1610
2552
 
1611
2553
  fn sql_call_is_parameterized(call: &str) -> bool {
1612
- call.contains('?') && (call.contains('[') || call.contains("whereArgs"))
2554
+ let arguments = top_level_call_arguments(call);
2555
+ arguments.get(1).is_some_and(|argument| {
2556
+ let value = argument.trim();
2557
+ !value.is_empty() && value != "null"
2558
+ }) || arguments.iter().any(|argument| {
2559
+ ["whereArgs", "variables", "parameters", "args"]
2560
+ .iter()
2561
+ .any(|name| {
2562
+ argument
2563
+ .split_once(':')
2564
+ .is_some_and(|(label, value)| label.trim() == *name && !value.trim().is_empty())
2565
+ })
2566
+ })
2567
+ }
2568
+
2569
+ fn sql_text_has_dynamic_input(root: Node<'_>, source: &str, index: usize, call: &str) -> bool {
2570
+ let Some(query) = top_level_call_arguments(call)
2571
+ .first()
2572
+ .map(|query| query.trim())
2573
+ else {
2574
+ return true;
2575
+ };
2576
+ if query.contains(" + ") || query.contains("+ ") || query.contains(" +") {
2577
+ return true;
2578
+ }
2579
+ let Some(expressions) = dart_string_interpolations(query) else {
2580
+ return true;
2581
+ };
2582
+ for expression in expressions {
2583
+ if !sql_interpolation_is_fixed(root, source, index, expression) {
2584
+ return true;
2585
+ }
2586
+ }
2587
+ false
2588
+ }
2589
+
2590
+ fn sql_interpolation_is_fixed(
2591
+ root: Node<'_>,
2592
+ source: &str,
2593
+ index: usize,
2594
+ expression: &str,
2595
+ ) -> bool {
2596
+ let expression = expression.trim();
2597
+ if expression.is_empty() || !is_identifier(expression) {
2598
+ return false;
2599
+ }
2600
+ if resolved_fixed_literal_value(root, source, index, expression).is_some() {
2601
+ return true;
2602
+ }
2603
+ let Some(value) = lexical_binding_value(root, source, index, expression) else {
2604
+ return false;
2605
+ };
2606
+ lexical_binding_is_const(source, value)
2607
+ || fixed_string_choice(value)
2608
+ || fixed_sql_placeholder_builder(value)
2609
+ }
2610
+
2611
+ fn lexical_binding_is_const(source: &str, value: &str) -> bool {
2612
+ let source_start = source.as_ptr() as usize;
2613
+ let value_start = value.as_ptr() as usize;
2614
+ let Some(offset) = value_start.checked_sub(source_start) else {
2615
+ return false;
2616
+ };
2617
+ let Some(prefix) = source.get(..offset) else {
2618
+ return false;
2619
+ };
2620
+ let statement_start = prefix
2621
+ .rfind([';', '{', '}'])
2622
+ .map_or(0, |delimiter| delimiter + 1);
2623
+ prefix[statement_start..]
2624
+ .split(|character: char| {
2625
+ character != '_' && character != '$' && !character.is_ascii_alphanumeric()
2626
+ })
2627
+ .any(|token| token == "const")
2628
+ }
2629
+
2630
+ fn fixed_string_choice(value: &str) -> bool {
2631
+ let Some(question) = top_level_delimiter(value, b'?', 0) else {
2632
+ return false;
2633
+ };
2634
+ let Some(colon) = top_level_delimiter(value, b':', question + 1) else {
2635
+ return false;
2636
+ };
2637
+ fixed_literal_value(&value[question + 1..colon]).is_some()
2638
+ && fixed_literal_value(&value[colon + 1..]).is_some()
2639
+ }
2640
+
2641
+ fn top_level_delimiter(value: &str, delimiter: u8, start: usize) -> Option<usize> {
2642
+ let bytes = value.as_bytes();
2643
+ let mut cursor = start;
2644
+ let mut depth = 0usize;
2645
+ while cursor < bytes.len() {
2646
+ match bytes[cursor] {
2647
+ b'\'' | b'"' => {
2648
+ cursor = read_string(value, cursor)?.2;
2649
+ continue;
2650
+ }
2651
+ b'(' | b'[' | b'{' => depth += 1,
2652
+ b')' | b']' | b'}' => depth = depth.saturating_sub(1),
2653
+ byte if byte == delimiter && depth == 0 => return Some(cursor),
2654
+ _ => {}
2655
+ }
2656
+ cursor += 1;
2657
+ }
2658
+ None
2659
+ }
2660
+
2661
+ fn fixed_sql_placeholder_builder(value: &str) -> bool {
2662
+ let compact = value.split_whitespace().collect::<String>();
2663
+ (compact.contains("List.filled(") || compact.contains("List.generate("))
2664
+ && (compact.contains(",'?'") || compact.contains("=>'?'"))
2665
+ && compact.contains(".join(")
1613
2666
  }
1614
2667
 
1615
2668
  fn has_dynamic_text(text: &str) -> bool {
1616
- text.contains('$') || text.contains(" + ") || text.contains("+ ") || text.contains(" +")
2669
+ text.contains(" + ")
2670
+ || text.contains("+ ")
2671
+ || text.contains(" +")
2672
+ || dart_string_interpolations(text).is_none_or(|expressions| !expressions.is_empty())
2673
+ }
2674
+
2675
+ fn dart_string_interpolations(text: &str) -> Option<Vec<&str>> {
2676
+ let bytes = text.as_bytes();
2677
+ let mut expressions = Vec::new();
2678
+ let mut cursor = 0usize;
2679
+ while cursor < bytes.len() {
2680
+ let (quote_index, raw) = if matches!(bytes[cursor], b'\'' | b'"') {
2681
+ (cursor, false)
2682
+ } else if matches!(bytes[cursor], b'r' | b'R')
2683
+ && matches!(bytes.get(cursor + 1), Some(b'\'' | b'"'))
2684
+ && cursor
2685
+ .checked_sub(1)
2686
+ .and_then(|index| bytes.get(index))
2687
+ .is_none_or(|byte| !is_identifier_byte(*byte))
2688
+ {
2689
+ (cursor + 1, true)
2690
+ } else {
2691
+ cursor += 1;
2692
+ continue;
2693
+ };
2694
+ let quote = bytes[quote_index];
2695
+ let triple =
2696
+ bytes.get(quote_index..quote_index + 3) == Some([quote, quote, quote].as_slice());
2697
+ cursor = quote_index + if triple { 3 } else { 1 };
2698
+ loop {
2699
+ if cursor >= bytes.len() {
2700
+ return None;
2701
+ }
2702
+ if triple {
2703
+ if bytes.get(cursor..cursor + 3) == Some([quote, quote, quote].as_slice()) {
2704
+ cursor += 3;
2705
+ break;
2706
+ }
2707
+ } else if bytes[cursor] == quote {
2708
+ cursor += 1;
2709
+ break;
2710
+ }
2711
+ if !raw && bytes[cursor] == b'\\' {
2712
+ cursor = (cursor + 2).min(bytes.len());
2713
+ continue;
2714
+ }
2715
+ if !raw && bytes[cursor] == b'$' {
2716
+ cursor += 1;
2717
+ let expression = if bytes.get(cursor) == Some(&b'{') {
2718
+ let start = cursor + 1;
2719
+ let relative_end = text.get(start..)?.find('}')?;
2720
+ cursor = start + relative_end + 1;
2721
+ text.get(start..start + relative_end)?.trim()
2722
+ } else {
2723
+ let start = cursor;
2724
+ while bytes
2725
+ .get(cursor)
2726
+ .is_some_and(|byte| is_identifier_byte(*byte))
2727
+ {
2728
+ cursor += 1;
2729
+ }
2730
+ text.get(start..cursor)?
2731
+ };
2732
+ expressions.push(expression);
2733
+ continue;
2734
+ }
2735
+ cursor += 1;
2736
+ }
2737
+ }
2738
+ Some(expressions)
1617
2739
  }
1618
2740
 
1619
2741
  fn sql_like_text(text: &str) -> bool {
@@ -1641,6 +2763,26 @@ fn has_network_context(line: &str) -> bool {
1641
2763
  .any(|pattern| line.contains(pattern))
1642
2764
  }
1643
2765
 
2766
+ fn plain_string_storage_receiver(source: &str, index: usize) -> bool {
2767
+ let receiver = source[..index]
2768
+ .rsplit(|character: char| {
2769
+ !character.is_ascii_alphanumeric() && !matches!(character, '_' | '$')
2770
+ })
2771
+ .next()
2772
+ .unwrap_or_default()
2773
+ .to_ascii_lowercase();
2774
+ [
2775
+ "prefs",
2776
+ "preference",
2777
+ "storage",
2778
+ "cache",
2779
+ "settings",
2780
+ "store",
2781
+ ]
2782
+ .iter()
2783
+ .any(|marker| receiver.contains(marker))
2784
+ }
2785
+
1644
2786
  fn has_secret_like_name(text: &str) -> bool {
1645
2787
  let lower = text.to_ascii_lowercase();
1646
2788
  [
@@ -1684,20 +2826,23 @@ fn firebase_secret_name_context(source: &str, index: usize) -> bool {
1684
2826
  literal_argument_context(source, index).is_some_and(has_secret_like_name)
1685
2827
  }
1686
2828
 
1687
- fn literal_secret_binding_context(source: &str, index: usize) -> bool {
1688
- literal_binding_name(source, index).is_some_and(|name| secret_binding_identifier(&name))
1689
- }
1690
-
1691
2829
  fn literal_binding_name(source: &str, index: usize) -> Option<String> {
1692
- let context = literal_context(source, index)?;
1693
- for separator in ['=', ':'] {
1694
- let Some((candidate, rest)) = context.rsplit_once(separator) else {
1695
- continue;
1696
- };
1697
- if rest.trim().is_empty() {
1698
- return trailing_identifier(candidate)
1699
- .map(str::to_owned)
1700
- .or_else(|| trailing_string_literal(candidate));
2830
+ for context in [
2831
+ literal_context(source, index),
2832
+ literal_argument_context(source, index),
2833
+ ]
2834
+ .into_iter()
2835
+ .flatten()
2836
+ {
2837
+ for separator in ['=', ':'] {
2838
+ let Some((candidate, rest)) = context.rsplit_once(separator) else {
2839
+ continue;
2840
+ };
2841
+ if rest.trim().is_empty() {
2842
+ return trailing_identifier(candidate)
2843
+ .map(str::to_owned)
2844
+ .or_else(|| trailing_string_literal(candidate));
2845
+ }
1701
2846
  }
1702
2847
  }
1703
2848
  None
@@ -1715,9 +2860,11 @@ fn trailing_string_literal(text: &str) -> Option<String> {
1715
2860
 
1716
2861
  fn secret_binding_identifier(identifier: &str) -> bool {
1717
2862
  let lower = identifier.to_ascii_lowercase();
1718
- [
2863
+ let suffixes = [
1719
2864
  "token",
1720
2865
  "secret",
2866
+ "secretkey",
2867
+ "secret_key",
1721
2868
  "jwt",
1722
2869
  "privatekey",
1723
2870
  "private_key",
@@ -1733,9 +2880,46 @@ fn secret_binding_identifier(identifier: &str) -> bool {
1733
2880
  "api_key",
1734
2881
  "signingkey",
1735
2882
  "signing_key",
1736
- ]
1737
- .iter()
1738
- .any(|suffix| lower == *suffix || lower.ends_with(suffix))
2883
+ ];
2884
+ suffixes
2885
+ .iter()
2886
+ .any(|suffix| lower == *suffix || lower.ends_with(suffix))
2887
+ || lower
2888
+ .char_indices()
2889
+ .next_back()
2890
+ .filter(|(_, suffix)| suffix.is_ascii_alphanumeric())
2891
+ .map(|(index, _)| &lower[..index])
2892
+ .is_some_and(|partitioned| {
2893
+ suffixes
2894
+ .iter()
2895
+ .any(|suffix| partitioned == *suffix || partitioned.ends_with(suffix))
2896
+ })
2897
+ }
2898
+
2899
+ fn non_secret_digest_identifier(identifier: &str) -> bool {
2900
+ let normalized = identifier
2901
+ .chars()
2902
+ .filter(char::is_ascii_alphanumeric)
2903
+ .collect::<String>()
2904
+ .to_ascii_lowercase();
2905
+ normalized.contains("sha256")
2906
+ || normalized.ends_with("checksum")
2907
+ || normalized.ends_with("digest")
2908
+ || normalized.ends_with("fingerprint")
2909
+ }
2910
+
2911
+ fn benign_secret_storage_metadata(key: &str, value: &str) -> bool {
2912
+ let normalized_key = key
2913
+ .chars()
2914
+ .filter(char::is_ascii_alphanumeric)
2915
+ .collect::<String>()
2916
+ .to_ascii_lowercase();
2917
+ let normalized_value = value.trim().to_ascii_lowercase();
2918
+ (normalized_value.strip_suffix(".name").is_some()
2919
+ && ["type", "kind", "name", "label"]
2920
+ .iter()
2921
+ .any(|marker| normalized_key.contains(marker)))
2922
+ || (normalized_key.contains("showtoken") && !has_secret_like_name(value))
1739
2923
  }
1740
2924
 
1741
2925
  fn stripe_secret_binding_context(source: &str, index: usize) -> bool {
@@ -1779,7 +2963,12 @@ fn oauth_endpoint_name(value: &str) -> bool {
1779
2963
  .collect::<String>();
1780
2964
  matches!(
1781
2965
  normalized.to_ascii_lowercase().as_str(),
1782
- "authorizationendpoint" | "tokenendpoint"
2966
+ "authorizationendpoint"
2967
+ | "tokenendpoint"
2968
+ | "oauthendpoint"
2969
+ | "oauthtoken"
2970
+ | "oauthtokenurl"
2971
+ | "oauthtokenendpoint"
1783
2972
  )
1784
2973
  }
1785
2974
 
@@ -2543,8 +3732,9 @@ fn has_secret_shape(value: &str) -> bool {
2543
3732
  return false;
2544
3733
  }
2545
3734
  value.contains("-----BEGIN ") && value.contains("PRIVATE KEY-----")
2546
- || value.starts_with("Bearer ")
2547
- || value.starts_with("sk_")
3735
+ || value
3736
+ .strip_prefix("Bearer ")
3737
+ .is_some_and(|token| token.trim().len() >= 8)
2548
3738
  || value.starts_with("ghp_")
2549
3739
  || jwt_like(value)
2550
3740
  || long_hex(value)
@@ -2650,25 +3840,55 @@ fn is_local_http_url(value: &str) -> bool {
2650
3840
  .any(|prefix| lower.starts_with(prefix))
2651
3841
  }
2652
3842
 
2653
- fn returns_true(text: &str) -> bool {
2654
- text.contains("=> true") || text.contains("return true") || text.contains(": true")
2655
- }
2656
-
2657
- fn returns_false(text: &str) -> bool {
2658
- text.contains("=> false") || text.contains("return false") || text.contains(": false")
2659
- }
2660
-
2661
- fn following_window(source: &str, index: usize, lines: usize) -> &str {
2662
- let mut end = index;
2663
- for _ in 0..lines {
2664
- end = source[end..]
2665
- .find('\n')
2666
- .map_or(source.len(), |relative| end + relative + 1);
2667
- if end == source.len() {
2668
- break;
2669
- }
3843
+ fn is_local_http_authority(value: &str) -> bool {
3844
+ let lower = value
3845
+ .rsplit_once('@')
3846
+ .map_or(value, |(_, authority)| authority)
3847
+ .to_ascii_lowercase();
3848
+ lower == "localhost"
3849
+ || lower.starts_with("localhost:")
3850
+ || lower == "127.0.0.1"
3851
+ || lower.starts_with("127.0.0.1:")
3852
+ || lower == "[::1]"
3853
+ || lower.starts_with("[::1]:")
3854
+ || lower == "::1"
3855
+ || lower.starts_with("::1:")
3856
+ || lower == "10.0.2.2"
3857
+ || lower.starts_with("10.0.2.2:")
3858
+ || lower == "0.0.0.0"
3859
+ || lower.starts_with("0.0.0.0:")
3860
+ }
3861
+
3862
+ fn debug_or_local_only_http_context(source: &str, index: usize) -> bool {
3863
+ let start = source[..index]
3864
+ .rfind('\n')
3865
+ .map_or(0, |line| {
3866
+ let mut start = line;
3867
+ for _ in 0..5 {
3868
+ start = source[..start].rfind('\n').map_or(0, |previous| previous);
3869
+ }
3870
+ start
3871
+ })
3872
+ .max(index.saturating_sub(768));
3873
+ let context = &source[start..index];
3874
+ if context.contains("kDebugMode") {
3875
+ return true;
2670
3876
  }
2671
- &source[index..end]
3877
+ context.contains('?')
3878
+ && [
3879
+ "startsWith('localhost')",
3880
+ "startsWith(\"localhost\")",
3881
+ "startsWith('127.')",
3882
+ "startsWith(\"127.\")",
3883
+ "startsWith('10.')",
3884
+ "startsWith(\"10.\")",
3885
+ "startsWith('192.168.')",
3886
+ "startsWith(\"192.168.\")",
3887
+ "startsWith('[::1]')",
3888
+ "startsWith(\"[::1]\")",
3889
+ ]
3890
+ .iter()
3891
+ .any(|guard| context.contains(guard))
2672
3892
  }
2673
3893
 
2674
3894
  fn line_at(source: &str, index: usize) -> &str {
@@ -2755,6 +3975,100 @@ class Runner {
2755
3975
  Some((parsed.tree().root_node(), parsed.source())),
2756
3976
  index,
2757
3977
  &call,
3978
+ None,
3979
+ ));
3980
+ }
3981
+
3982
+ #[test]
3983
+ fn fixed_sql_lookup_crosses_nested_transaction_callbacks() {
3984
+ let source = r"const _stylesTable = 'tb_styles';
3985
+ class TagDao extends BaseDao {
3986
+ Future<int> insertTag(String name) async {
3987
+ final db = await database;
3988
+ return db.transaction((txn) async {
3989
+ final existing = await txn.rawQuery(
3990
+ '''
3991
+ SELECT id FROM $_stylesTable
3992
+ WHERE LOWER(font_family) = LOWER(?)
3993
+ ''',
3994
+ [name],
3995
+ );
3996
+ return existing.length;
3997
+ });
3998
+ }
3999
+ }
4000
+ ";
4001
+ let parsed = parse_dart_source_lossy(Path::new("lib/tag.dart"), source)
4002
+ .unwrap_or_else(|error| panic!("parse fixture: {error}"));
4003
+ let index = source
4004
+ .find(".rawQuery")
4005
+ .unwrap_or_else(|| panic!("raw query call"));
4006
+ let open = call_open_after(source, index + ".rawQuery".len())
4007
+ .unwrap_or_else(|| panic!("call open"));
4008
+ let call = call_inside_after(source, open + 1).unwrap_or_else(|| panic!("query arguments"));
4009
+ assert_eq!(
4010
+ lexical_binding_value(
4011
+ parsed.tree().root_node(),
4012
+ parsed.source(),
4013
+ index,
4014
+ "_stylesTable",
4015
+ ),
4016
+ Some("'tb_styles'")
4017
+ );
4018
+ assert!(!sql_text_has_dynamic_input(
4019
+ parsed.tree().root_node(),
4020
+ parsed.source(),
4021
+ index,
4022
+ &call,
4023
+ ));
4024
+ }
4025
+
4026
+ #[test]
4027
+ fn unresolved_public_inherited_sql_names_remain_dynamic() {
4028
+ let source = r"const table = 'users';
4029
+ class Store extends UnknownStore {
4030
+ void query(dynamic db) {
4031
+ db.rawQuery('SELECT * FROM $table');
4032
+ }
4033
+ }
4034
+ ";
4035
+ let parsed = parse_dart_source_lossy(Path::new("lib/store.dart"), source)
4036
+ .unwrap_or_else(|error| panic!("parse fixture: {error}"));
4037
+ let index = source
4038
+ .find(".rawQuery")
4039
+ .unwrap_or_else(|| panic!("raw query call"));
4040
+ let open = call_open_after(source, index + ".rawQuery".len())
4041
+ .unwrap_or_else(|| panic!("call open"));
4042
+ let call = call_inside_after(source, open + 1).unwrap_or_else(|| panic!("query arguments"));
4043
+ assert!(sql_text_has_dynamic_input(
4044
+ parsed.tree().root_node(),
4045
+ parsed.source(),
4046
+ index,
4047
+ &call,
4048
+ ));
4049
+ }
4050
+
4051
+ #[test]
4052
+ fn oauth_metadata_exclusion_preserves_embedded_credentials() {
4053
+ let source = r"const tokenEndpoint =
4054
+ 'https://client:concrete-secret@login.acme.com/oauth2/token';
4055
+ const metadata = OAuthMetadata(
4056
+ authorizationEndpoint:
4057
+ 'https://login.acme.com/oauth2/authorize#code_verifier=concrete-code-verifier',
4058
+ );";
4059
+ let literals = string_literals(source);
4060
+ assert_eq!(literals.len(), 2);
4061
+ assert!(literal_has_url_userinfo(&literals[0].value));
4062
+ assert!(literal_has_secret_like_url_parameter(&literals[1].value));
4063
+ assert!(!oauth_endpoint_metadata_context(
4064
+ source,
4065
+ literals[0].index,
4066
+ &literals[0].value,
4067
+ ));
4068
+ assert!(!oauth_endpoint_metadata_context(
4069
+ source,
4070
+ literals[1].index,
4071
+ &literals[1].value,
2758
4072
  ));
2759
4073
  }
2760
4074
  }