eb_pipeline/
lint.rs

1//! Placeholder lint for example site files.
2//!
3//! Examples must carry neutral values only: absolute paths under `/opt`,
4//! `/srv` or `/scratch`, angle-bracket placeholders, and host names under
5//! `example.org` or `.invalid`. An operator who keeps a private site file next
6//! to the templates can name extra substrings to refuse through
7//! `EB_PIPELINE_LINT_DENY` (comma-separated); the repository itself names none.
8
9const ROOTS: [&str; 3] = ["/opt", "/srv", "/scratch"];
10const FILE_EXTS: [&str; 16] = [
11    "eb", "json", "toml", "list", "lock", "sh", "log", "txt", "py", "yaml", "yml", "cfg", "conf",
12    "md", "gz", "tar",
13];
14
15fn path_ok(p: &str) -> bool {
16    ROOTS
17        .iter()
18        .any(|r| p == *r || p.starts_with(&format!("{r}/")))
19}
20
21fn host_ok(h: &str) -> bool {
22    h == "example.org" || h.ends_with(".example.org") || h == "invalid" || h.ends_with(".invalid")
23}
24
25fn looks_like_host(t: &str) -> bool {
26    if t.contains('/') || !t.contains('.') {
27        return false;
28    }
29    if !t
30        .chars()
31        .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '.' || c == '-')
32    {
33        return false;
34    }
35    let last = t.rsplit('.').next().unwrap_or("");
36    last.len() >= 2
37        && last.chars().all(|c| c.is_ascii_lowercase())
38        && !FILE_EXTS.contains(&last)
39        && !t.starts_with('-')
40        && !t.starts_with('.')
41}
42
43fn check_token(key: &str, raw: &str, out: &mut Vec<String>) {
44    let t = raw.trim_matches(|c| matches!(c, '\'' | '"' | '(' | ')' | '[' | ']'));
45    if t.is_empty() || (t.starts_with('<') && t.ends_with('>')) {
46        return;
47    }
48    let t = t.rsplit('@').next().unwrap_or(t);
49    if t.starts_with('/') {
50        if !path_ok(t) {
51            out.push(format!(
52                "{key}: path `{t}` is not under /opt, /srv or /scratch and not a placeholder"
53            ));
54        }
55    } else if looks_like_host(t) && !host_ok(t) {
56        out.push(format!(
57            "{key}: host `{t}` is not under example.org or .invalid"
58        ));
59    }
60}
61
62fn check_value(key: &str, v: &str, deny: &[String], out: &mut Vec<String>) {
63    for d in deny {
64        if v.contains(d.as_str()) {
65            out.push(format!("{key}: value contains the denied text `{d}`"));
66        }
67    }
68    for word in v.split_whitespace() {
69        if let Some((_, rest)) = word.split_once("://") {
70            let host = rest.split(['/', ':']).next().unwrap_or("");
71            if !host_ok(host) {
72                out.push(format!(
73                    "{key}: host `{host}` is not under example.org or .invalid"
74                ));
75            }
76            continue;
77        }
78        for raw in word.split([':', ',', '=', ';']) {
79            check_token(key, raw, out);
80        }
81    }
82}
83
84fn walk(key: &str, v: &toml::Value, deny: &[String], out: &mut Vec<String>) {
85    match v {
86        toml::Value::String(s) => check_value(key, s, deny, out),
87        toml::Value::Array(a) => a.iter().for_each(|x| walk(key, x, deny, out)),
88        toml::Value::Table(t) => t.iter().for_each(|(k, x)| {
89            let kk = if key.is_empty() {
90                k.clone()
91            } else {
92                format!("{key}.{k}")
93            };
94            walk(&kk, x, deny, out)
95        }),
96        _ => {}
97    }
98}
99
100/// Return one message per value that looks site-specific.
101pub fn lint_example(text: &str) -> Vec<String> {
102    lint_example_with(text, &[])
103}
104
105/// As [`lint_example`], and also refuse any string value containing one of
106/// `deny`.
107pub fn lint_example_with(text: &str, deny: &[String]) -> Vec<String> {
108    let mut out = Vec::new();
109    match toml::from_str::<toml::Value>(text) {
110        Ok(v) => walk("", &v, deny, &mut out),
111        Err(e) => out.push(format!("not valid TOML: {e}")),
112    }
113    out
114}
115
116/// The extra substrings named by `EB_PIPELINE_LINT_DENY`, comma-separated;
117/// blank entries are dropped.
118pub fn deny_from_env() -> Vec<String> {
119    std::env::var("EB_PIPELINE_LINT_DENY")
120        .unwrap_or_default()
121        .split(',')
122        .map(str::trim)
123        .filter(|s| !s.is_empty())
124        .map(str::to_string)
125        .collect()
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn accepts_placeholders() {
134        let t = r#"
135a = "/opt/eb/sources"
136b = ["/scratch/x:/srv/y"]
137c = "<scratch>/tmp"
138d = "-p batch -N 1 -t 15:00"
139e = "https://example.org/x"
140f = "user@node.example.org"
141g = "foss/2026.1 GCC:-march=x86-64-v3 Foo-1.0-foss-2025a.eb"
142"#;
143        assert!(lint_example(t).is_empty(), "{:?}", lint_example(t));
144    }
145
146    #[test]
147    fn rejects_site_values() {
148        let t = r#"
149a = "/home/builder/eb"
150b = "login.cluster.net"
151c = "https://git.corp.example.com/x"
152d = "-o /projects/lab/x"
153"#;
154        assert_eq!(lint_example(t).len(), 4, "{:?}", lint_example(t));
155    }
156
157    #[test]
158    fn deny_list_refuses_named_text() {
159        let t = "a = \"/opt/eb/layout-x/cpu\"\nb = [\"/opt/eb/ok\"]\n";
160        assert!(lint_example(t).is_empty());
161        let deny = vec!["layout-x".to_string()];
162        let hits = lint_example_with(t, &deny);
163        assert_eq!(hits.len(), 1, "{hits:?}");
164        assert!(hits[0].starts_with("a:"), "{hits:?}");
165    }
166}