syncable_cli/analyzer/hadolint/rules/
dl3046.rs

1//! DL3046: useradd without -l flag may result in large layers
2//!
3//! When adding a user with useradd, use the -l flag to avoid creating
4//! large layers due to /var/log/lastlog growing.
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        "DL3046",
14        Severity::Warning,
15        "`useradd` without flag `-l` and target UID not within `/etc/login.defs` may result in excessively large image.",
16        |instr, shell| {
17            match instr {
18                Instruction::Run(_) => {
19                    if let Some(shell) = shell {
20                        !shell.any_command(|cmd| {
21                            if cmd.name == "useradd" {
22                                // Check if -l or --no-log-init flag is present
23                                // Also check combined flags like -lm
24                                let has_l_flag = cmd.arguments.iter().any(|a| {
25                                    a == "-l"
26                                        || a == "--no-log-init"
27                                        || (a.starts_with('-')
28                                            && !a.starts_with("--")
29                                            && a.contains('l'))
30                                });
31                                !has_l_flag
32                            } else {
33                                false
34                            }
35                        })
36                    } else {
37                        true
38                    }
39                }
40                _ => true,
41            }
42        },
43    )
44}
45
46#[cfg(test)]
47mod tests {
48    use super::*;
49    use crate::analyzer::hadolint::config::HadolintConfig;
50    use crate::analyzer::hadolint::lint::{LintResult, lint};
51
52    fn lint_dockerfile(content: &str) -> LintResult {
53        lint(content, &HadolintConfig::default())
54    }
55
56    #[test]
57    fn test_useradd_without_l() {
58        let result = lint_dockerfile("FROM ubuntu:20.04\nRUN useradd -m myuser");
59        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3046"));
60    }
61
62    #[test]
63    fn test_useradd_with_l() {
64        let result = lint_dockerfile("FROM ubuntu:20.04\nRUN useradd -l -m myuser");
65        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3046"));
66    }
67
68    #[test]
69    fn test_useradd_with_no_log_init() {
70        let result = lint_dockerfile("FROM ubuntu:20.04\nRUN useradd --no-log-init -m myuser");
71        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3046"));
72    }
73}