foxguard 0.10.0

A security scanner as fast as a linter, written in Rust. 200+ built-in rules across 12 source languages.
Documentation
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
use std::sync::OnceLock;

use regex::Regex;

use crate::impl_rule;
use crate::rules::common::{
    hardcoded_secret_re, is_secret_value_long_enough, make_finding, make_finding_from_offsets,
    walk_tree,
};
use crate::{Language, Severity};

// ─── Static regex helpers (compiled once) ────────────────────────────────────

fn swift_weak_crypto_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"\b(CC_MD5|CC_SHA1|\.md5|\.sha1|Insecure\.MD5|Insecure\.SHA1)\b")
            .expect("static Swift weak crypto regex should compile")
    })
}

fn swift_sql_keywords_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"(?i)(SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|CREATE)\s")
            .expect("static Swift SQL keyword regex should compile")
    })
}

fn swift_interp_string_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r#""[^"]*\\\([^)]+\)[^"]*""#)
            .expect("static Swift interpolation regex should compile")
    })
}

fn swift_sql_concat_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(
            r#"(?i)(execute|prepare|sqlite3_exec)\s*\([^)]*(?:SELECT|INSERT|UPDATE|DELETE|DROP)[^)]*\+\s*"#,
        )
        .expect("static Swift SQL concat regex should compile")
    })
}

fn swift_keychain_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"\b(kSecAttrAccessibleAlways|kSecAttrAccessibleAlwaysThisDeviceOnly)\b")
            .expect("static Swift keychain regex should compile")
    })
}

fn swift_tls_expired_certs_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"allowsExpiredCertificates\s*=\s*true")
            .expect("static Swift TLS regex should compile")
    })
}

fn swift_tls_expired_roots_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"allowsExpiredRoots\s*=\s*true").expect("static Swift TLS regex should compile")
    })
}

fn swift_tls_disable_eval_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        Regex::new(r"\.disableEvaluation").expect("static Swift TLS regex should compile")
    })
}

// ─── Constant-folding support ────────────────────────────────────────────────
//
// Several of the dynamic-argument rules below (command injection, eval-js,
// path traversal, SSRF) used to flag any call whose argument was not an inline
// quoted string literal. That produced false positives whenever the argument
// was a `let`-bound string-literal constant declared earlier in scope, e.g.
//
//     let cmd = "/bin/ls"
//     Process().launchPath = cmd   // <- constant, not user input
//
// `swift_const_string_names` does a cheap source-level pre-pass to collect the
// names of simple `let NAME = "literal"` (and `let NAME: Type = "literal"`)
// declarations whose right-hand side is a plain, non-interpolated string
// literal. Rules can then treat references to these names as safe constants.

fn swift_const_decl_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        // `let NAME` or `let NAME: Type`, then `=`, then a double-quoted string
        // up to the closing quote. We reject interpolation (`\(`) afterwards.
        Regex::new(r#"(?m)\blet\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?::\s*[^=\n]+?)?=\s*"([^"\\]*)""#)
            .expect("static Swift const decl regex should compile")
    })
}

/// Collect names of `let`-bound, non-interpolated string-literal constants.
fn swift_const_string_names(source: &str) -> std::collections::HashSet<String> {
    let mut names = std::collections::HashSet::new();
    for caps in swift_const_decl_re().captures_iter(source) {
        // caps[2] is the (already interpolation-free, since `\` is excluded
        // from the body) string contents. The regex body class `[^"\\]*`
        // rejects both embedded quotes and backslashes, so `\(...)`
        // interpolation never matches here.
        if let Some(name) = caps.get(1) {
            names.insert(name.as_str().to_string());
        }
    }
    names
}

/// Extract the textual contents between the first `(` and the matching final
/// `)` of a call expression's source text. Falls back to the full text if no
/// parentheses are present. Used to feed argument text to `swift_arg_is_constant`.
fn call_args(text: &str) -> &str {
    match (text.find('('), text.rfind(')')) {
        (Some(open), Some(close)) if close > open => &text[open + 1..close],
        _ => text,
    }
}

/// Extract the value text following a labeled argument such as `atPath:` or
/// `path:`, up to the next top-level comma or the end of the call text.
/// Returns `None` if the label is not present.
fn labeled_arg_value<'a>(text: &'a str, label: &str) -> Option<&'a str> {
    let start = text.find(label)? + label.len();
    let rest = &text[start..];
    Some(first_arg(rest))
}

