pinner 0.0.13

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
//! CLI argument parsing and command definitions.
//!
//! This module uses `clap` to define the command-line interface for Pinner.
//! It includes the main [`Cli`] struct and the [`Commands`] enum for subcommands.

use clap::{Parser, Subcommand, ValueEnum};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

/// Strategy for upgrading actions to newer versions.
///
/// It determines which tags are considered "newer" during an upgrade operation.
#[derive(ValueEnum, Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum UpgradeStrategy {
    /// Upgrade to the latest available version (default).
    Latest,
    /// Upgrade only within the current major version (e.g., v1.x.x -> v1.y.y).
    /// This follows semver and avoids breaking changes.
    Major,
    /// Upgrade only within the current minor version (e.g., v1.1.x -> v1.1.y).
    /// This is the most conservative upgrade strategy.
    Minor,
    /// Upgrade to the latest commit on the default branch (ignoring tags).
    Commit,
}

/// Format for the output results.
#[derive(ValueEnum, Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
    /// Standard text output with colors and diffs (default).
    #[default]
    Text,
    /// Machine-readable JSON format.
    Json,
    /// Markdown table format suitable for PR comments.
    Markdown,
    /// GitHub Actions workflow command annotations.
    Github,
    /// JUnit XML test results format.
    Junit,
}

/// The main command-line interface for Pinner.
#[derive(Parser, Clone)]
#[command(version, about, long_about = None)]
pub struct Cli {
    /// Subcommand to execute.
    #[command(subcommand)]
    pub command: Commands,
    /// Workflow files or directories to process.
    #[arg(
        short,
        long,
        global = true,
        help = "Workflow files or directories to process"
    )]
    pub workflows: Vec<PathBuf>,
    /// Automatically confirm all replacements without prompting.
    #[arg(short, long, global = true)]
    pub yes: bool,
    /// Suppress all console output except for critical errors.
    #[arg(short, long, global = true, conflicts_with = "verbose")]
    pub quiet: bool,
    /// Print verbose output for debugging.
    #[arg(short, long, global = true, conflicts_with = "quiet")]
    pub verbose: bool,
    /// Disable persistent disk caching.
    #[arg(
        long,
        global = true,
        env = "PINNER_NO_CACHE",
        conflicts_with = "cache_ttl"
    )]
    pub no_cache: bool,
    /// Cache TTL in seconds (default: 3600).
    #[arg(long, global = true, env = "PINNER_CACHE_TTL")]
    pub cache_ttl: Option<u64>,
    /// Force offline mode, preventing any network requests.
    #[arg(long, global = true, env = "PINNER_OFFLINE")]
    pub offline: bool,

    /// Print what would be changed without actually modifying any files.

    #[arg(short, long, global = true)]
    pub dry_run: bool,
    /// GitHub API Token for authentication.
    #[arg(long, global = true, env = "GITHUB_TOKEN")]
    pub github_token: Option<String>,
    /// Bitbucket API Token for authentication.
    #[arg(long, global = true, env = "BITBUCKET_TOKEN")]
    pub bitbucket_token: Option<String>,
    /// GitLab API Token for authentication.
    #[arg(long, global = true, env = "GITLAB_TOKEN")]
    pub gitlab_token: Option<String>,
    /// Forgejo/Gitea API Token for authentication.
    #[arg(long, global = true, env = "FORGEJO_TOKEN")]
    pub forgejo_token: Option<String>,
    /// CircleCI API Token for authentication.
    #[arg(long, global = true, env = "CIRCLECI_TOKEN")]
    pub circleci_token: Option<String>,
    /// Output results in the specified format.
    #[arg(long, global = true, value_enum, default_value_t = OutputFormat::Text)]
    pub format: OutputFormat,
    /// Base URL for the GitHub API (defaults to public GitHub).
    #[arg(
        long,
        global = true,
        env = "PINNER_GITHUB_URL",
        default_value = "https://api.github.com"
    )]
    pub github_url: String,
    /// Base URL for the Bitbucket API.
    #[arg(
        long,
        global = true,
        env = "PINNER_BITBUCKET_URL",
        default_value = "https://api.bitbucket.org/2.0"
    )]
    pub bitbucket_url: String,
    /// Base URL for the GitLab API.
    #[arg(
        long,
        global = true,
        env = "PINNER_GITLAB_URL",
        default_value = "https://gitlab.com"
    )]
    pub gitlab_url: String,
    /// Base URL for the Forgejo/Gitea API.
    #[arg(
        long,
        global = true,
        env = "PINNER_FORGEJO_URL",
        default_value = "https://codeberg.org"
    )]
    pub forgejo_url: String,
    /// Base URL for the CircleCI GraphQL API.
    #[arg(
        long,
        global = true,
        env = "PINNER_CIRCLECI_URL",
        default_value = "https://circleci.com/graphql-unstable"
    )]
    pub circleci_url: String,

    /// Number of concurrent API requests to make.
    #[arg(long, global = true, env = "PINNER_CONCURRENCY")]
    pub concurrency: Option<usize>,
    /// Actions or images to ignore (e.g., "actions/checkout").
    #[arg(long, global = true, env = "PINNER_IGNORE", value_delimiter = ',')]
    pub ignore: Vec<String>,

    /// Username for OCI registry authentication.
    #[arg(
        long,
        global = true,
        env = "PINNER_OCI_USERNAME",
        requires = "oci_password"
    )]
    pub oci_username: Option<String>,
    /// Password for OCI registry authentication.
    #[arg(
        long,
        global = true,
        env = "PINNER_OCI_PASSWORD",
        requires = "oci_username"
    )]
    pub oci_password: Option<String>,
}

