zizmor 1.24.1

Static analysis for GitHub Actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
//! Template injection detection.
//!
//! This looks for job steps where the step contains indicators of template
//! expansion, i.e. anything matching `${{ ... }}`.
//!
//! Supports both `run:` clauses (i.e. for template injection within a shell
//! context) as well as `uses:` clauses where one or more inputs is known
//! to be a code injection sink. `actions/github-script` with `script:`
//! is an example of the latter.
//!
//! The list of action injection sinks is derived in part from
//! [CodeQL's models](https://github.com/github/codeql/blob/main/actions/ql/lib/ext),
//! which are licensed by GitHub, Inc. under the MIT License.
//!
//! A small amount of additional processing is done to remove template
//! expressions that an attacker can't control.

use std::{env, ops::Deref, sync::LazyLock, vec};

use fst::Map;
use github_actions_expressions::{Expr, context::Context, literal::Literal};
use github_actions_models::common::{EnvValue, RepositoryUses, Uses, expr::LoE};
use itertools::Itertools as _;

use super::{Audit, AuditLoadError, audit_meta};
use crate::{
    audit::AuditError,
    config::Config,
    finding::{
        Confidence, Finding, Fix, Persona, Severity,
        location::{Routable as _, SymbolicLocation},
    },
    models::{
        self, StepCommon, action::CompositeStep, inputs::Capability, uses::RepositoryUsesPattern,
        workflow::Step,
    },
    state::AuditState,
    utils::{self, DEFAULT_ENVIRONMENT_VARIABLES, ExtractedExpr, extract_fenced_expressions},
};
use subfeature::Subfeature;
use yamlpatch::{Op, Patch};

pub(crate) struct TemplateInjection;

audit_meta!(
    TemplateInjection,
    "template-injection",
    "code injection via template expansion"
);

#[allow(clippy::unwrap_used)]
static ACTION_INJECTION_SINKS: LazyLock<Vec<(RepositoryUsesPattern, Vec<&str>)>> =
    LazyLock::new(|| {
        let mut sinks: Vec<(RepositoryUsesPattern, Vec<&str>)> = serde_json::from_slice(
            include_bytes!(concat!(env!("OUT_DIR"), "/codeql-injection-sinks.json")),
        )
        .unwrap();

        sinks.extend([
            // These sinks are not tracked by CodeQL (yet)
            ("amadevus/pwsh-script".parse().unwrap(), vec!["script"]),
            (
                "jannekem/run-python-script-action".parse().unwrap(),
                vec!["script"],
            ),
            (
                "cardinalby/js-eval-action".parse().unwrap(),
                vec!["expression"],
            ),
            (
                "addnab/docker-run-action".parse().unwrap(),
                vec!["options", "run"],
            ),
        ]);
        sinks
    });

static CONTEXT_CAPABILITIES_FST: LazyLock<Map<&[u8]>> = LazyLock::new(|| {
    fst::Map::new(include_bytes!(concat!(env!("OUT_DIR"), "/context-capabilities.fst")).as_slice())
        .expect("couldn't initialize context capabilities FST")
});

impl Capability {
    fn from_context(context: &str) -> Option<Self> {
        match CONTEXT_CAPABILITIES_FST.get(context) {
            Some(0) => Some(Capability::Arbitrary),
            Some(1) => Some(Capability::Structured),
            Some(2) => Some(Capability::Fixed),
            Some(_) => unreachable!("unexpected context capability"),
            _ => None,
        }
    }
}

impl TemplateInjection {
    fn action_injection_sinks(uses: &RepositoryUses) -> &[&'static str] {
        // TODO: Optimize; this performs a linear scan over the map at the moment.
        // This isn't meaningfully slower than a linear scan over a list
        // of patterns at current sizes, but if we go above a few hundred
        // patterns we might want to consider something like
        // the context capabilities FST.
        ACTION_INJECTION_SINKS
            .iter()
            .find(|(pattern, _)| pattern.matches(uses))
            .map(|(_, sinks)| sinks.as_slice())
            .unwrap_or(&[])
    }