/// Return the first comma-separated argument from a call argument string,
/// ignoring commas nested inside parentheses or brackets. Used to isolate the
/// first positional argument (e.g. the JS string in
/// `evaluateJavaScript(script, completionHandler:)`).
fn first_arg(args: &str) -> &str {
    let mut depth = 0i32;
    for (i, c) in args.char_indices() {
        match c {
            '(' | '[' | '{' => depth += 1,
            ')' | ']' | '}' => depth -= 1,
            ',' if depth == 0 => return &args[..i],
            _ => {}
        }
    }
    args
}

/// Given the textual contents of a call argument list (or assignment RHS),
/// decide whether every "operand" is safe: i.e. a string literal or a known
/// string constant. Returns `false` (unsafe) if the text contains string
/// interpolation, or references an identifier that is not a known constant.
///
/// This is intentionally conservative on the unsafe side: anything we cannot
/// confidently classify as a literal/constant is treated as dynamic.
fn swift_arg_is_constant(arg: &str, consts: &std::collections::HashSet<String>) -> bool {
    let trimmed = arg.trim();
    if trimmed.is_empty() {
        return true;
    }
    // Interpolation is always dynamic.
    if trimmed.contains("\\(") {
        return false;
    }
    // Split on `+` (concatenation) and `,` (array/argument elements), then
    // evaluate each operand independently. Every operand must be either an
    // inline string literal or a known string constant.
    for raw_operand in trimmed.split(['+', ',']) {
        // Strip surrounding whitespace and any leading/trailing grouping or
        // collection delimiters left over from slicing inside a larger
        // expression (e.g. `myPath)` from `removeItem(atPath: myPath)` or
        // `["-la"]` from a `process.arguments` assignment).
        let mut operand = raw_operand
            .trim()
            .trim_start_matches(['(', '[', '{'])
            .trim_end_matches([')', ']', '}'])
            .trim();
        if operand.is_empty() {
            continue;
        }
        // Strip a leading argument label (`name:`) so that
        // `arguments: [safeCmd]` is evaluated as `safeCmd`. Only strip when
        // the prefix is a plain identifier followed by a colon (not `::` and
        // not part of a string literal).
        if let Some((label, rest)) = operand.split_once(':') {
            if !label.is_empty()
                && label.chars().all(|c| c.is_alphanumeric() || c == '_')
                && !rest.starts_with(':')
            {
                operand = rest
                    .trim()
                    .trim_start_matches(['(', '[', '{'])
                    .trim_end_matches([')', ']', '}'])
                    .trim();
            }
        }
        if operand.is_empty() {
            continue;
        }
        // Inline string literal operand.
        if operand.starts_with('"') {
            continue;
        }
        // Bare identifier operand — safe only if it is a known constant.
        let ident: String = operand
            .chars()
            .take_while(|c| c.is_alphanumeric() || *c == '_')
            .collect();
        if !ident.is_empty() && operand.len() == ident.len() && consts.contains(&ident) {
            continue;
        }
        return false;
    }
    true
}

// ─── Rule 1: no-hardcoded-secret ────────────────────────────────────────────

pub struct NoHardcodedSecret;

