pinner 0.0.10

Secure CI/CD workflows by pinning mutable tags to immutable SHA-1 hashes. A high-performance Rust CLI that preserves YAML formatting and comments. Supports GitHub, GitLab, Bitbucket, Forgejo, and Docker image 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
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
use crate::core::UpdateTask;
use crate::core::{CiProvider, DependencyName};
use crate::error::PinnerError;
use std::path::Path;
use std::sync::LazyLock;
use tree_sitter::{Node, Point, Query, QueryCursor, StreamingIterator};

impl CiProvider {
    /// Detects the CI provider based on the file path.
    ///
    /// This heuristic matches standard CI/CD directory structures (e.g., `.github/workflows`).
    pub fn from_path(path: &Path) -> Self {
        let path_str = path.to_string_lossy();
        let mappings = [
            (".github/workflows", CiProvider::GitHub),
            (".forgejo/workflows", CiProvider::Forgejo),
            (".gitea/workflows", CiProvider::Gitea),
            (".gitlab-ci", CiProvider::GitLab),
            ("bitbucket-pipelines", CiProvider::Bitbucket),
            (".circleci", CiProvider::CircleCI),
            ("azure-pipelines", CiProvider::AzureDevOps),
            ("buildspec", CiProvider::AwsCodeBuild),
        ];

        for (pattern, provider) in mappings {
            if path_str.contains(pattern) {
                return provider;
            }
        }
        CiProvider::Unknown
    }

    /// Returns true if the given YAML key represents a dependency for this provider.
    ///
    /// For example, GitHub Actions uses the `uses` key, while Bitbucket Pipelines uses `pipe`.
    pub fn supports_key(&self, key: &str) -> bool {
        match self {
            CiProvider::GitHub | CiProvider::Forgejo | CiProvider::Gitea => {
                matches!(key, "uses" | "image")
            }
            CiProvider::GitLab => matches!(key, "include" | "image" | "ref"),
            CiProvider::Bitbucket => matches!(key, "pipe" | "image"),
            // CircleCI support includes Docker Images (e.g. cimg/*) and Orbs.
            CiProvider::CircleCI => matches!(key, "image" | "orbs"),
            CiProvider::AzureDevOps => matches!(key, "task" | "template" | "image"),
            CiProvider::AwsCodeBuild => matches!(key, "image"),
            CiProvider::Unknown => true,
        }
    }
}