    /// Returns a list of three-tuples containing the script body,
    /// script location, and any related locations for a step that's
    /// known to be a template injection sink.
    fn scripts_with_location<'doc>(
        step: &impl StepCommon<'doc>,
    ) -> Vec<(
        &'doc str,
        SymbolicLocation<'doc>,
        Vec<SymbolicLocation<'doc>>,
    )> {
        match step.body() {
            models::StepBodyCommon::Uses {
                uses: Uses::Repository(uses),
                with: LoE::Literal(with),
            } => TemplateInjection::action_injection_sinks(uses)
                .iter()
                .filter_map(|input| {
                    let input = *input;
                    with.get(input)
                        .and_then(|script| {
                            // Non-string env values can't contain expressions,
                            // so we skip them.
                            if let EnvValue::String(script) = script {
                                Some(script.as_str())
                            } else {
                                None
                            }
                        })
                        .map(|script| {
                            (
                                script,
                                step.location().with_keys(["with".into(), input.into()]),
                                vec![
                                    // TODO: Plumb the step name/id as a related
                                    // location here and below; this will require us
                                    // to add it to StepCommon.
                                    step.location()
                                        .with_keys(["uses".into()])
                                        .annotated("action accepts arbitrary code"),
                                    step.location()
                                        .with_keys(["with".into(), input.into()])
                                        .annotated("via this input")
                                        .key_only(),
                                ],
                            )
                        })
                })
                .collect(),
            models::StepBodyCommon::Run { run, .. } => {
                vec![(
                    run,
                    step.location().with_keys(["run".into()]),
                    vec![
                        step.location()
                            .with_keys(["run".into()])
                            .annotated("this run block")
                            .key_only(),
                    ],
                )]
            }
            _ => vec![],
        }
    }

    /// Returns the appropriate variable expansion syntax for the given variable
    /// based on the step's shell type. Returns `None` if the shell type is unsupported
    /// for auto-fixing.
    fn variable_expansion_for_shell<'doc>(
        env_var: &str,
        step: &impl StepCommon<'doc>,
    ) -> Option<String> {
        // Only provide fixes for run steps
        if !matches!(step.body(), models::StepBodyCommon::Run { .. }) {
            return None;
        }

        let shell = utils::normalize_shell(step.shell()?.0);

        match shell {
            "bash" | "sh" | "zsh" => Some(format!("${{{env_var}}}")),
            "cmd" => Some(format!("%{env_var}%")),
            "pwsh" | "powershell" => Some(format!("$env:{env_var}")),
            _ => None,
        }
    }

    /// Converts a [`Context`] into an appropriate environment variable name,
    /// or `None` if conversion is not possible.
    fn context_to_env_var(ctx: &Context) -> Option<String> {
        // This is annoyingly non-trivial because of a few different syntax
        // forms in contexts, plus some special cases we want to produce:
        //
        // - Contexts like `foo.bar` should become `FOO_BAR` (the happy path)
        // - Contexts that contain `[n]` where `n <= 3` should render with
        //   a friendly index, e.g. `foo.bar[0]` becomes `FOO_FIRST_BAR`
        //   and `foo.bar[2]` becomes `FOO_THIRD_BAR`.
        // - Contexts that contain `[n]` where `n > 3` should render with
        //   an index, e.g. `foo.bar[4]` becomes `FOO_5TH_BAR`.
        // - Contexts that contain `*` should render with `ANY`, e.g.
        //   `foo.bar[*]` becomes `FOO_ANY_BAR`, as does `foo.bar.*`.
        let mut env_parts = vec![];

        let mut ctx_parts = ctx.parts.iter();

        // `env` contexts don't include the `env` prefix in the variable name,
        // both because they're already environment variables and so that
        // we can check against the runner's default environment variables.
        // TODO: We could probably go a step further here and avoid the
        // loop below entirely, since we expect `env` contexts to only
        // have a single part, i.e. `foo.bar` and never `foo.bar.baz`.
        let is_env_context = ctx.child_of("env");
        if is_env_context {
            ctx_parts.next();
        }

        // TODO: Pop off `matrix` and `secrets` heads, since these don't
        // add any extra information to the variable name?
        // Doing this will require us to do a bit of deconflicting, since
        // we don't want to accidentally produce a default environment
        // variable, e.g. `secrets.GITHUB_JOB` should not become `GITHUB_JOB`.

        for part in ctx_parts {
            match part.deref() {
                // We don't support turning call-led contexts into variable names.
                Expr::Call { .. } => return None,
                Expr::Identifier(ident) => {
                    env_parts.push(ident.as_str().replace('-', "_"));
                }
                Expr::Star => {
                    env_parts.insert(env_parts.len() - 1, "ANY".into());
                }
                Expr::Index(idx) => {
                    // We support string, numeric, and star indices;
                    // everything else is presumed computed.
                    match idx.as_ref().deref() {
                        // FIXME: Annoying soundness hole here: index-style
                        // literal keys can be anything, not just valid identifiers.
                        // The right thing to do here is to parse these literals
                        // and refuse to convert them if we can't make them
                        // into valid identifiers.
                        Expr::Literal(Literal::String(lit)) => {
                            env_parts.push(lit.replace('-', "_"))
                        }
                        Expr::Literal(Literal::Number(idx)) => {
                            let name = match *idx as i64 {
                                0 => "FIRST".into(),
                                1 => "SECOND".into(),
                                2 => "THIRD".into(),
                                n => format!("{}TH", n + 1),
                            };

                            env_parts.insert(env_parts.len() - 1, name);
                        }
                        Expr::Star => {
                            env_parts.insert(env_parts.len() - 1, "ANY".into());
                        }
                        _ => return None,
                    }
                }
                _ => {
                    tracing::warn!("unexpected context component: {part:?}");
                    return None;
                }
            }
        }

        let env_var = env_parts.join("_");

        // For `env` contexts, preserve the original case since these refer
        // to existing environment variables. GitHub recommends treating
        // environment variables as case sensitive.
        if is_env_context {
            Some(env_var)
        } else {
            Some(env_var.to_uppercase())
        }
    }

    /// Attempts to produce a `Fix` for a given expression.
    fn attempt_fix<'doc>(
        &self,
        raw: &ExtractedExpr<'doc>,
        parsed: &Expr,
        step: &impl StepCommon<'doc>,
    ) -> Option<Fix<'doc>> {
        // We can only fix `run:` steps for now.
        if !matches!(step.body(), models::StepBodyCommon::Run { .. }) {
            return None;
        }

        // If our expression isn't a single context, then we can't fix it yet.
        let Expr::Context(ctx) = parsed else {
            return None;
        };

        // From here, our fix consists of two patch operations:
        // 1. Replacing the expression in the script with an environment
        //    variable of our generation. The variable syntax depends on
        //    the shell type: `${VAR}` for bash/sh, `%VAR%` for cmd,
        //    `$env:VAR` for PowerShell.
        // 2. Inserting the new environment variable into the step's
        //    `env:` block, e.g. `FOO_BAR: ${{ foo.bar }}`.
        //
        // TODO: We could optimize patching a bit here by keeping track
        // of contexts that have pre-defined environment variable equivalents,
        // e.g. `github.ref_name` is always `GITHUB_REF_NAME`. When we see
        // these, we shouldn't add a new `env:` member.

        // We might fail to produce a reasonable environment variable,
        // e.g. if the context is a call expression or has a computed
        // index. In those kinds of cases, we don't produce a fix.
        let env_var = Self::context_to_env_var(ctx)?;

        // Express the variable's expansion according to the step's shell.
        // For example, `VAR` becomes `${VAR}` in bash/sh/zsh,
        let var_expansion = Self::variable_expansion_for_shell(&env_var, step)?;

        let mut patches = vec![];
        patches.push(Patch {
            route: step.route().with_key("run"),
            operation: Op::RewriteFragment {
                from: subfeature::Subfeature::new(0, raw.as_raw()),
                to: var_expansion.into(),
            },
        });

        // We need to insert a new key into the `env:` block, unless the
        // variable is already a default *or* the context is `env.FOO`,
        // since the latter implies that `FOO` is already present.
        let needs_new_env = !DEFAULT_ENVIRONMENT_VARIABLES
            .iter()
            .map(|t| t.0)
            .contains(&env_var.as_str())
            && !ctx.child_of("env");

        if needs_new_env {
            patches.push(Patch {
                route: step.route(),
                operation: Op::MergeInto {
                    key: "env".to_string(),
                    updates: indexmap::IndexMap::from_iter([(
                        env_var.clone(),
                        serde_yaml::Value::String(raw.as_raw().into()),
                    )]),
                },
            });
        }

        Some(Fix {
            title: "replace expression with environment variable".into(),
            key: step.location().key,
            disposition: Default::default(),
            patches,
        })
    }

    fn injectable_template_expressions<'doc>(
        &self,
        script: &'doc str,
        step: &impl StepCommon<'doc>,
    ) -> Vec<(
        Subfeature<'doc>,
        Option<Fix<'doc>>,
        Severity,
        Confidence,
        Persona,
    )> {
        let mut all_bad_expressions = vec![];
        for (expr, expr_span) in extract_fenced_expressions(script) {
            let Ok(parsed) = Expr::parse(expr.as_bare()) else {
                tracing::warn!("couldn't parse expression: {expr}", expr = expr.as_raw());
                continue;
            };
            let mut bad_expressions = vec![];

            for (context, origin) in parsed.dataflow_contexts() {
                // Try and turn our context into a pattern for
                // matching against the FST.
                match context.as_pattern().as_deref() {
                    Some(context_pattern) => {
                        // Try and get the pattern's capability from our FST.
                        match Capability::from_context(context_pattern) {
                            // Fixed means no meaningful injectable structure.
                            Some(Capability::Fixed) => continue,
                            // Structured means some attacker-controllable
                            // structure, but not fully arbitrary.
                            Some(Capability::Structured) => {
                                bad_expressions.push((
                                    Subfeature::new(
                                        expr_span.start + origin.span.start,
                                        origin.raw,
                                    ),
                                    self.attempt_fix(&expr, &parsed, step),
                                    Severity::Medium,
                                    Confidence::High,
                                    Persona::default(),
                                ));
                            }
                            // Arbitrary means the context's expansion is
                            // fully attacker-controllable.
                            Some(Capability::Arbitrary) => {
                                bad_expressions.push((
                                    Subfeature::new(
                                        expr_span.start + origin.span.start,
                                        origin.raw,
                                    ),
                                    self.attempt_fix(&expr, &parsed, step),
                                    Severity::High,
                                    Confidence::High,
                                    Persona::default(),
                                ));
                            }
                            None => {
                                // Without a FST match, we fall back on heuristics.
                                if context.child_of("secrets") {
                                    // While not ideal, secret expansion is typically not exploitable.
                                    continue;
                                } else if context.matches("needs.*.result") {
                                    // `result` is always one of `success`, `failure`, `cancelled`, or `skipped`.
                                    continue;
                                } else if context.child_of("inputs") {
                                    let (severity, confidence, persona) = match context
                                        .single_tail()
                                        .and_then(|input_name| step.get_input(input_name))
                                    {
                                        Some(Capability::Fixed) => {
                                            (Severity::Low, Confidence::High, Persona::Pedantic)
                                        }
                                        Some(Capability::Structured) => {
                                            (Severity::Medium, Confidence::High, Persona::default())
                                        }
                                        Some(Capability::Arbitrary) => {
                                            (Severity::High, Confidence::High, Persona::default())
                                        }
                                        None => {
                                            (Severity::Low, Confidence::Low, Persona::default())
                                        }
                                    };

                                    bad_expressions.push((
                                        Subfeature::new(
                                            expr_span.start + origin.span.start,
                                            origin.raw,
                                        ),
                                        self.attempt_fix(&expr, &parsed, step),
                                        severity,
                                        confidence,
                                        persona,
                                    ));
                                } else if context.child_of("env") {
                                    let env_is_static = step.env_is_static(context);

                                    if !env_is_static {
                                        bad_expressions.push((
                                            Subfeature::new(
                                                expr_span.start + origin.span.start,
                                                origin.raw,
                                            ),
                                            self.attempt_fix(&expr, &parsed, step),
                                            Severity::Low,
                                            Confidence::High,
                                            Persona::default(),
                                        ));
                                    } else {
                                        // Emit a pedantic finding even if we think the env context
                                        // expansion is probably static.
                                        bad_expressions.push((
                                            Subfeature::new(
                                                expr_span.start + origin.span.start,
                                                origin.raw,
                                            ),
                                            self.attempt_fix(&expr, &parsed, step),
                                            Severity::Low,
                                            Confidence::High,
                                            Persona::Pedantic,
                                        ));
                                    }
                                } else if context.child_of("github") {
                                    // TODO: Filter these more finely; not everything in the event
                                    // context is actually attacker-controllable.
                                    bad_expressions.push((
                                        Subfeature::new(
                                            expr_span.start + origin.span.start,
                                            origin.raw,
                                        ),
                                        self.attempt_fix(&expr, &parsed, step),
                                        Severity::High,
                                        Confidence::High,
                                        Persona::default(),
                                    ));
                                } else if context.child_of("matrix") {
                                    let matrix_is_static = match step.matrix() {
                                        Some(matrix) => matrix.expands_to_static_values(context),
                                        // Context specifies a matrix, but there is no matrix defined.
                                        // This is an invalid workflow so there's no point in flagging it.
                                        None => continue,
                                    };

                                    if !matrix_is_static {
                                        bad_expressions.push((
                                            Subfeature::new(
                                                expr_span.start + origin.span.start,
                                                origin.raw,
                                            ),
                                            self.attempt_fix(&expr, &parsed, step),
                                            Severity::Medium,
                                            Confidence::Medium,
                                            Persona::default(),
                                        ));
                                    }
                                } else {
                                    // All other contexts are typically not attacker controllable,
                                    // but may be in obscure cases.
                                    bad_expressions.push((
                                        Subfeature::new(
                                            expr_span.start + origin.span.start,
                                            origin.raw,
                                        ),
                                        self.attempt_fix(&expr, &parsed, step),
                                        Severity::Informational,
                                        Confidence::Low,
                                        Persona::default(),
                                    ));
                                }
                            }
                        }
                    }
                    None => {
                        // If we couldn't turn the context into a pattern,
                        // we almost certainly have something like
                        // `call(...).foo.bar`.
                        bad_expressions.push((
                            Subfeature::new(expr_span.start + origin.span.start, origin.raw),
                            self.attempt_fix(&expr, &parsed, step),
                            Severity::Informational,
                            Confidence::Low,
                            Persona::default(),
                        ));
                    }
                }
            }

            // If we didn't find anything noteworthy inside the extracted expression
            // (i.e., no injectable contexts with relevant dataflows), then
            // we emit a blanket pedantic finding for the extracted expression itself.
            // We do this because any expression in a code context is a code smell,
            // even if unexploitable.
            if bad_expressions.is_empty() {
                bad_expressions.push((
                    Subfeature::new(expr_span.start, &parsed),
                    // Intentionally not providing a fix here.
                    None,
                    Severity::Low,
                    Confidence::High,
                    Persona::Pedantic,
                ));
            }

            all_bad_expressions.extend(bad_expressions);
        }

        all_bad_expressions
    }

    fn process_step<'doc>(
        &self,
        step: &impl StepCommon<'doc>,
    ) -> Result<Vec<Finding<'doc>>, AuditError> {
        let mut findings = vec![];

        for (script, script_loc, related_locs) in Self::scripts_with_location(step) {
            for (subfeature, fix, severity, confidence, persona) in
                self.injectable_template_expressions(script, step)
            {
                let mut finding_builder = Self::finding()
                    .severity(severity)
                    .confidence(confidence)
                    .persona(persona)
                    .add_location(step.location().hidden())
                    .add_location(
                        script_loc
                            .clone()
                            .primary()
                            .subfeature(subfeature)
                            .annotated("may expand into attacker-controllable code".to_string()),
                    );

                for related_loc in &related_locs {
                    finding_builder = finding_builder.add_location(related_loc.clone());
                }

                if let Some(fix) = fix {
                    finding_builder = finding_builder.fix(fix);
                }

                let finding = finding_builder.build(step)?;
                findings.push(finding);
            }
        }

        Ok(findings)
    }
}