impl_rule! {
    NoHardcodedSecret,
    id = "swift/no-hardcoded-secret",
    severity = Severity::High,
    cwe = Some("CWE-798"),
    description = "Hardcoded secret or credential detected",
    language = Language::Swift,
    fn check_with_context(_self, source, tree, ctx) {

        let mut findings = Vec::new();
        let mut reported_lines = std::collections::HashSet::new();
        let secret_pattern = hardcoded_secret_re();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            // Match property declarations: let password = "hardcoded"
            // or var apiKey = "secret123"
            if node.kind() == "property_declaration" {
                // Check if the name portion matches a secret pattern
                if let Some(name_node) = node.child_by_field_name("name") {
                    let name = &src[name_node.byte_range()];
                    if secret_pattern.is_match(name) {
                        // Walk children looking for a string_literal value
                        let mut has_string_value = false;
                        let mut string_val = String::new();
                        let mut cursor = node.walk();
                        for child in node.children(&mut cursor) {
                            if child.kind() == "line_string_literal"
                                || child.kind() == "string_literal"
                            {
                                has_string_value = true;
                                string_val = src[child.byte_range()].to_string();
                            }
                        }
                        if has_string_value {
                            let inner = string_val.trim_matches('"');
                            let line = node.start_position().row;
                            if is_secret_value_long_enough(inner, ctx.secret_thresholds)
                                && reported_lines.insert(line)
                            {
                                findings.push(make_finding(
                                    _self.id(),
                                    _self.severity(),
                                    _self.cwe(),
                                    &format!(
                                        "Hardcoded secret in '{}' — use environment variables or Keychain",
                                        name
                                    ),
                                    node,
                                    src,
                                ));
                            }
                        }
                    }
                }
            }

            // Fallback: regex-based detection for patterns like `let password = "..."`
            // that may parse differently
            if node.kind() == "value_binding_pattern" || node.kind() == "pattern" {
                let name = &src[node.byte_range()];
                if secret_pattern.is_match(name) {
                    if let Some(parent) = node.parent() {
                        let line = parent.start_position().row;
                        if reported_lines.contains(&line) {
                            return;
                        }
                        let mut cursor = parent.walk();
                        for child in parent.children(&mut cursor) {
                            if child.kind() == "line_string_literal"
                                || child.kind() == "string_literal"
                            {
                                let val = &src[child.byte_range()];
                                let inner = val.trim_matches('"');
                                if is_secret_value_long_enough(inner, ctx.secret_thresholds)
                                    && reported_lines.insert(line)
                                {
                                    findings.push(make_finding(
                                        _self.id(),
                                        _self.severity(),
                                        _self.cwe(),
                                        &format!(
                                            "Hardcoded secret in '{}' — use environment variables or Keychain",
                                            name
                                        ),
                                        parent,
                                        src,
                                    ));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        });
        findings

    }
}

// ─── Rule 2: no-command-injection ───────────────────────────────────────────

pub struct NoCommandInjection;

impl_rule! {
    NoCommandInjection,
    id = "swift/no-command-injection",
    severity = Severity::Critical,
    cwe = Some("CWE-78"),
    description = "Potential command injection via Process or NSTask with dynamic arguments",
    language = Language::Swift,
    fn check(_self, source, tree) {

        let mut findings = Vec::new();
        let consts = swift_const_string_names(source);

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                let text = &src[node.byte_range()];
                if text.starts_with("Process(") || text.starts_with("NSTask(") {
                    // A bare constructor (`Process()`) or one whose arguments are
                    // all string literals / known constants is not, by itself,
                    // command injection. Only flag when an argument is dynamic
                    // (interpolation, concatenation with a non-constant, or a
                    // bare non-constant identifier).
                    let args = call_args(text);
                    if !swift_arg_is_constant(args, &consts) {
                        findings.push(make_finding(
                            _self.id(),
                            _self.severity(),
                            _self.cwe(),
                            "Process/NSTask created with dynamic arguments — ensure arguments are not user-controlled to prevent command injection",
                            node,
                            src,
                        ));
                    }
                }
            }

            // Detect .launchPath or .arguments assignment with non-literal values
            if node.kind() == "assignment" {
                let text = &src[node.byte_range()];
                if text.contains(".launchPath") || text.contains(".arguments") {
                    // The RHS is what matters: flag only if it is dynamic and
                    // not a known string constant.
                    let rhs = text.split_once('=').map(|x| x.1).unwrap_or(text);
                    if !swift_arg_is_constant(rhs, &consts) {
                        findings.push(make_finding(
                            _self.id(),
                            _self.severity(),
                            _self.cwe(),
                            "Process arguments set with dynamic value — risk of command injection",
                            node,
                            src,
                        ));
                    }
                }
            }
        });
        findings

    }
}

// ─── Rule 3: no-weak-crypto ────────────────────────────────────────────────

pub struct NoWeakCrypto;

impl_rule! {
    NoWeakCrypto,
    id = "swift/no-weak-crypto",
    severity = Severity::Medium,
    cwe = Some("CWE-327"),
    description = "Use of weak cryptographic hash (MD5/SHA1)",
    language = Language::Swift,
    fn check(_self, source, _tree) {

        let mut findings = Vec::new();
        let pattern = swift_weak_crypto_re();

        for matched in pattern.find_iter(source) {
            let algo = if matched.as_str().contains("MD5") || matched.as_str().contains("md5") {
                "MD5"
            } else {
                "SHA1"
            };
            findings.push(make_finding_from_offsets(
                _self.id(),
                _self.severity(),
                _self.cwe(),
                &format!(
                    "{} is cryptographically weak — use SHA-256 or stronger",
                    algo
                ),
                source,
                matched.start(),
                matched.end(),
            ));
        }
        findings

    }
}

// ─── Rule 4: no-insecure-transport ─────────────────────────────────────────

pub struct NoInsecureTransport;

impl_rule! {
    NoInsecureTransport,
    id = "swift/no-insecure-transport",
    severity = Severity::High,
    cwe = Some("CWE-319"),
    description = "Insecure HTTP URL detected — use HTTPS instead",
    language = Language::Swift,
    fn check(_self, source, tree) {

        let mut findings = Vec::new();

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "line_string_literal" || node.kind() == "string_literal" {
                let text = &src[node.byte_range()];
                if text.contains("http://")
                    && !text.contains("http://localhost")
                    && !text.contains("http://127.0.0.1")
                {
                    findings.push(make_finding(
                        _self.id(),
                        _self.severity(),
                        _self.cwe(),
                        "Insecure HTTP URL — use HTTPS to protect data in transit",
                        node,
                        src,
                    ));
                }
            }
        });
        findings

    }
}

