syncable_cli/analyzer/hadolint/rules/
dl3010.rs

1//! DL3010: Use ADD for extracting archives into an image
2//!
3//! ADD can automatically extract tar archives. Use ADD instead of
4//! COPY + RUN tar for better efficiency.
5
6use crate::analyzer::hadolint::parser::instruction::Instruction;
7use crate::analyzer::hadolint::rules::{SimpleRule, simple_rule};
8use crate::analyzer::hadolint::shell::ParsedShell;
9use crate::analyzer::hadolint::types::Severity;
10
11pub fn rule() -> SimpleRule<impl Fn(&Instruction, Option<&ParsedShell>) -> bool + Send + Sync> {
12    simple_rule(
13        "DL3010",
14        Severity::Info,
15        "Use ADD for extracting archives into an image.",
16        |instr, _shell| {
17            match instr {
18                Instruction::Copy(args, _) => {
19                    // Check if any source looks like a local tar archive
20                    !args.sources.iter().any(|src| is_local_archive(src))
21                }
22                _ => true,
23            }
24        },
25    )
26}
27
28/// Check if source is a local archive file (not URL)
29fn is_local_archive(src: &str) -> bool {
30    // Skip URLs
31    if src.starts_with("http://") || src.starts_with("https://") || src.starts_with("ftp://") {
32        return false;
33    }
34
35    // Skip variables
36    if src.starts_with('$') {
37        return false;
38    }
39
40    // Check for archive extensions
41    let archive_extensions = [
42        ".tar",
43        ".tar.gz",
44        ".tgz",
45        ".tar.bz2",
46        ".tbz2",
47        ".tar.xz",
48        ".txz",
49        ".tar.zst",
50        ".tar.lz",
51        ".tar.lzma",
52    ];
53
54    let lower = src.to_lowercase();
55    archive_extensions.iter().any(|ext| lower.ends_with(ext))
56}
57
58#[cfg(test)]
59mod tests {
60    use super::*;
61    use crate::analyzer::hadolint::config::HadolintConfig;
62    use crate::analyzer::hadolint::lint::{LintResult, lint};
63
64    fn lint_dockerfile(content: &str) -> LintResult {
65        lint(content, &HadolintConfig::default())
66    }
67
68    #[test]
69    fn test_copy_tar_file() {
70        let result = lint_dockerfile("FROM ubuntu:20.04\nCOPY app.tar.gz /app/");
71        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3010"));
72    }
73
74    #[test]
75    fn test_copy_tgz_file() {
76        let result = lint_dockerfile("FROM ubuntu:20.04\nCOPY archive.tgz /tmp/");
77        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3010"));
78    }
79
80    #[test]
81    fn test_copy_regular_file() {
82        let result = lint_dockerfile("FROM ubuntu:20.04\nCOPY app.js /app/");
83        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3010"));
84    }
85
86    #[test]
87    fn test_copy_directory() {
88        let result = lint_dockerfile("FROM ubuntu:20.04\nCOPY src/ /app/");
89        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3010"));
90    }
91}