/// Tree-sitter query to identify potential dependency nodes in YAML.
///
/// It targets common keys like `uses`, `image`, `pipe`, etc., and also captures
/// the specific structure of CircleCI Orbs. Comments are captured separately
/// to associate them with the preceding value if they appear on the same line.
static USES_QUERY: LazyLock<Result<Query, String>> = LazyLock::new(|| {
    Query::new(
        &tree_sitter_yaml::LANGUAGE.into(),
        r#"
        ; Capture standard key-value pairs where the key matches our known dependency triggers.
        (block_mapping_pair
          key: [
            (flow_node (plain_scalar (string_scalar) @key))
            (plain_scalar (string_scalar) @key)
          ]
          value: (_) @value
          (#match? @key "^(uses|pipe|image|include|ref|task|template)$"))

        ; Capture CircleCI Orbs which have a nested structure: orbs -> name -> value.
        (block_mapping_pair
          key: [
            (flow_node (plain_scalar (string_scalar) @key))
            (plain_scalar (string_scalar) @key)
          ]
          (#eq? @key "orbs")
          value: (block_node
            (block_mapping
              (block_mapping_pair
                value: [
                  (flow_node (plain_scalar (string_scalar) @value))
                  (plain_scalar (string_scalar) @value)
                ]
              )
            )
          )
        )

        ; Capture comments to associate them with the value node above them.
        (comment) @comment
        "#,
    )
    .map_err(|e| format!("Failed to create tree-sitter query: {:?}", e))
});

/// Removes surrounding quotes from a string.
fn unquote(s: &str) -> String {
    let s = s.trim();
    if ((s.starts_with('\'') && s.ends_with('\'')) || (s.starts_with('"') && s.ends_with('"')))
        && s.len() >= 2
    {
        return s[1..s.len() - 1].to_string();
    }
    s.to_string()
}

/// Resolves the GitLab project name for an `include` entry.
///
/// In GitLab CI, an `include` can specify a `project` and a `ref`.
/// This function walks the AST to find the sibling `project` key for a given `ref` value.
fn resolve_gitlab_project(v_node: Node, content: &[u8]) -> Option<String> {
    let parent_pair = v_node.parent()?;
    let mapping = parent_pair.parent()?;
    let mut cursor = mapping.walk();
    for child in mapping.children(&mut cursor) {
        if child.kind() == "block_mapping_pair" {
            if let Some(k_node) = child.child_by_field_name("key") {
                if k_node.utf8_text(content).unwrap_or("") == "project" {
                    if let Some(v_node) = child.child_by_field_name("value") {
                        return Some(unquote(v_node.utf8_text(content).unwrap_or("")));
                    }
                }
            }
        }
    }
    None
}

/// Identifies all dependency update tasks within a YAML AST node.
///
/// This function uses tree-sitter queries to find relevant keys (like `uses`, `image`, `orbs`)
/// and maps them to `UpdateTask` domain models. It handles provider-specific logic
/// and associates end-of-line comments with their respective values.
pub fn find_tasks(
    path: &Path,
    node: Node,
    content: &[u8],
    ignore_list: &[String],
) -> Result<Vec<UpdateTask>, PinnerError> {
    let mut results = Vec::new();
    let query = USES_QUERY
        .as_ref()
        .map_err(|e| PinnerError::Parse(e.clone()))?;

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, node, content);

    let key_idx = query
        .capture_index_for_name("key")
        .ok_or_else(|| PinnerError::Parse("key capture missing".to_string()))?;
    let value_idx = query
        .capture_index_for_name("value")
        .ok_or_else(|| PinnerError::Parse("value capture missing".to_string()))?;
    let comment_idx = query.capture_index_for_name("comment");

    let provider = CiProvider::from_path(path);
    let ctx = FileContext {
        path,
        provider,
        ignore_list,
    };

    // We keep track of the last value found to associate it with a potential comment
    // on the same line. Because tree-sitter queries can return captures in sequence,
    // we "buffer" the value until we see if a comment follows it on the same line.
    let mut last_value: Option<(usize, usize, String, Point, String)> = None;

    while let Some(m) = matches.next() {
        let mut current_key = String::new();
        for cap in m.captures {
            if cap.index == key_idx {
                current_key = cap.node.utf8_text(content).unwrap_or("").to_string();
            } else if cap.index == value_idx {
                if !provider.supports_key(&current_key) {
                    continue;
                }

                // If we had a buffered value from a previous match that didn't have a same-line comment,
                // push it now.
                if let Some((start, end, value, pos, key)) = last_value.take() {
                    if let Some(task) = create_task(
                        ctx,
                        Position {
                            start,
                            end,
                            line: pos.row + 1,
                            column: pos.column + 1,
                        },
                        value,
                        None,
                        key,
                    ) {
                        results.push(task);
                    }
                }

                let v_node = cap.node;
                let mut val = unquote(v_node.utf8_text(content).unwrap_or(""));

                // GitLab special case: combine 'project' and 'ref' into a single virtual dependency.
                if current_key == "ref" {
                    if let Some(project) = resolve_gitlab_project(v_node, content) {
                        val = format!("{}@{}", project, val);
                    }
                }

                last_value = Some((
                    v_node.start_byte(),
                    v_node.end_byte(),
                    val,
                    v_node.start_position(),
                    current_key.clone(),
                ));
            } else if Some(cap.index) == comment_idx {
                if let Some((start, end, value, pos, key)) = last_value.take() {
                    let comment_node = cap.node;
                    // Check if the comment is on the same line as the buffered value.
                    if comment_node.start_position().row == pos.row {
                        let comment_text =
                            comment_node.utf8_text(content).unwrap_or("").to_string();
                        if let Some(task) = create_task(
                            ctx,
                            Position {
                                start,
                                end,
                                line: pos.row + 1,
                                column: pos.column + 1,
                            },
                            value,
                            Some(comment_text),
                            key,
                        ) {
                            results.push(task);
                        }
                    } else {
                        // The comment is on a different line, so the buffered value has no comment.
                        if let Some(task) = create_task(
                            ctx,
                            Position {
                                start,
                                end,
                                line: pos.row + 1,
                                column: pos.column + 1,
                            },
                            value,
                            None,
                            key,
                        ) {
                            results.push(task);
                        }
                    }
                }
            }
        }
    }

    if let Some((start, end, value, pos, key)) = last_value {
        if let Some(task) = create_task(
            ctx,
            Position {
                start,
                end,
                line: pos.row + 1,
                column: pos.column + 1,
            },
            value,
            None,
            key,
        ) {
            results.push(task);
        }
    }
    Ok(results)
}

#[derive(Clone, Copy)]
struct FileContext<'a> {
    path: &'a Path,
    provider: CiProvider,
    ignore_list: &'a [String],
}

struct Position {
    start: usize,
    end: usize,
    line: usize,
    column: usize,
}

fn create_task(
    ctx: FileContext,
    pos: Position,
    value: String,
    comment: Option<String>,
    key: String,
) -> Option<UpdateTask> {
    if key == "include" || key == "project" {
        return None;
    }
    if value.starts_with("./") {
        return None;
    }

    let (action_part, tag) = if let Some((a, t)) = value.split_once('@') {
        (a, Some(t))
    } else if value.starts_with("docker://") && value.contains(':') {
        if let Some(last_colon) = value.rfind(':') {
            (&value[..last_colon], Some(&value[last_colon + 1..]))
        } else {
            (value.as_str(), None)
        }
    } else if let Some((a, t)) = value.split_once(':') {
        (a, Some(t))
    } else {
        (value.as_str(), None)
    };

    let action = DependencyName::from(action_part);

    if ctx
        .ignore_list
        .iter()
        .any(|pattern| action.0.contains(pattern))
    {
        return None;
    }

    Some(UpdateTask {
        path: ctx.path.to_path_buf(),
        start: pos.start,
        end: pos.end,
        line: pos.line,
        column: pos.column,
        action,
        current_tag: tag.map(|s| s.to_string()),
        comment,
        key,
        provider: ctx.provider,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use tree_sitter::Parser as TSParser;

    fn parse_yaml(content: &str) -> (tree_sitter::Tree, Vec<u8>) {
        let mut parser = TSParser::new();
        parser
            .set_language(&tree_sitter_yaml::LANGUAGE.into())
            .expect("Error loading YAML grammar");
        let tree = parser.parse(content, None).expect("Error parsing YAML");
        (tree, content.as_bytes().to_vec())
    }

    #[test]
    fn test_find_tasks_github() {
        let yaml = "uses: actions/checkout@v3";
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].action.0, "actions/checkout");
        assert_eq!(results[0].current_tag.as_deref(), Some("v3"));
        assert_eq!(results[0].key, "uses");
    }

    #[test]
    fn test_find_tasks_with_quotes() {
        let yaml = "uses: \"actions/checkout@v3\"";
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].action.0, "actions/checkout");
        assert_eq!(results[0].current_tag.as_deref(), Some("v3"));
    }

    #[test]
    fn test_find_tasks_with_comment() {
        let yaml = "uses: actions/checkout@hash # v3";
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].action.0, "actions/checkout");
        assert_eq!(results[0].current_tag.as_deref(), Some("hash"));
        assert_eq!(results[0].comment, Some("# v3".to_string()));
    }

    #[test]
    fn test_find_tasks_circleci_orbs() {
        let yaml = r#"
version: 2.1
orbs:
  node: circleci/node@5.0.0
  slack: circleci/slack@4.1.0
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".circleci/config.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 2);

        let node_orb = results
            .iter()
            .find(|r| r.action.0 == "circleci/node")
            .unwrap();
        assert_eq!(node_orb.key, "orbs");
        assert_eq!(node_orb.current_tag.as_deref(), Some("5.0.0"));

        let slack_orb = results
            .iter()
            .find(|r| r.action.0 == "circleci/slack")
            .unwrap();
        assert_eq!(slack_orb.key, "orbs");
        assert_eq!(slack_orb.current_tag.as_deref(), Some("4.1.0"));
    }

    #[test]
    fn test_find_other_keys() {
        let yaml = r#"
image: alpine:latest
pipe: sonarsource/sonarcloud-scan:1.4.0
include: other-template.yml
orbs:
  node: circleci/node@5.0.0
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new("other.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        let keys: Vec<String> = results.iter().map(|r| r.key.clone()).collect();
        assert!(keys.contains(&"image".to_string()));
        assert!(keys.contains(&"pipe".to_string()));
    }

    fn find_node_with_text<'a>(
        node: tree_sitter::Node<'a>,
        text: &str,
        content: &[u8],
    ) -> Option<tree_sitter::Node<'a>> {
        if node.utf8_text(content).unwrap_or("") == text {
            return Some(node);
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if let Some(found) = find_node_with_text(child, text, content) {
                return Some(found);
            }
        }
        None
    }

    #[test]
    fn test_resolve_gitlab_project_success() {
        let yaml = r#"
include:
  - project: 'my-group/my-project'
    ref: 'v1.0.0'
"#;
        let (tree, content) = parse_yaml(yaml);
        let node = find_node_with_text(tree.root_node(), "'v1.0.0'", &content).unwrap();
        let project = resolve_gitlab_project(node, &content);
        assert_eq!(project, Some("my-group/my-project".to_string()));
    }

    #[test]
    fn test_gitlab_ref_project() {
        let yaml = r#"
include:
  - project: 'my-group/my-project'
    ref: 'v1.0.0'
    file: '/templates/.gitlab-ci.yml'
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".gitlab-ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        let ref_node = results.iter().find(|r| r.key == "ref").unwrap();
        assert_eq!(ref_node.action.0, "my-group/my-project");
        assert_eq!(ref_node.current_tag.as_deref(), Some("v1.0.0"));
    }

    #[test]
    fn test_github_ignore_include() {
        let yaml = r#"
strategy:
  matrix:
    include:
      - os: ubuntu-latest
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert!(results.is_empty());
    }

    #[test]
    fn test_unquote_exhaustive() {
        assert_eq!(unquote("'v1'"), "v1");
        assert_eq!(unquote("\"v2\""), "v2");
        assert_eq!(unquote("v3"), "v3");
        assert_eq!(unquote("'"), "'");
        assert_eq!(unquote("\""), "\"");
        assert_eq!(unquote("''"), "");
        assert_eq!(unquote("  'v4'  "), "v4");
    }

    #[test]
    fn test_ci_provider_from_path() {
        assert_eq!(
            CiProvider::from_path(Path::new(".github/workflows/ci.yml")),
            CiProvider::GitHub
        );
        assert_eq!(
            CiProvider::from_path(Path::new(".gitlab-ci.yml")),
            CiProvider::GitLab
        );
        assert_eq!(
            CiProvider::from_path(Path::new("bitbucket-pipelines.yml")),
            CiProvider::Bitbucket
        );
        assert_eq!(
            CiProvider::from_path(Path::new(".circleci/config.yml")),
            CiProvider::CircleCI
        );
    }

    #[test]
    fn test_ci_provider_supports_key() {
        let github = CiProvider::GitHub;
        assert!(github.supports_key("uses"));
        assert!(github.supports_key("image"));
        assert!(!github.supports_key("pipe"));

        let gitlab = CiProvider::GitLab;
        assert!(gitlab.supports_key("include"));
        assert!(gitlab.supports_key("ref"));
        assert!(!gitlab.supports_key("uses"));
    }

    #[test]
    fn test_find_tasks_azure_devops() {
        let yaml = r#"
steps:
- task: NodeTool@0
  inputs:
    versionSpec: '16.x'
- template: templates/build.yml@templates-repo
  parameters:
    buildConfig: 'Release'
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new("azure-pipelines.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 2);

        let task = results.iter().find(|r| r.key == "task").unwrap();
        assert_eq!(task.action.0, "NodeTool");
        assert_eq!(task.current_tag.as_deref(), Some("0"));

        let template = results.iter().find(|r| r.key == "template").unwrap();
        assert_eq!(template.action.0, "templates/build.yml");
        assert_eq!(template.current_tag.as_deref(), Some("templates-repo"));
    }

    #[test]
    fn test_find_tasks_aws_codebuild() {
        let yaml = r#"
version: 0.2
phases:
  install:
    runtime-versions:
      nodejs: 16
build:
  commands:
    - echo "Building..."
image: aws/codebuild/standard:5.0
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new("buildspec.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].action.0, "aws/codebuild/standard");
        assert_eq!(results[0].current_tag.as_deref(), Some("5.0"));
    }

    #[test]
    fn test_find_tasks_multi_document() {
        let yaml = r#"
uses: actions/checkout@v1
---
uses: actions/setup-node@v2
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 2);
        assert_eq!(results[0].action.0, "actions/checkout");
        assert_eq!(results[1].action.0, "actions/setup-node");
    }

    #[test]
    fn test_find_tasks_malformed_yaml() {
        // Tree-sitter is resilient and should still find the dependency in partial/broken YAML
        let yaml = r#"
jobs:
  build:
    steps:
      - uses: actions/checkout@v3
    invalid_yaml_here: [
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].action.0, "actions/checkout");
    }

    #[test]
    fn test_find_tasks_empty_yaml() {
        let yaml = "";
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert!(results.is_empty());
    }

    #[test]
    fn test_find_tasks_complex_nesting() {
        let yaml = r#"
jobs:
  build:
    steps:
      - name: Checkout
        uses: actions/checkout@v3
      - name: Nested
        run: |
          echo "hello"
        env:
          IMAGE: "not-a-dependency"
      - image: redis:6.0 # This is a dependency
"#;
        let (tree, content) = parse_yaml(yaml);
        let path = Path::new(".github/workflows/ci.yml");
        let results = find_tasks(path, tree.root_node(), &content, &[]).unwrap();

        assert_eq!(results.len(), 2);
        assert!(results.iter().any(|r| r.action.0 == "actions/checkout"));
        assert!(results.iter().any(|r| r.action.0 == "redis"));
    }
}