// ─── Rule 5: no-eval-js ────────────────────────────────────────────────────

pub struct NoEvalJs;

impl_rule! {
    NoEvalJs,
    id = "swift/no-eval-js",
    severity = Severity::Critical,
    cwe = Some("CWE-95"),
    description = "WKWebView evaluateJavaScript with dynamic input enables code injection",
    language = Language::Swift,
    fn check(_self, source, tree) {

        let mut findings = Vec::new();
        let consts = swift_const_string_names(source);

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                let text = &src[node.byte_range()];
                if text.contains("evaluateJavaScript") {
                    // Extract the argument(s) to evaluateJavaScript(...) and flag
                    // only when dynamic: interpolation, concatenation with a
                    // non-constant, or a bare non-constant identifier. An inline
                    // literal or a known string constant is safe.
                    let args = first_arg(call_args(text));
                    let is_variable_arg = !swift_arg_is_constant(args, &consts);
                    if is_variable_arg {
                        findings.push(make_finding(
                            _self.id(),
                            _self.severity(),
                            _self.cwe(),
                            "evaluateJavaScript called with dynamic input — risk of JavaScript injection in WKWebView",
                            node,
                            src,
                        ));
                    }
                }
            }
        });
        findings

    }
}

// ─── Rule 6: no-sql-injection ──────────────────────────────────────────────

pub struct NoSqlInjection;

impl_rule! {
    NoSqlInjection,
    id = "swift/no-sql-injection",
    severity = Severity::Critical,
    cwe = Some("CWE-89"),
    description = "Potential SQL injection via string interpolation in SQLite queries",
    language = Language::Swift,
    fn check(_self, source, _tree) {

        let mut findings = Vec::new();
        let sql_keywords = swift_sql_keywords_re();

        // Detect SQL strings with interpolation: "SELECT ... \(variable) ..."
        let interp_string = swift_interp_string_re();
        for matched in interp_string.find_iter(source) {
            let text = matched.as_str();
            if sql_keywords.is_match(text) {
                findings.push(make_finding_from_offsets(
                    _self.id(),
                    _self.severity(),
                    _self.cwe(),
                    "SQL query with string interpolation — use parameterized queries to prevent SQL injection",
                    source,
                    matched.start(),
                    matched.end(),
                ));
            }
        }

        // Detect execute/prepare calls with string concatenation
        let sql_concat = swift_sql_concat_re();
        for matched in sql_concat.find_iter(source) {
            findings.push(make_finding_from_offsets(
                _self.id(),
                _self.severity(),
                _self.cwe(),
                "SQL query built with string concatenation — use parameterized queries",
                source,
                matched.start(),
                matched.end(),
            ));
        }

        findings

    }
}

// ─── Rule 7: no-insecure-keychain ──────────────────────────────────────────

pub struct NoInsecureKeychain;

impl_rule! {
    NoInsecureKeychain,
    id = "swift/no-insecure-keychain",
    severity = Severity::High,
    cwe = Some("CWE-311"),
    description = "Insecure Keychain accessibility level allows access when device is locked",
    language = Language::Swift,
    fn check(_self, source, _tree) {

        let mut findings = Vec::new();
        let pattern = swift_keychain_re();

        for matched in pattern.find_iter(source) {
            findings.push(make_finding_from_offsets(
                _self.id(),
                _self.severity(),
                _self.cwe(),
                &format!(
                    "{} allows Keychain access when device is locked — use kSecAttrAccessibleWhenUnlocked",
                    matched.as_str()
                ),
                source,
                matched.start(),
                matched.end(),
            ));
        }
        findings

    }
}

// ─── Rule 8: no-tls-disabled ───────────────────────────────────────────────

pub struct NoTlsDisabled;

