syncable_cli/analyzer/hadolint/rules/
dl3048.rs

1//! DL3048: Invalid label key
2//!
3//! Label keys should follow the OCI annotation specification.
4
5use crate::analyzer::hadolint::parser::instruction::Instruction;
6use crate::analyzer::hadolint::rules::{simple_rule, SimpleRule};
7use crate::analyzer::hadolint::shell::ParsedShell;
8use crate::analyzer::hadolint::types::Severity;
9
10pub fn rule() -> SimpleRule<impl Fn(&Instruction, Option<&ParsedShell>) -> bool + Send + Sync> {
11    simple_rule(
12        "DL3048",
13        Severity::Style,
14        "Invalid label key.",
15        |instr, _shell| {
16            match instr {
17                Instruction::Label(pairs) => {
18                    pairs.iter().all(|(key, _)| is_valid_label_key(key))
19                }
20                _ => true,
21            }
22        },
23    )
24}
25
26fn is_valid_label_key(key: &str) -> bool {
27    if key.is_empty() {
28        return false;
29    }
30
31    // Label keys must start with a letter or number
32    let first_char = key.chars().next().unwrap();
33    if !first_char.is_ascii_alphanumeric() {
34        return false;
35    }
36
37    // Label keys can only contain alphanumeric, -, _, .
38    key.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use crate::analyzer::hadolint::lint::{lint, LintResult};
45    use crate::analyzer::hadolint::config::HadolintConfig;
46
47    fn lint_dockerfile(content: &str) -> LintResult {
48        lint(content, &HadolintConfig::default())
49    }
50
51    #[test]
52    fn test_valid_label() {
53        let result = lint_dockerfile("FROM ubuntu:20.04\nLABEL maintainer=\"test@test.com\"");
54        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3048"));
55    }
56
57    #[test]
58    fn test_valid_oci_label() {
59        let result = lint_dockerfile("FROM ubuntu:20.04\nLABEL org.opencontainers.image.title=\"Test\"");
60        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3048"));
61    }
62
63    #[test]
64    fn test_invalid_label_special_char() {
65        // Note: The parser may not accept labels starting with special chars,
66        // so this test validates the rule itself works with the unit test approach
67        use crate::analyzer::hadolint::rules::{Rule, RuleState};
68        use crate::analyzer::hadolint::parser::instruction::Instruction;
69
70        let rule = rule();
71        let mut state = RuleState::new();
72
73        // Manually test with an invalid key starting with @
74        let instr = Instruction::Label(vec![("@invalid".to_string(), "test".to_string())]);
75        rule.check(&mut state, 1, &instr, None);
76
77        assert_eq!(state.failures.len(), 1);
78        assert_eq!(state.failures[0].code.as_str(), "DL3048");
79    }
80}