github-actions-maintainer 0.7.5

General-purpose GitHub Actions maintenance toolkit with secure workflow pinning
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
use std::{
    cmp::Reverse,
    fs,
    path::{Path, PathBuf},
    sync::LazyLock,
};

use anyhow::{Context, Result, bail};
use regex::Regex;
use walkdir::WalkDir;

use crate::model::{PinChange, ScriptType, ScriptUsage, WorkflowAction};

static USES_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^(?P<indent>\s*)(?P<list>-\s*)?uses:\s*(?P<uses>[^#\s]+)\s*(?:#\s*(?P<comment>.*))?$",
    )
    .expect("valid workflow uses regex")
});

static RUN_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?P<indent>\s*)(?P<list>-\s*)?run:\s*(?P<command>.*)$")
        .expect("valid workflow run regex")
});

static SHELL_LINE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*shell:\s*(?P<shell>[^#\s]+)").expect("valid workflow shell regex")
});

static YAML_KEY_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\s*(?:-\s*)?[A-Za-z_][A-Za-z0-9_-]*\s*:").expect("valid yaml key regex")
});

static BASH_USAGE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"(^|[\s;|&({\["'`$])(?:/usr/bin/env\s+)?(?:/bin/)?(?:bash|sh)\b|(^|[\s;|&({\["'`$])(?:\./|/|[A-Za-z0-9_.-]+/)[^\s;|&({\["'`$]+\.sh\b"#,
    )
    .expect("valid bash usage regex")
});

static PYTHON_USAGE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r#"(^|[\s;|&({\["'`$])(?:/usr/bin/env\s+)?python(?:3(?:\.\d+)?)?\b|(^|[\s;|&({\["'`$])(?:\./|/|[A-Za-z0-9_.-]+/)[^\s;|&({\["'`$]+\.py\b"#,
    )
    .expect("valid python usage regex")
});

#[derive(Debug, Clone, Eq, PartialEq)]
struct ParsedActionTarget {
    action_slug: String,
    owner: String,
    repository: String,
    version: String,
}

pub fn discover_workflow_files(repo_root: &Path, workflows_path: &Path) -> Result<Vec<PathBuf>> {
    let workflow_root = if workflows_path.is_absolute() {
        workflows_path.to_path_buf()
    } else {
        repo_root.join(workflows_path)
    };

    if !workflow_root.exists() {
        bail!("workflow directory '{}' does not exist", workflow_root.display());
    }

    let mut files = WalkDir::new(&workflow_root)
        .into_iter()
        .filter_map(std::result::Result::ok)
        .filter(|entry| entry.file_type().is_file())
        .filter(|entry| {
            matches!(entry.path().extension().and_then(|ext| ext.to_str()), Some("yml" | "yaml"))
        })
        .map(walkdir::DirEntry::into_path)
        .collect::<Vec<_>>();

    files.sort();
    Ok(files)
}

pub fn scan_workflow(path: &Path) -> Result<Vec<WorkflowAction>> {
    let content = fs::read_to_string(path)
        .with_context(|| format!("failed to read workflow '{}'", path.display()))?;

    let mut actions = Vec::new();

    for (index, line) in content.lines().enumerate() {
        let Some(captures) = USES_LINE_RE.captures(line) else {
            continue;
        };

        let uses_value = captures.name("uses").expect("uses capture is required").as_str();

        let Some(parsed) = parse_action_target(uses_value) else {
            continue;
        };

        let indentation =
            captures.name("indent").map_or(String::new(), |capture| capture.as_str().to_owned());
        let list_prefix =
            captures.name("list").map_or(String::new(), |capture| capture.as_str().to_owned());
        let inline_comment = captures.name("comment").map(|capture| capture.as_str().to_owned());

        actions.push(WorkflowAction {
            file: path.to_path_buf(),
            line_number: index + 1,
            indentation,
            list_prefix,
            action_slug: parsed.action_slug,
            owner: parsed.owner,
            repository: parsed.repository,
            version: parsed.version,
            inline_comment,
            original_line: line.to_owned(),
        });
    }

    Ok(actions)
}

pub fn scan_workflow_scripts(path: &Path) -> Result<Vec<ScriptUsage>> {
    let content = fs::read_to_string(path)
        .with_context(|| format!("failed to read workflow '{}'", path.display()))?;

    Ok(scan_workflow_script_content(path, &content))
}