impl Cli {
    /// Returns true if the quiet flag is set.
    pub fn quiet(&self) -> bool {
        self.quiet
    }
}

/// Subcommands for the Pinner CLI.
#[derive(Subcommand, Debug, PartialEq, Clone)]
pub enum Commands {
    /// Pin all actions to their current commit SHAs.
    Pin,
    /// Upgrade all actions to their latest releases.
    Upgrade {
        /// Interactively select which actions to upgrade.
        #[arg(short, long)]
        interactive: bool,
        /// Strategy to use when upgrading actions.
        #[arg(long, env = "PINNER_UPGRADE_STRATEGY", default_value = "latest")]
        upgrade_strategy: UpgradeStrategy,
    },
    /// Verify that all actions are pinned to commit SHAs.
    Verify {
        /// Also check the OSV database for known vulnerabilities and compromised hashes during verification.
        #[arg(long, env = "PINNER_CHECK_OSV", conflicts_with = "offline")]
        check_osv: bool,
        /// Fail verification if any dependency is not explicitly vetted in the configuration.
        #[arg(long, env = "PINNER_STRICT")]
        strict: bool,
    },
    /// Set a specific action to a specific commit SHA.
    Set {
        /// Action name (e.g., actions/checkout)
        action: String,
        /// Commit SHA-1 hash
        hash: String,
    },
    /// Install a pre-commit hook that runs pinner verify.
    InstallHook,
    /// Automatically initialize pinner configuration for this repository.
    Init,
    /// Export a Software Bill of Materials (SBOM) for all dependencies in the workflows.
    ExportSbom,
    /// Scan workflows and query OSV to identify compromised dependencies, updating .pinner.toml.
    Scan {
        /// Strategy to use when upgrading actions.
        #[arg(long, env = "PINNER_UPGRADE_STRATEGY", default_value = "latest")]
        upgrade_strategy: UpgradeStrategy,
    },
    /// Automatically commit changes, push to a new branch, and create a Pull Request/Merge Request.
    PrCreate {
        /// Git commit message.
        #[arg(
            short,
            long,
            default_value = "security: pin dependencies to secure commit hashes"
        )]
        message: String,
        /// Name of the new git branch.
        #[arg(short, long, default_value = "pinner/pin-dependencies")]
        branch: String,
    },
    /// Generate shell completions.
    GenerateCompletion {
        /// Shell to generate completions for. If omitted, attempts to detect from the SHELL environment variable.
        shell: Option<clap_complete::Shell>,
    },
}
#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;

    #[test]
    fn test_cli_pin_basic() {
        let cli = Cli::try_parse_from(["pinner", "pin"]).unwrap();
        assert_eq!(cli.command, Commands::Pin);
        assert!(!cli.yes);
        assert!(!cli.quiet());
        assert!(!cli.dry_run);
    }

    #[test]
    fn test_cli_verify() {
        let cli = Cli::try_parse_from(["pinner", "verify"]).unwrap();
        assert_eq!(
            cli.command,
            Commands::Verify {
                check_osv: false,
                strict: false
            }
        );
    }
    #[test]
    fn test_cli_flags() {
        let cli = Cli::try_parse_from(["pinner", "-y", "-q", "--dry-run", "pin"]).unwrap();
        assert_eq!(cli.command, Commands::Pin);
        assert!(cli.yes);
        assert!(cli.quiet);
        assert!(cli.dry_run);
    }

    #[test]
    fn test_cli_upgrade() {
        let cli = Cli::try_parse_from(["pinner", "upgrade"]).unwrap();
        assert_eq!(
            cli.command,
            Commands::Upgrade {
                interactive: false,
                upgrade_strategy: UpgradeStrategy::Latest
            }
        );
    }

    #[test]
    fn test_cli_set() {
        let cli = Cli::try_parse_from([
            "pinner",
            "set",
            "actions/checkout",
            "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2",
        ])
        .unwrap();
        assert_eq!(
            cli.command,
            Commands::Set {
                action: "actions/checkout".into(),
                hash: "a1b2c3d4e5f6a1b2c3d4e5f6a1b2c3d4e5f6a1b2".into(),
            }
        );
    }

    #[test]
    fn test_cli_workflows() {
        let cli =
            Cli::try_parse_from(["pinner", "-w", "dir1", "--workflows", "dir2", "pin"]).unwrap();
        assert_eq!(
            cli.workflows,
            vec![PathBuf::from("dir1"), PathBuf::from("dir2")]
        );
    }

    #[test]
    fn test_cli_methods() {
        let cli = Cli {
            command: Commands::Pin,
            workflows: vec![],
            yes: false,
            quiet: true,
            verbose: false,
            no_cache: false,
            cache_ttl: None,
            offline: false,
            dry_run: false,
            github_token: None,
            bitbucket_token: None,
            gitlab_token: None,
            forgejo_token: None,
            circleci_token: None,
            oci_username: None,
            oci_password: None,
            format: OutputFormat::Text,
            github_url: "https://api.github.com".to_string(),
            bitbucket_url: "https://api.bitbucket.org/2.0".to_string(),
            gitlab_url: "https://gitlab.com".to_string(),
            forgejo_url: "https://codeberg.org".to_string(),
            circleci_url: "https://circleci.com/graphql-unstable".to_string(),
            concurrency: None,
            ignore: vec![],
        };
        assert!(cli.quiet());
        assert_eq!(cli.format, OutputFormat::Text);
        assert!(!cli.offline);
    }

    #[test]
    fn test_cli_offline() {
        let cli = Cli::try_parse_from(["pinner", "--offline", "pin"]).unwrap();
        assert!(cli.offline);
    }

    #[test]
    fn test_cli_verify_options() {
        let cli = Cli::try_parse_from(["pinner", "verify", "--check-osv", "--strict"]).unwrap();
        assert_eq!(
            cli.command,
            Commands::Verify {
                check_osv: true,
                strict: true,
            }
        );
    }

    #[test]
    fn test_cli_quiet_verbose_conflict() {
        let res = Cli::try_parse_from(["pinner", "--quiet", "--verbose", "pin"]);
        assert!(res.is_err());
    }

    #[test]
    fn test_cli_no_cache_cache_ttl_conflict() {
        let res = Cli::try_parse_from(["pinner", "--no-cache", "--cache-ttl", "3600", "pin"]);
        assert!(res.is_err());
    }

    #[test]
    fn test_cli_oci_username_requires_password() {
        let res = Cli::try_parse_from(["pinner", "--oci-username", "foo", "pin"]);
        assert!(res.is_err());
    }

    #[test]
    fn test_cli_oci_password_requires_username() {
        let res = Cli::try_parse_from(["pinner", "--oci-password", "bar", "pin"]);
        assert!(res.is_err());
    }

    #[test]
    fn test_cli_oci_both_ok() {
        let cli = Cli::try_parse_from([
            "pinner",
            "--oci-username",
            "foo",
            "--oci-password",
            "bar",
            "pin",
        ])
        .unwrap();
        assert_eq!(cli.oci_username, Some("foo".to_string()));
        assert_eq!(cli.oci_password, Some("bar".to_string()));
    }

    #[test]
    #[serial_test::serial]
    fn test_cli_token_env() {
        std::env::set_var("GITHUB_TOKEN", "test_token");
        let cli = Cli::try_parse_from(["pinner", "pin"]).unwrap();
        assert_eq!(cli.github_token, Some("test_token".to_string()));
        std::env::remove_var("GITHUB_TOKEN");
    }
}