syncable_cli/analyzer/hadolint/rules/
dl3018.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 "DL3018",
13 Severity::Warning,
14 "Pin versions in apk add. Instead of `apk add <package>` use `apk add <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 == "apk" && cmd.has_any_arg(&["add"]) {
21 let packages = get_apk_packages(cmd);
23 packages.iter().any(|pkg| !is_pinned_apk_package(pkg))
25 } else {
26 false
27 }
28 })
29 } else {
30 true
31 }
32 }
33 _ => true,
34 }
35 },
36 )
37}
38
39fn get_apk_packages(cmd: &crate::analyzer::hadolint::shell::Command) -> Vec<&str> {
41 let mut packages = Vec::new();
42 let mut found_add = false;
43
44 for arg in &cmd.arguments {
45 if arg == "add" {
46 found_add = true;
47 continue;
48 }
49 if found_add && !arg.starts_with('-') {
50 packages.push(arg.as_str());
51 }
52 }
53
54 packages
55}
56
57fn is_pinned_apk_package(pkg: &str) -> bool {
59 if pkg.starts_with('-') {
61 return true;
62 }
63
64 if pkg.starts_with('.') {
66 return true;
67 }
68
69 pkg.contains('=') || pkg.contains('~')
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_apk_add_unpinned() {
85 let result = lint_dockerfile("FROM alpine:3.18\nRUN apk add nginx");
86 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3018"));
87 }
88
89 #[test]
90 fn test_apk_add_pinned() {
91 let result = lint_dockerfile("FROM alpine:3.18\nRUN apk add nginx=1.24.0-r0");
92 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3018"));
93 }
94
95 #[test]
96 fn test_apk_add_pinned_tilde() {
97 let result = lint_dockerfile("FROM alpine:3.18\nRUN apk add nginx~1.24");
98 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3018"));
99 }
100
101 #[test]
102 fn test_apk_add_no_cache_unpinned() {
103 let result = lint_dockerfile("FROM alpine:3.18\nRUN apk add --no-cache curl");
104 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3018"));
105 }
106
107 #[test]
108 fn test_apk_update() {
109 let result = lint_dockerfile("FROM alpine:3.18\nRUN apk update");
110 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3018"));
111 }
112}