syncable_cli/analyzer/hadolint/rules/
dl3021.rs1use crate::analyzer::hadolint::parser::instruction::Instruction;
7use crate::analyzer::hadolint::rules::{simple_rule, SimpleRule};
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.iter().all(|src| {
23 is_url(src) || is_archive(src)
24 })
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", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz",
46 ".tar.zst", ".tar.lz", ".tar.lzma", ".gz", ".bz2", ".xz"
47 ];
48
49 let lower = src.to_lowercase();
50 archive_extensions.iter().any(|ext| lower.ends_with(ext))
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56 use crate::analyzer::hadolint::lint::{lint, LintResult};
57 use crate::analyzer::hadolint::config::HadolintConfig;
58
59 fn lint_dockerfile(content: &str) -> LintResult {
60 lint(content, &HadolintConfig::default())
61 }
62
63 #[test]
64 fn test_add_regular_file() {
65 let result = lint_dockerfile("FROM ubuntu:20.04\nADD config.json /etc/app/");
66 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
67 }
68
69 #[test]
70 fn test_add_url() {
71 let result = lint_dockerfile("FROM ubuntu:20.04\nADD https://example.com/file.tar.gz /tmp/");
72 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
73 }
74
75 #[test]
76 fn test_add_tar_archive() {
77 let result = lint_dockerfile("FROM ubuntu:20.04\nADD app.tar.gz /app/");
78 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
79 }
80
81 #[test]
82 fn test_add_directory() {
83 let result = lint_dockerfile("FROM ubuntu:20.04\nADD src/ /app/");
84 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3021"));
85 }
86}