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