syncable_cli/analyzer/hadolint/rules/
dl3041.rs1use crate::analyzer::hadolint::parser::instruction::Instruction;
6use crate::analyzer::hadolint::rules::{SimpleRule, simple_rule};
7use crate::analyzer::hadolint::shell::ParsedShell;
8use crate::analyzer::hadolint::types::Severity;
9
10pub fn rule() -> SimpleRule<impl Fn(&Instruction, Option<&ParsedShell>) -> bool + Send + Sync> {
11 simple_rule(
12 "DL3041",
13 Severity::Warning,
14 "Specify version with `dnf install <package>-<version>`.",
15 |instr, shell| match instr {
16 Instruction::Run(_) => {
17 if let Some(shell) = shell {
18 !shell.any_command(|cmd| {
19 if cmd.name == "dnf" && cmd.has_any_arg(&["install"]) {
20 let packages = get_dnf_packages(cmd);
21 packages.iter().any(|pkg| !is_pinned_dnf_package(pkg))
22 } else {
23 false
24 }
25 })
26 } else {
27 true
28 }
29 }
30 _ => true,
31 },
32 )
33}
34
35fn get_dnf_packages(cmd: &crate::analyzer::hadolint::shell::Command) -> Vec<&str> {
36 let mut packages = Vec::new();
37 let mut found_install = false;
38
39 for arg in &cmd.arguments {
40 if arg == "install" {
41 found_install = true;
42 continue;
43 }
44 if found_install && !arg.starts_with('-') {
45 packages.push(arg.as_str());
46 }
47 }
48
49 packages
50}
51
52fn is_pinned_dnf_package(pkg: &str) -> bool {
53 if pkg.starts_with('-') {
54 return true;
55 }
56 if pkg.ends_with(".rpm") {
57 return true;
58 }
59 let parts: Vec<&str> = pkg.rsplitn(2, '-').collect();
61 if parts.len() >= 2 {
62 let potential_version = parts[0];
63 potential_version
64 .chars()
65 .next()
66 .map(|c| c.is_ascii_digit())
67 .unwrap_or(false)
68 } else {
69 false
70 }
71}
72
73#[cfg(test)]
74mod tests {
75 use super::*;
76 use crate::analyzer::hadolint::config::HadolintConfig;
77 use crate::analyzer::hadolint::lint::{LintResult, lint};
78
79 fn lint_dockerfile(content: &str) -> LintResult {
80 lint(content, &HadolintConfig::default())
81 }
82
83 #[test]
84 fn test_dnf_unpinned() {
85 let result = lint_dockerfile("FROM fedora:latest\nRUN dnf install -y nginx");
86 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3041"));
87 }
88
89 #[test]
90 fn test_dnf_pinned() {
91 let result = lint_dockerfile("FROM fedora:latest\nRUN dnf install -y nginx-1.20.0");
92 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3041"));
93 }
94}