fn scan_workflow_script_content(path: &Path, content: &str) -> Vec<ScriptUsage> {
    let mut usages = Vec::new();
    let mut run_block_indent = None;

    for (index, line) in content.lines().enumerate() {
        let line_number = index + 1;
        let mut candidates = Vec::new();

        if let Some(captures) = RUN_LINE_RE.captures(line) {
            let indent =
                captures.name("indent").map_or(0, |capture| capture.as_str().chars().count());
            let command = captures.name("command").expect("command capture is required").as_str();
            let trimmed = command.trim();
            if is_block_scalar(trimmed) {
                run_block_indent = Some(indent);
            } else if !trimmed.is_empty() {
                run_block_indent = None;
                candidates.push(trimmed.to_owned());
            }
        } else if let Some(indent) = run_block_indent {
            if line.trim().is_empty() {
                continue;
            }

            let current_indent = leading_spaces(line);
            if current_indent <= indent && YAML_KEY_RE.is_match(line) {
                run_block_indent = None;
            } else {
                candidates.push(line.trim().to_owned());
            }
        }

        for command in candidates {
            push_script_usages(path, line_number, &command, line, &mut usages);
        }

        if let Some(captures) = SHELL_LINE_RE.captures(line) {
            let shell = captures.name("shell").expect("shell capture is required").as_str();
            push_shell_usage(path, line_number, shell, line, &mut usages);
        }
    }

    usages
}

fn push_script_usages(
    path: &Path,
    line_number: usize,
    command: &str,
    context: &str,
    usages: &mut Vec<ScriptUsage>,
) {
    if BASH_USAGE_RE.is_match(command) {
        usages.push(ScriptUsage {
            file: path.to_path_buf(),
            line_number,
            script_type: ScriptType::Bash,
            command: command.to_owned(),
            context: context.to_owned(),
        });
    }

    if PYTHON_USAGE_RE.is_match(command) {
        usages.push(ScriptUsage {
            file: path.to_path_buf(),
            line_number,
            script_type: ScriptType::Python,
            command: command.to_owned(),
            context: context.to_owned(),
        });
    }
}

fn push_shell_usage(
    path: &Path,
    line_number: usize,
    shell: &str,
    context: &str,
    usages: &mut Vec<ScriptUsage>,
) {
    let normalized =
        shell.trim_matches(|character| matches!(character, '"' | '\'')).to_ascii_lowercase();
    let shell_name = normalized.split_whitespace().next().unwrap_or_default();
    let script_type = if shell_name.starts_with("python") {
        Some(ScriptType::Python)
    } else if matches!(shell_name, "bash" | "sh")
        || shell_name.ends_with("/bash")
        || shell_name.ends_with("/sh")
    {
        Some(ScriptType::Bash)
    } else {
        None
    };

    if let Some(script_type) = script_type {
        usages.push(ScriptUsage {
            file: path.to_path_buf(),
            line_number,
            script_type,
            command: shell.to_owned(),
            context: context.to_owned(),
        });
    }
}

fn is_block_scalar(value: &str) -> bool {
    matches!(value, "|" | ">" | "|-" | ">-" | "|+" | ">+")
}

fn leading_spaces(value: &str) -> usize {
    value.chars().take_while(|character| *character == ' ').count()
}

pub fn apply_changes(changes: &[PinChange]) -> Result<()> {
    let mut by_file = changes.iter().fold(
        std::collections::BTreeMap::<&Path, Vec<&PinChange>>::new(),
        |mut grouped, change| {
            grouped.entry(change.file.as_path()).or_default().push(change);
            grouped
        },
    );

    for (path, file_changes) in &mut by_file {
        let content = fs::read_to_string(path)
            .with_context(|| format!("failed to read workflow '{}'", path.display()))?;
        let rewritten = apply_changes_to_content(&content, file_changes)?;

        fs::write(path, rewritten)
            .with_context(|| format!("failed to write workflow '{}'", path.display()))?;
    }

    Ok(())
}

pub fn apply_changes_to_content(content: &str, changes: &[&PinChange]) -> Result<String> {
    let mut lines = content.lines().map(str::to_owned).collect::<Vec<_>>();
    let mut sorted_changes = changes.to_vec();

    sorted_changes.sort_by_key(|change| Reverse(change.line_number));

    for change in sorted_changes {
        let line_index = change.line_number - 1;
        if line_index >= lines.len() {
            bail!("cannot rewrite content: line {} is outside the file", change.line_number);
        }

        lines[line_index].clone_from(&change.rewritten_line);
    }

    let rewritten =
        if content.ends_with('\n') { format!("{}\n", lines.join("\n")) } else { lines.join("\n") };

    Ok(rewritten)
}

fn parse_action_target(raw: &str) -> Option<ParsedActionTarget> {
    if raw.contains("${{")
        || raw.starts_with("./")
        || raw.starts_with("../")
        || raw.starts_with('/')
        || raw.starts_with("docker://")
    {
        return None;
    }

    let (action_slug, version) = raw.rsplit_once('@')?;
    let parts = action_slug.split('/').collect::<Vec<_>>();

    if parts.len() < 2 {
        return None;
    }

    Some(ParsedActionTarget {
        action_slug: action_slug.to_owned(),
        owner: parts[0].to_owned(),
        repository: parts[1].to_owned(),
        version: version.to_owned(),
    })
}

#[cfg(test)]
mod tests {
    use std::{fs, path::Path};

    use tempfile::tempdir;