impl_rule! {
    NoTlsDisabled,
    id = "swift/no-tls-disabled",
    severity = Severity::High,
    cwe = Some("CWE-295"),
    description = "TLS certificate validation disabled or weakened",
    language = Language::Swift,
    fn check(_self, source, _tree) {

        let mut findings = Vec::new();

        let patterns: [(&Regex, &str); 3] = [
            (
                swift_tls_expired_certs_re(),
                "allowsExpiredCertificates = true disables certificate expiry validation",
            ),
            (
                swift_tls_expired_roots_re(),
                "allowsExpiredRoots = true disables root certificate expiry validation",
            ),
            (
                swift_tls_disable_eval_re(),
                ".disableEvaluation disables TLS server trust evaluation entirely",
            ),
        ];

        for (pattern, msg) in &patterns {
            for matched in pattern.find_iter(source) {
                findings.push(make_finding_from_offsets(
                    _self.id(),
                    _self.severity(),
                    _self.cwe(),
                    msg,
                    source,
                    matched.start(),
                    matched.end(),
                ));
            }
        }
        findings

    }
}

// ─── Rule 9: no-path-traversal ─────────────────────────────────────────────

pub struct NoPathTraversal;

impl_rule! {
    NoPathTraversal,
    id = "swift/no-path-traversal",
    severity = Severity::High,
    cwe = Some("CWE-22"),
    description = "Potential path traversal via FileManager with dynamic path",
    language = Language::Swift,
    fn check(_self, source, tree) {

        let mut findings = Vec::new();
        let mut reported_lines = std::collections::HashSet::new();
        let consts = swift_const_string_names(source);

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                let text = &src[node.byte_range()];
                // Detect FileManager operations with non-literal paths
                let fm_ops = [
                    "contentsOfDirectory",
                    "createDirectory",
                    "removeItem",
                    "copyItem",
                    "moveItem",
                    "fileExists",
                    "contents(atPath",
                ];
                let has_fm_op = fm_ops.iter().any(|op| text.contains(op));
                if has_fm_op {
                    // Check the value passed to atPath:/path:. It is dynamic
                    // only if it is neither an inline literal nor a known
                    // string constant.
                    let path_value = labeled_arg_value(text, "atPath:")
                        .or_else(|| labeled_arg_value(text, "path:"));
                    let has_dynamic_path = match path_value {
                        Some(v) => !swift_arg_is_constant(v, &consts),
                        None => false,
                    };
                    if has_dynamic_path {
                        let line = node.start_position().row;
                        if reported_lines.insert(line) {
                            findings.push(make_finding(
                                _self.id(),
                                _self.severity(),
                                _self.cwe(),
                                "FileManager operation with dynamic path — validate and sanitize to prevent path traversal",
                                node,
                                src,
                            ));
                        }
                    }
                }
            }
        });

        findings

    }
}

// ─── Rule 10: no-ssrf ──────────────────────────────────────────────────────

pub struct NoSsrf;

impl_rule! {
    NoSsrf,
    id = "swift/no-ssrf",
    severity = Severity::High,
    cwe = Some("CWE-918"),
    description = "Potential SSRF via URLSession or URL with dynamic input",
    language = Language::Swift,
    fn check(_self, source, tree) {

        let mut findings = Vec::new();
        let mut reported_lines = std::collections::HashSet::new();
        let consts = swift_const_string_names(source);

        walk_tree(tree.root_node(), source, &mut |node, src| {
            if node.kind() == "call_expression" {
                let text = &src[node.byte_range()];

                // Detect URL(string: variable)
                if text.starts_with("URL(string:") || text.starts_with("URL(string :") {
                    // The string: value is dynamic only if it is neither an
                    // inline literal nor a known string constant.
                    let value = text.split_once(':').map(|x| x.1).unwrap_or("");
                    if !swift_arg_is_constant(first_arg(value), &consts) {
                        let line = node.start_position().row;
                        if reported_lines.insert(line) {
                            findings.push(make_finding(
                                _self.id(),
                                _self.severity(),
                                _self.cwe(),
                                "URL(string:) called with dynamic value — validate and allowlist target hosts to prevent SSRF",
                                node,
                                src,
                            ));
                        }
                    }
                }

                // Detect URLSession.shared.dataTask with non-literal URL
                if text.contains("dataTask") && text.contains("url") {
                    // Dynamic unless an inline http literal or a known string
                    // constant is referenced in the call.
                    let line = node.start_position().row;
                    let mentions_const = consts.iter().any(|c| {
                        // word-boundary-ish containment check
                        text.split(|ch: char| !(ch.is_alphanumeric() || ch == '_'))
                            .any(|w| w == c)
                    });
                    if !text.contains("\"http") && !mentions_const && reported_lines.insert(line) {
                        findings.push(make_finding(
                            _self.id(),
                            _self.severity(),
                            _self.cwe(),
                            "URLSession.dataTask called with dynamic URL — validate and allowlist target hosts to prevent SSRF",
                            node,
                            src,
                        ));
                    }
                }
            }
        });
        findings

    }
}