syncable_cli/analyzer/hadolint/rules/
dl3004.rs

1//! DL3004: Do not use sudo
2//!
3//! Using sudo in Dockerfiles is unnecessary since containers run as root
4//! by default, and using it indicates a misunderstanding of Docker.
5
6use 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        "DL3004",
14        Severity::Error,
15        "Do not use sudo as it leads to unpredictable behavior. Use a tool like gosu to enforce root",
16        |instr, shell| {
17            match instr {
18                Instruction::Run(_) => {
19                    if let Some(shell) = shell {
20                        !shell.any_command(|cmd| cmd.name == "sudo")
21                    } else {
22                        true
23                    }
24                }
25                _ => true,
26            }
27        },
28    )
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34    use crate::analyzer::hadolint::parser::instruction::RunArgs;
35    use crate::analyzer::hadolint::rules::{Rule, RuleState};
36
37    #[test]
38    fn test_no_sudo() {
39        let rule = rule();
40        let mut state = RuleState::new();
41
42        let instr = Instruction::Run(RunArgs::shell("apt-get update"));
43        let shell = ParsedShell::parse("apt-get update");
44        rule.check(&mut state, 1, &instr, Some(&shell));
45        assert!(state.failures.is_empty());
46    }
47
48    #[test]
49    fn test_with_sudo() {
50        let rule = rule();
51        let mut state = RuleState::new();
52
53        let instr = Instruction::Run(RunArgs::shell("sudo apt-get update"));
54        let shell = ParsedShell::parse("sudo apt-get update");
55        rule.check(&mut state, 1, &instr, Some(&shell));
56        assert_eq!(state.failures.len(), 1);
57        assert_eq!(state.failures[0].code.as_str(), "DL3004");
58    }
59}