#[async_trait::async_trait]
impl Audit for TemplateInjection {
    fn new(_state: &AuditState) -> Result<Self, AuditLoadError>
    where
        Self: Sized,
    {
        Ok(Self)
    }

    async fn audit_step<'doc>(
        &self,
        step: &Step<'doc>,
        _config: &Config,
    ) -> Result<Vec<Finding<'doc>>, AuditError> {
        self.process_step(step)
    }

    async fn audit_composite_step<'a>(
        &self,
        step: &CompositeStep<'a>,
        _config: &Config,
    ) -> Result<Vec<Finding<'a>>, AuditError> {
        self.process_step(step)
    }
}

#[cfg(test)]
mod tests {
    use github_actions_expressions::Expr;

    use crate::audit::Audit;
    use crate::audit::template_injection::{Capability, TemplateInjection};
    use crate::config::Config;
    use crate::models::AsDocument;
    use crate::models::workflow::Workflow;
    use crate::registry::input::InputKey;
    use crate::state::AuditState;

    /// Macro for testing workflow audits with common boilerplate
    macro_rules! test_workflow_audit {
        ($audit_type:ty, $filename:expr, $workflow_content:expr, $test_fn:expr) => {{
            let key = InputKey::local("fakegroup".into(), $filename, None::<&str>);
            let workflow = Workflow::from_string($workflow_content.to_string(), key).unwrap();
            let audit_state = AuditState::default();
            let audit = <$audit_type>::new(&audit_state).unwrap();
            let findings = audit
                .audit_workflow(&workflow, &Config::default())
                .await
                .unwrap();

            $test_fn(&workflow, findings)
        }};
    }

