syncable_cli/analyzer/hadolint/rules/
dl3048.rs1use crate::analyzer::hadolint::parser::instruction::Instruction;
6use crate::analyzer::hadolint::rules::{SimpleRule, simple_rule};
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| match instr {
16 Instruction::Label(pairs) => pairs.iter().all(|(key, _)| is_valid_label_key(key)),
17 _ => true,
18 },
19 )
20}
21
22fn is_valid_label_key(key: &str) -> bool {
23 if key.is_empty() {
24 return false;
25 }
26
27 let first_char = key.chars().next().unwrap();
29 if !first_char.is_ascii_alphanumeric() {
30 return false;
31 }
32
33 key.chars()
35 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
36}
37
38#[cfg(test)]
39mod tests {
40 use super::*;
41 use crate::analyzer::hadolint::config::HadolintConfig;
42 use crate::analyzer::hadolint::lint::{LintResult, lint};
43
44 fn lint_dockerfile(content: &str) -> LintResult {
45 lint(content, &HadolintConfig::default())
46 }
47
48 #[test]
49 fn test_valid_label() {
50 let result = lint_dockerfile("FROM ubuntu:20.04\nLABEL maintainer=\"test@test.com\"");
51 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3048"));
52 }
53
54 #[test]
55 fn test_valid_oci_label() {
56 let result =
57 lint_dockerfile("FROM ubuntu:20.04\nLABEL org.opencontainers.image.title=\"Test\"");
58 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3048"));
59 }
60
61 #[test]
62 fn test_invalid_label_special_char() {
63 use crate::analyzer::hadolint::parser::instruction::Instruction;
66 use crate::analyzer::hadolint::rules::{Rule, RuleState};
67
68 let rule = rule();
69 let mut state = RuleState::new();
70
71 let instr = Instruction::Label(vec![("@invalid".to_string(), "test".to_string())]);
73 rule.check(&mut state, 1, &instr, None);
74
75 assert_eq!(state.failures.len(), 1);
76 assert_eq!(state.failures[0].code.as_str(), "DL3048");
77 }
78}