syncable_cli/analyzer/hadolint/rules/
dl3021.rs1use 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 "DL3021",
14 Severity::Error,
15 "Use `COPY` instead of `ADD` for copying non-archive files.",
16 |instr, _shell| {
17 match instr {
18 Instruction::Add(args, _) => {
19 args.sources
23 .iter()
24 .all(|src| is_url(src) || is_archive(src))
25 }
26 _ => true,
27 }
28 },
29 )
30}
31
32fn is_url(src: &str) -> bool {
34 src.starts_with("http://") || src.starts_with("https://") || src.starts_with("ftp://")
35}
36
37fn is_archive(src: &str) -> bool {
39 if src.starts_with('$') {
41 return true;
42 }
43
44 let archive_extensions = [
45 ".tar",
46 ".tar.gz",
47 ".tgz",
48 ".tar.bz2",
49 ".tbz2",
50 ".tar.xz",
51 ".txz",
52 ".tar.zst",
53 ".tar.lz",
54 ".tar.lzma",
55 ".gz",
56 ".bz2",
57 ".xz",
58 ];
59
60 let lower = src.to_lowercase();
61 archive_extensions.iter().any(|ext| lower.ends_with(ext))
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67 use crate::analyzer::hadolint::config::HadolintConfig;
68 use crate::analyzer::hadolint::lint::{LintResult, lint};
69
70 fn lint_dockerfile(content: &str) -> LintResult {
71 lint(content, &HadolintConfig::default())
72 }
73
74 #[test]
75 fn test_add_regular_file() {
76 let result = lint_dockerfile("FROM ubuntu:20.04\nADD config.json /etc/app/");
77 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
78 }
79
80 #[test]
81 fn test_add_url() {
82 let result =
83 lint_dockerfile("FROM ubuntu:20.04\nADD https://example.com/file.tar.gz /tmp/");
84 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
85 }
86
87 #[test]
88 fn test_add_tar_archive() {
89 let result = lint_dockerfile("FROM ubuntu:20.04\nADD app.tar.gz /app/");
90 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
91 }
92
93 #[test]
94 fn test_add_directory() {
95 let result = lint_dockerfile("FROM ubuntu:20.04\nADD src/ /app/");
96 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
97 }
98}