    use super::{apply_changes, discover_workflow_files, scan_workflow, scan_workflow_scripts};
    use crate::model::{PinChange, ScriptType};

    #[test]
    fn scan_workflow_collects_github_actions() {
        let temp_dir = tempdir().expect("tempdir");
        let workflow = temp_dir.path().join("ci.yml");
        fs::write(
            &workflow,
            r"jobs:
  lint:
    steps:
      - uses: actions/checkout@v4
      - uses: github/codeql-action/init@v3 # security
      - uses: ./local-action
      - uses: docker://ghcr.io/acme/tool:latest
      - uses: ${{ matrix.action }}
",
        )
        .expect("write workflow");

        let actions = scan_workflow(&workflow).expect("scan workflow");

        assert_eq!(actions.len(), 2);
        assert_eq!(actions[0].action_slug, "actions/checkout");
        assert_eq!(actions[0].version, "v4");
        assert_eq!(actions[1].action_slug, "github/codeql-action/init");
        assert_eq!(actions[1].inline_comment.as_deref(), Some("security"));
    }

    #[test]
    fn discover_workflow_files_only_returns_yaml() {
        let temp_dir = tempdir().expect("tempdir");
        let workflow_dir = temp_dir.path().join(".github").join("workflows");
        fs::create_dir_all(&workflow_dir).expect("create workflow directory");
        fs::write(workflow_dir.join("ci.yml"), "name: CI\n").expect("write yml workflow");
        fs::write(workflow_dir.join("release.yaml"), "name: Release\n")
            .expect("write yaml workflow");
        fs::write(workflow_dir.join("notes.txt"), "skip\n").expect("write non-workflow");

        let files = discover_workflow_files(temp_dir.path(), Path::new(".github/workflows"))
            .expect("discover workflows");

        assert_eq!(files.len(), 2);
    }

    #[test]
    fn scan_workflow_scripts_collects_single_line_and_block_usage() {
        let temp_dir = tempdir().expect("tempdir");
        let workflow = temp_dir.path().join("ci.yml");
        fs::write(
            &workflow,
            r#"jobs:
  lint:
    steps:
      - run: python3 scripts/check.py
      - run: |
          ./bin/bootstrap.sh
          severity="$(python - <<'PY'
          print('high')
          PY
      - run: cargo test
        shell: bash
"#,
        )
        .expect("write workflow");

        let usages = scan_workflow_scripts(&workflow).expect("scan scripts");

        assert_eq!(usages.len(), 4);
        assert_eq!(usages[0].script_type, ScriptType::Python);
        assert_eq!(usages[1].script_type, ScriptType::Bash);
        assert_eq!(usages[2].script_type, ScriptType::Python);
        assert_eq!(usages[3].script_type, ScriptType::Bash);
    }

    #[test]
    fn scan_workflow_scripts_detects_shell_python() {
        let temp_dir = tempdir().expect("tempdir");
        let workflow = temp_dir.path().join("ci.yml");
        fs::write(
            &workflow,
            r"jobs:
  lint:
    steps:
      - run: print('hello')
        shell: python
",
        )
        .expect("write workflow");

        let usages = scan_workflow_scripts(&workflow).expect("scan scripts");

        assert_eq!(usages.len(), 1);
        assert_eq!(usages[0].script_type, ScriptType::Python);
        assert_eq!(usages[0].line_number, 5);
    }

    #[test]
    fn apply_changes_rewrites_target_lines() {
        let temp_dir = tempdir().expect("tempdir");
        let workflow = temp_dir.path().join("ci.yml");
        fs::write(&workflow, "steps:\n  - uses: actions/checkout@v4\n  - uses: actions/cache@v4\n")
            .expect("write workflow");

        apply_changes(&[
            PinChange {
                file: workflow.clone(),
                line_number: 2,
                action_slug: "actions/checkout".into(),
                from_version: "v4".into(),
                to_sha: "0123456789abcdef0123456789abcdef01234567".into(),
                original_line: "  - uses: actions/checkout@v4".into(),
                rewritten_line:
                    "  - uses: actions/checkout@0123456789abcdef0123456789abcdef01234567  # v4"
                        .into(),
            },
            PinChange {
                file: workflow.clone(),
                line_number: 3,
                action_slug: "actions/cache".into(),
                from_version: "v4".into(),
                to_sha: "89abcdef0123456789abcdef0123456789abcdef".into(),
                original_line: "  - uses: actions/cache@v4".into(),
                rewritten_line:
                    "  - uses: actions/cache@89abcdef0123456789abcdef0123456789abcdef  # v4".into(),
            },
        ])
        .expect("apply changes");

        let updated = fs::read_to_string(&workflow).expect("read rewritten workflow");
        assert!(
            updated.contains(
                "  - uses: actions/checkout@0123456789abcdef0123456789abcdef01234567  # v4"
            )
        );
        assert!(
            updated
                .contains("  - uses: actions/cache@89abcdef0123456789abcdef0123456789abcdef  # v4")
        );
    }
}