    /// Helper function to apply a specific fix by title and return the result for snapshot testing
    fn apply_fix_by_title_for_snapshot(
        document: &yamlpath::Document,
        finding: &crate::finding::Finding,
        expected_title: &str,
    ) -> yamlpath::Document {
        assert!(!finding.fixes.is_empty(), "Expected fixes but got none");

        let fix = finding
            .fixes
            .iter()
            .find(|f| f.title == expected_title)
            .unwrap_or_else(|| panic!("Expected fix with title '{expected_title}' but not found"));

        fix.apply(document).unwrap()
    }

    #[tokio::test]
    async fn test_template_injection_fix_github_ref_name() {
        let workflow_content = r#"
name: Test Template Injection
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Vulnerable step
        run: echo "Branch is ${{ github.ref_name }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_github_ref_name.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection
                assert!(!findings.is_empty());

                // Should have at least one finding with a fix
                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(
                    finding_with_fix.is_some(),
                    "Expected at least one finding with a fix"
                );

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection
                    on: push
                    jobs:
                      test:
                        runs-on: ubuntu-latest
                        steps:
                          - name: Vulnerable step
                            run: echo "Branch is ${GITHUB_REF_NAME}"
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_github_actor() {
        let workflow_content = r#"
name: Test Template Injection
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Vulnerable step
        run: |
          echo "Hello ${{ github.actor }}"
          echo "Processing user input"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_github_actor.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection
                assert!(!findings.is_empty());

                // Should have at least one finding with a fix
                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(
                    finding_with_fix.is_some(),
                    "Expected at least one finding with a fix"
                );

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection
                    on: push
                    jobs:
                      test:
                        runs-on: ubuntu-latest
                        steps:
                          - name: Vulnerable step
                            run: |
                              echo "Hello ${GITHUB_ACTOR}"
                              echo "Processing user input"
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_with_existing_env() {
        let workflow_content = r#"
name: Test Template Injection
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Vulnerable step with existing env
        run: echo "Event name is ${{ github.event.head_commit.message }}"
        env:
          EXISTING_VAR: "existing_value"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_with_existing_env.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection
                assert!(!findings.is_empty());

                // Should have at least one finding with a fix
                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(
                    finding_with_fix.is_some(),
                    "Expected at least one finding with a fix"
                );

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection
                    on: push
                    jobs:
                      test:
                        runs-on: ubuntu-latest
                        steps:
                          - name: Vulnerable step with existing env
                            run: echo "Event name is ${GITHUB_EVENT_HEAD_COMMIT_MESSAGE}"
                            env:
                              EXISTING_VAR: "existing_value"
                              GITHUB_EVENT_HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_no_fix_for_action_sinks() {
        let workflow_content = r#"
name: Test Template Injection - Actions
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Action with injection sink
        uses: actions/github-script@v7
        with:
          script: |
            console.log("${{ github.actor }}")
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_no_fix_for_action_sinks.yml",
            workflow_content,
            |_workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection
                assert!(!findings.is_empty());

                // But should not have fixes for action sinks (only run: steps get fixes)
                let findings_with_fixes: Vec<_> =
                    findings.iter().filter(|f| !f.fixes.is_empty()).collect();
                assert!(
                    findings_with_fixes.is_empty(),
                    "Expected no fixes for action injection sinks"
                );
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_multiple_expressions() {
        let workflow_content = r#"
name: Test Multiple Template Injections
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Multiple vulnerable expressions
        # All expressions are replaced and environment variables are created in a single comprehensive fix
        run: |
          echo "User: ${{ github.actor }}"
          echo "Ref: ${{ github.ref_name }}"
          echo "Commit: ${{ github.event.head_commit.message }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_multiple_expressions.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find multiple template injections
                assert!(!findings.is_empty());

                // Should have multiple findings
                assert!(
                    findings.len() >= 3,
                    "Expected at least 3 findings for 3 expressions"
                );

                // Our comprehensive fix approach now handles all expressions in a single operation:
                // All expressions in the script are replaced with environment variables,
                // and all corresponding environment variables are defined in the env section.
                let mut current_document = workflow.as_document().clone();
                let findings_with_fixes: Vec<_> =
                    findings.iter().filter(|f| !f.fixes.is_empty()).collect();

                assert!(
                    !findings_with_fixes.is_empty(),
                    "Expected at least one finding with a fix"
                );

                // Apply each fix in sequence
                for finding in findings_with_fixes {
                    if let Some(fix) = finding
                        .fixes
                        .iter()
                        .find(|f| f.title == "replace expression with environment variable")
                    {
                        if let Ok(new_document) = fix.apply(&current_document) {
                            current_document = new_document;
                        }
                    }
                }

                insta::assert_snapshot!(current_document.source(), @r#"

                name: Test Multiple Template Injections
                on: push
                jobs:
                  test:
                    runs-on: ubuntu-latest
                    steps:
                      - name: Multiple vulnerable expressions
                        # All expressions are replaced and environment variables are created in a single comprehensive fix
                        run: |
                          echo "User: ${GITHUB_ACTOR}"
                          echo "Ref: ${GITHUB_REF_NAME}"
                          echo "Commit: ${GITHUB_EVENT_HEAD_COMMIT_MESSAGE}"
                        env:
                          GITHUB_EVENT_HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }}
                "#);
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_duplicate_expressions() {
        let workflow_content = r#"
        name: Test Duplicate Template Injections
        on: push
        jobs:
          test:
            runs-on: ubuntu-latest
            steps:
              - name: Duplicate vulnerable expressions
                run: |
                  echo "User: ${{ github.actor }}"
                  echo "User again: ${{ github.actor }}"
                  echo "Ref: ${{ github.ref_name }}"
        "#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_duplicate_expressions.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection
                assert!(!findings.is_empty());

                // Should have at least one finding with a fix
                let findings_with_fixes: Vec<_> =
                    findings.iter().filter(|f| !f.fixes.is_empty()).collect();
                assert!(
                    !findings_with_fixes.is_empty(),
                    "Expected at least one finding with a fix"
                );

                // Apply each fix in sequence
                let mut current_document = workflow.as_document().clone();
                for finding in findings_with_fixes {
                    if let Some(fix) = finding
                        .fixes
                        .iter()
                        .find(|f| f.title == "replace expression with environment variable")
                    {
                        if let Ok(new_document) = fix.apply(&current_document) {
                            current_document = new_document;
                        }
                    }
                }

                insta::assert_snapshot!(current_document.source(), @r#"

                name: Test Duplicate Template Injections
                on: push
                jobs:
                  test:
                    runs-on: ubuntu-latest
                    steps:
                      - name: Duplicate vulnerable expressions
                        run: |
                          echo "User: ${GITHUB_ACTOR}"
                          echo "User again: ${GITHUB_ACTOR}"
                          echo "Ref: ${GITHUB_REF_NAME}"
                "#);
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_equivalent_expressions() {
        let workflow_content = r#"
        name: Test Duplicate Template Injections
        on: push
        jobs:
          test:
            runs-on: ubuntu-latest
            steps:
              - name: Equivalent vulnerable expressions
                run: |
                  echo "User: ${{ github.actor }}"
                  echo "User: ${{ env.GITHUB_ACTOR }}"
                  echo "User: ${{ env['GITHUB_ACTOR'] }}"
                  echo "User: ${{ env['github_actor'] }}"
        "#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_equivalent_expressions.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection
                assert!(!findings.is_empty());

                // Should have at least one finding with a fix
                let findings_with_fixes: Vec<_> =
                    findings.iter().filter(|f| !f.fixes.is_empty()).collect();

                // Apply each fix in sequence
                let mut current_document = workflow.as_document().clone();
                for finding in findings_with_fixes {
                    if let Some(fix) = finding
                        .fixes
                        .iter()
                        .find(|f| f.title == "replace expression with environment variable")
                    {
                        if let Ok(new_document) = fix.apply(&current_document) {
                            current_document = new_document;
                        }
                    }
                }

                insta::assert_snapshot!(current_document.source(), @r#"

                name: Test Duplicate Template Injections
                on: push
                jobs:
                  test:
                    runs-on: ubuntu-latest
                    steps:
                      - name: Equivalent vulnerable expressions
                        run: |
                          echo "User: ${GITHUB_ACTOR}"
                          echo "User: ${GITHUB_ACTOR}"
                          echo "User: ${GITHUB_ACTOR}"
                          echo "User: ${github_actor}"
                "#);
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_no_env_overcorrection() {
        // Testcase for #1052.
        let workflow_content = r#"
name: Test Duplicate Template Injections
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Equivalent vulnerable expressions
        run: |
          echo "User: ${{ env.THIS_IS_NOT_A_DEFAULT }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_no_env_overcorrection.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection
                assert!(!findings.is_empty());

                // Should have at least one finding with a fix
                let findings_with_fixes: Vec<_> =
                    findings.iter().filter(|f| !f.fixes.is_empty()).collect();
                assert!(
                    !findings_with_fixes.is_empty(),
                    "Expected at least one finding with a fix"
                );

                // Apply each fix in sequence
                let mut current_document = workflow.as_document().clone();
                for finding in findings_with_fixes {
                    if let Some(fix) = finding
                        .fixes
                        .iter()
                        .find(|f| f.title == "replace expression with environment variable")
                    {
                        if let Ok(new_document) = fix.apply(&current_document) {
                            current_document = new_document;
                        }
                    }
                }

                insta::assert_snapshot!(current_document.source(), @r#"

                name: Test Duplicate Template Injections
                on: push
                jobs:
                  test:
                    runs-on: ubuntu-latest
                    steps:
                      - name: Equivalent vulnerable expressions
                        run: |
                          echo "User: ${THIS_IS_NOT_A_DEFAULT}"
                "#);
            }
        );
    }

    #[test]
    fn test_capability_from_context() {
        assert!(matches!(
            Capability::from_context("github.event.workflow_run.triggering_actor.login"),
            Some(Capability::Arbitrary)
        ));
        assert!(matches!(
            Capability::from_context("github.event.answer.user.gists_url"),
            Some(Capability::Structured)
        ));
        assert!(matches!(
            Capability::from_context("github.event.type.is_enabled"),
            Some(Capability::Fixed)
        ));
        assert!(matches!(
            Capability::from_context("runner.arch"),
            Some(Capability::Fixed)
        ));
    }

    #[test]
    fn test_context_to_env_var() {
        for (ctx, expected) in [
            ("foo.bar", Some("FOO_BAR")),
            ("foo.bar[0]", Some("FOO_FIRST_BAR")),
            ("foo.bar[0][0]", Some("FOO_FIRST_FIRST_BAR")),
            ("foo.bar[1]", Some("FOO_SECOND_BAR")),
            ("foo.bar[2]", Some("FOO_THIRD_BAR")),
            ("foo.bar[3]", Some("FOO_4TH_BAR")),
            ("foo.bar[4]", Some("FOO_5TH_BAR")),
            ("foo.bar[*]", Some("FOO_ANY_BAR")),
            ("foo.bar.*", Some("FOO_ANY_BAR")),
            ("foo.bar.*.*", Some("FOO_ANY_ANY_BAR")),
            ("foo.bar.*[*]", Some("FOO_ANY_ANY_BAR")),
            ("foo.bar[*].*", Some("FOO_ANY_ANY_BAR")),
            ("foo.bar.baz", Some("FOO_BAR_BAZ")),
            ("foo.bar['baz']", Some("FOO_BAR_BAZ")),
            ("foo.bar['baz']['quux']", Some("FOO_BAR_BAZ_QUUX")),
            ("foo.bar['baz']['quux'].zap", Some("FOO_BAR_BAZ_QUUX_ZAP")),
            ("github.event.issue.title", Some("GITHUB_EVENT_ISSUE_TITLE")),
            // Calls not supported
            ("fromJSON(foo.bar).baz", None),
            // Computed indices not supported
            ("foo.bar[computed]", None),
            ("foo.bar[abc && def]", None),
            // env contexts should have the env prefix removed and preserve case
            ("env.FOO_BAR", Some("FOO_BAR")),
            ("env.foo_bar", Some("foo_bar")),
            ("ENV.foo_bar", Some("foo_bar")),
            ("ENV['foo_bar']", Some("foo_bar")),
            ("env.GITHUB_ACTOR", Some("GITHUB_ACTOR")),
            // FIXME: soundness hole
            (
                "foo.bar['oops all spaces']",
                Some("FOO_BAR_OOPS ALL SPACES"),
            ),
        ] {
            let expr = Expr::parse(ctx).unwrap();
            let Expr::Context(ctx) = &*expr else {
                panic!("Expected context expression, got: {expr:?}");
            };

            assert_eq!(
                TemplateInjection::context_to_env_var(ctx).as_deref(),
                expected
            );
        }
    }

    #[tokio::test]
    async fn test_template_injection_fix_bash_shell() {
        let workflow_content = r#"
name: Test Template Injection - Bash
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Vulnerable step with bash shell
        shell: bash
        run: echo "User is ${{ github.actor }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_bash_shell.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                assert!(!findings.is_empty());

                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(finding_with_fix.is_some());

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection - Bash
                    on: push
                    jobs:
                      test:
                        runs-on: ubuntu-latest
                        steps:
                          - name: Vulnerable step with bash shell
                            shell: bash
                            run: echo "User is ${GITHUB_ACTOR}"
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_bash_shell_full_path() {
        let workflow_content = r#"
name: Test Template Injection - Bash
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Vulnerable step with bash shell
        shell: /bin/bash
        run: echo "User is ${{ github.actor }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_bash_shell.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                assert!(!findings.is_empty());

                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(finding_with_fix.is_some());

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection - Bash
                    on: push
                    jobs:
                      test:
                        runs-on: ubuntu-latest
                        steps:
                          - name: Vulnerable step with bash shell
                            shell: /bin/bash
                            run: echo "User is ${GITHUB_ACTOR}"
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_cmd_shell() {
        let workflow_content = r#"
name: Test Template Injection - CMD
on: push
jobs:
  test:
    runs-on: windows-latest
    steps:
      - name: Vulnerable step with cmd shell
        shell: cmd
        run: echo User is ${{ github.actor }}
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_cmd_shell.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                assert!(!findings.is_empty());

                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(finding_with_fix.is_some());

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @"

                    name: Test Template Injection - CMD
                    on: push
                    jobs:
                      test:
                        runs-on: windows-latest
                        steps:
                          - name: Vulnerable step with cmd shell
                            shell: cmd
                            run: echo User is %GITHUB_ACTOR%
                    ");
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_pwsh_shell() {
        let workflow_content = r#"
name: Test Template Injection - PowerShell
on: push
jobs:
  test:
    runs-on: windows-latest
    steps:
      - name: Vulnerable step with pwsh shell
        shell: pwsh
        run: Write-Host "User is ${{ github.actor }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_pwsh_shell.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                assert!(!findings.is_empty());

                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(finding_with_fix.is_some());

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection - PowerShell
                    on: push
                    jobs:
                      test:
                        runs-on: windows-latest
                        steps:
                          - name: Vulnerable step with pwsh shell
                            shell: pwsh
                            run: Write-Host "User is $env:GITHUB_ACTOR"
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_default_shell_ubuntu() {
        let workflow_content = r#"
name: Test Template Injection - Default Shell Ubuntu
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Vulnerable step with default shell
        run: echo "User is ${{ github.actor }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_default_shell_ubuntu.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                assert!(!findings.is_empty());

                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(finding_with_fix.is_some());

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    // Ubuntu default shell is bash, so should use ${VAR} syntax
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection - Default Shell Ubuntu
                    on: push
                    jobs:
                      test:
                        runs-on: ubuntu-latest
                        steps:
                          - name: Vulnerable step with default shell
                            run: echo "User is ${GITHUB_ACTOR}"
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_default_shell_windows() {
        let workflow_content = r#"
name: Test Template Injection - Default Shell Windows
on: push
jobs:
  test:
    runs-on: windows-latest
    steps:
      - name: Vulnerable step with default shell
        run: Write-Host "User is ${{ github.actor }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_default_shell_windows.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                assert!(!findings.is_empty());

                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(finding_with_fix.is_some());

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    // Windows default shell is pwsh, so should use $env:VAR syntax
                    insta::assert_snapshot!(fixed_content.source(), @r#"

                    name: Test Template Injection - Default Shell Windows
                    on: push
                    jobs:
                      test:
                        runs-on: windows-latest
                        steps:
                          - name: Vulnerable step with default shell
                            run: Write-Host "User is $env:GITHUB_ACTOR"
                    "#);
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_fix_cmd_shell_with_custom_env() {
        let workflow_content = r#"
name: Test Template Injection - CMD with Custom Env
on: push
jobs:
  test:
    runs-on: windows-latest
    steps:
      - name: Vulnerable step with custom context
        shell: cmd
        run: echo PR title is ${{ github.event.pull_request.title }}
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_fix_cmd_shell_with_custom_env.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                assert!(!findings.is_empty());

                let finding_with_fix = findings.iter().find(|f| !f.fixes.is_empty());
                assert!(finding_with_fix.is_some());

                if let Some(finding) = finding_with_fix {
                    let fixed_content = apply_fix_by_title_for_snapshot(
                        workflow.as_document(),
                        finding,
                        "replace expression with environment variable",
                    );
                    insta::assert_snapshot!(fixed_content.source(), @"

                    name: Test Template Injection - CMD with Custom Env
                    on: push
                    jobs:
                      test:
                        runs-on: windows-latest
                        steps:
                          - name: Vulnerable step with custom context
                            shell: cmd
                            run: echo PR title is %GITHUB_EVENT_PULL_REQUEST_TITLE%
                            env:
                              GITHUB_EVENT_PULL_REQUEST_TITLE: ${{ github.event.pull_request.title }}
                    ");
                }
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_no_fix_unknown_shell() {
        let workflow_content = r#"
name: Test Template Injection - Unknown Shell
on: push
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Vulnerable step with unknown shell
        shell: fish
        run: echo "User is ${{ github.actor }}"
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_no_fix_unknown_shell.yml",
            workflow_content,
            |_workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find the vulnerability but not provide a fix for unknown shell
                assert!(!findings.is_empty());

                let findings_with_fixes: Vec<_> =
                    findings.iter().filter(|f| !f.fixes.is_empty()).collect();
                assert!(
                    findings_with_fixes.is_empty(),
                    "Expected no fixes for unknown shell type"
                );
            }
        );
    }

    #[tokio::test]
    async fn test_template_injection_unicode_in_script() {
        let workflow_content = r#"
name: Repro issue #1580
on:
  issue_comment:
    types: [created]
jobs:
  repro:
    runs-on: ubuntu-latest
    steps:
      - shell: bash
        run: |
          echo "✓ ${{ github.event.comment.body }}"

      - shell: bash
        run: echo ok
"#;

        test_workflow_audit!(
            TemplateInjection,
            "test_template_injection_unicode_in_script.yml",
            workflow_content,
            |workflow: &Workflow, findings: Vec<crate::finding::Finding>| {
                // Should find template injection for github.event.comment.body
                assert!(!findings.is_empty(), "Expected at least one finding");

                // Should have at least one finding with a fix
                let finding = findings
                    .iter()
                    .find(|f| !f.fixes.is_empty())
                    .expect("Should find at least one finding with fixes");

                let fixed_content = apply_fix_by_title_for_snapshot(
                    workflow.as_document(),
                    finding,
                    "replace expression with environment variable",
                );
                insta::assert_snapshot!(fixed_content.source(), @r#"

                name: Repro issue #1580
                on:
                  issue_comment:
                    types: [created]
                jobs:
                  repro:
                    runs-on: ubuntu-latest
                    steps:
                      - shell: bash
                        run: |
                          echo "✓ ${GITHUB_EVENT_COMMENT_BODY}"
                        env:
                          GITHUB_EVENT_COMMENT_BODY: ${{ github.event.comment.body }}

                      - shell: bash
                        run: echo ok
                "#);
            }
        );
    }
}