Skip to main content

vault_core/
config_check.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Cross-chunk, cross-format checks for a project (Phase 29, "the config compiler"; ADR-0137).
4//!
5//! Phase 18's validation matrix runs each generated file past its own tool
6//! (`nginx -t`, `wg-quick strip`), which can only ever see one format. The
7//! mistakes that bite sit between chunks: a `proxy_pass` naming a service the
8//! project does not define, two WireGuard peers claiming one address.
9//!
10//! **Eight rule ids over the six designed checks, hand-written, and no rule language**
11//! (WireGuard and Kubernetes each split into an error case and a softer one). A false positive costs far
12//! more than a missing check: a validator that cries wolf gets switched off and
13//! then protects nothing. So every rule fires only on positive evidence that the
14//! project means to define the thing (a rule about Docker services stays silent in
15//! a project with no `docker_service` chunk), and anything that could be resolved
16//! somewhere this function cannot see — a `name@provider` Traefik reference, a
17//! `${bundle:…}` reference, a hostname with a dot — is skipped, not guessed at.
18//!
19//! The functions are pure over the project JSON, so the CLI (`unv check`) and the
20//! desktop app (over IPC) cannot disagree about what a project means. Messages
21//! carry names and never values: a finding must be safe to print, and a hostname
22//! or chunk name is not a secret where a field value might be.
23
24use serde_json::{json, Value};
25use std::collections::{HashMap, HashSet};
26use std::net::IpAddr;
27
28/// One finding. `severity` is `"error"` (the generated config is wrong) or
29/// `"warning"` (probably wrong; could be satisfied somewhere this cannot see).
30pub struct Finding {
31    pub rule: &'static str,
32    pub severity: &'static str,
33    pub chunk_id: String,
34    pub chunk_name: String,
35    pub chunk_type: String,
36    pub field: String,
37    pub message: String,
38    /// Other chunks involved, by name.
39    pub related: Vec<String>,
40}
41
42impl Finding {
43    pub fn to_json(&self) -> Value {
44        json!({
45            "rule": self.rule,
46            "severity": self.severity,
47            "chunk_id": self.chunk_id,
48            "chunk": self.chunk_name,
49            "chunk_type": self.chunk_type,
50            "field": self.field,
51            "message": self.message,
52            "related": self.related,
53        })
54    }
55}
56
57fn s<'a>(v: &'a Value, key: &str) -> &'a str {
58    v.get(key).and_then(Value::as_str).unwrap_or("")
59}
60
61fn fields(chunk: &Value) -> Vec<&Value> {
62    chunk
63        .get("fields")
64        .and_then(Value::as_array)
65        .map(|a| a.iter().collect())
66        .unwrap_or_default()
67}
68
69/// First non-empty value of `key`, trimmed.
70fn field<'a>(chunk: &'a Value, key: &str) -> &'a str {
71    fields(chunk)
72        .into_iter()
73        .find(|f| s(f, "key") == key && !s(f, "value").trim().is_empty())
74        .map(|f| s(f, "value").trim())
75        .unwrap_or("")
76}
77
78/// Every non-empty value of `key` (a key may repeat, e.g. `listen`).
79fn field_all<'a>(chunk: &'a Value, key: &str) -> Vec<&'a str> {
80    fields(chunk)
81        .into_iter()
82        .filter(|f| s(f, "key") == key)
83        .map(|f| s(f, "value").trim())
84        .filter(|v| !v.is_empty())
85        .collect()
86}
87
88fn split_list(raw: &str) -> Vec<String> {
89    raw.split(|c: char| c == ',' || c.is_whitespace())
90        .map(str::trim)
91        .filter(|x| !x.is_empty())
92        .map(String::from)
93        .collect()
94}
95
96/// A disabled chunk is excluded from exports, so it is excluded here too.
97fn active_chunks(project: &Value) -> Vec<&Value> {
98    project
99        .get("chunks")
100        .and_then(Value::as_array)
101        .map(|a| {
102            a.iter()
103                .filter(|c| !c.get("disabled").and_then(Value::as_bool).unwrap_or(false))
104                .collect()
105        })
106        .unwrap_or_default()
107}
108
109fn of_type<'a>(chunks: &[&'a Value], t: &str) -> Vec<&'a Value> {
110    chunks
111        .iter()
112        .copied()
113        .filter(|c| s(c, "chunk_type") == t)
114        .collect()
115}
116
117fn finding(
118    rule: &'static str,
119    severity: &'static str,
120    chunk: &Value,
121    field: &str,
122    message: String,
123    related: Vec<String>,
124) -> Finding {
125    Finding {
126        rule,
127        severity,
128        chunk_id: s(chunk, "id").to_string(),
129        chunk_name: s(chunk, "name").to_string(),
130        chunk_type: s(chunk, "chunk_type").to_string(),
131        field: field.to_string(),
132        message,
133        related,
134    }
135}
136
137/// Compose names a service the way the exporter does: whitespace to `_`, lowercase.
138fn service_name(chunk: &Value) -> String {
139    s(chunk, "name")
140        .split_whitespace()
141        .collect::<Vec<_>>()
142        .join("_")
143        .to_lowercase()
144}
145
146/// Every name a service answers to on a Docker network.
147fn service_aliases(chunk: &Value) -> Vec<String> {
148    let mut v = vec![service_name(chunk)];
149    let cn = field(chunk, "container_name").to_lowercase();
150    if !cn.is_empty() {
151        v.push(cn);
152    }
153    v
154}
155
156fn norm(name: &str) -> String {
157    name.chars()
158        .map(|c| {
159            if c.is_ascii_alphanumeric() {
160                c.to_ascii_uppercase()
161            } else {
162                '_'
163            }
164        })
165        .collect()
166}
167
168fn is_ref(v: &str) -> bool {
169    v.contains("${")
170}
171
172// ── Rule 1: nginx proxy_pass → a Docker service the project does not define ──
173
174fn rule_nginx_proxy_pass(chunks: &[&Value], elsewhere: &[String], out: &mut Vec<Finding>) {
175    let services = of_type(chunks, "docker_service");
176    if services.is_empty() && elsewhere.is_empty() {
177        return; // no evidence this project (or, with --all-projects, any) defines services
178    }
179    let mut known: HashSet<String> = services.iter().flat_map(|c| service_aliases(c)).collect();
180    known.extend(elsewhere.iter().cloned());
181    for u in of_type(chunks, "nginx_upstream") {
182        known.insert(s(u, "name").to_lowercase());
183    }
184    for t in ["nginx_location", "nginx_server"] {
185        for c in of_type(chunks, t) {
186            for target in field_all(c, "proxy_pass") {
187                let Some(host) = proxy_host(target) else {
188                    continue;
189                };
190                if !known.contains(&host) {
191                    out.push(finding(
192                        "nginx-proxy-pass-unknown-service",
193                        "warning",
194                        c,
195                        "proxy_pass",
196                        format!(
197                            "proxy_pass names `{host}`, which is neither a Docker service nor an upstream defined in this project"
198                        ),
199                        services.iter().map(|x| service_name(x)).collect(),
200                    ));
201                }
202            }
203        }
204    }
205}
206
207/// The bare host of a `proxy_pass` target, or `None` when it is not a service-style
208/// name (an IP, a dotted hostname, `localhost`, a variable, a unix socket, a ref).
209fn proxy_host(target: &str) -> Option<String> {
210    if is_ref(target) || target.contains('$') || target.starts_with("unix:") {
211        return None;
212    }
213    let rest = target.split_once("://").map(|(_, r)| r).unwrap_or(target);
214    if rest.starts_with("unix:") {
215        return None;
216    }
217    let host = rest.split(['/', ':']).next().unwrap_or("").to_lowercase();
218    if host.is_empty()
219        || host == "localhost"
220        || host.contains('.')
221        || host.contains('[')
222        || host.parse::<IpAddr>().is_ok()
223    {
224        return None;
225    }
226    Some(host)
227}
228
229// ── Rule 2: two WireGuard peers with the same AllowedIPs network ─────────────
230
231/// `10.0.0.5/24` → the masked network `10.0.0.0/24`; `None` if unparseable.
232fn network(cidr: &str) -> Option<(u8, u128, u8)> {
233    let (addr, len) = match cidr.split_once('/') {
234        Some((a, l)) => (a, Some(l.parse::<u8>().ok()?)),
235        None => (cidr, None),
236    };
237    match addr.parse::<IpAddr>().ok()? {
238        IpAddr::V4(a) => {
239            let len = len.unwrap_or(32);
240            if len > 32 {
241                return None;
242            }
243            let bits = u32::from(a) as u128;
244            let mask = if len == 0 {
245                0
246            } else {
247                (!0u32 << (32 - len)) as u128
248            };
249            Some((4, bits & mask, len))
250        }
251        IpAddr::V6(a) => {
252            let len = len.unwrap_or(128);
253            if len > 128 {
254                return None;
255            }
256            let bits = u128::from(a);
257            let mask = if len == 0 { 0 } else { !0u128 << (128 - len) };
258            Some((6, bits & mask, len))
259        }
260    }
261}
262
263/// `a` strictly contains `b` (same family, shorter prefix, same leading bits).
264fn contains(a: (u8, u128, u8), b: (u8, u128, u8)) -> bool {
265    if a.0 != b.0 || a.2 >= b.2 {
266        return false;
267    }
268    let width: u32 = if a.0 == 4 { 32 } else { 128 };
269    let shift = width - a.2 as u32;
270    // For IPv4 the address sits in the low 32 bits of the u128.
271    if a.2 == 0 {
272        return true;
273    }
274    (a.1 >> shift) == (b.1 >> shift)
275}
276
277/// Two peers claiming the *same* network is always wrong: the kernel silently
278/// moves it to whichever peer was added last (an error). One peer's network
279/// *containing* another's is how WireGuard expresses a split route, since it routes
280/// by longest prefix, so it is only a warning, and a default route (`/0`) beside
281/// host routes, the standard full-tunnel pattern, is not reported at all.
282fn rule_wireguard_allowed_ips(chunks: &[&Value], out: &mut Vec<Finding>) {
283    let peers = of_type(chunks, "wg_peer");
284    let mut seen: HashMap<(u8, u128, u8), &Value> = HashMap::new();
285    let mut nets: Vec<((u8, u128, u8), String, &Value)> = Vec::new();
286    for p in peers {
287        let mut mine: HashSet<(u8, u128, u8)> = HashSet::new();
288        for raw in field_all(p, "AllowedIPs") {
289            if is_ref(raw) {
290                continue;
291            }
292            for item in split_list(raw) {
293                let Some(net) = network(&item) else { continue };
294                if !mine.insert(net) {
295                    continue;
296                }
297                if let Some(other) = seen.get(&net) {
298                    out.push(finding(
299                        "wireguard-allowed-ips-duplicate",
300                        "error",
301                        p,
302                        "AllowedIPs",
303                        format!(
304                            "AllowedIPs `{item}` is also claimed by peer `{}`; WireGuard gives the address to only one of them",
305                            s(other, "name")
306                        ),
307                        vec![s(other, "name").to_string()],
308                    ));
309                } else {
310                    seen.insert(net, p);
311                    nets.push((net, item.clone(), p));
312                }
313            }
314        }
315    }
316    // Strict containment between different peers, excluding default routes.
317    for (outer, outer_text, op) in &nets {
318        if outer.2 == 0 {
319            continue;
320        }
321        for (inner, inner_text, ip) in &nets {
322            if std::ptr::eq(*op, *ip) || !contains(*outer, *inner) {
323                continue;
324            }
325            out.push(finding(
326                "wireguard-allowed-ips-overlap",
327                "warning",
328                ip,
329                "AllowedIPs",
330                format!(
331                    "AllowedIPs `{inner_text}` sits inside `{outer_text}` claimed by peer `{}`; WireGuard sends it to this peer (longest prefix), so the wider peer never sees it",
332                    s(op, "name")
333                ),
334                vec![s(op, "name").to_string()],
335            ));
336        }
337    }
338}
339
340// ── Rule 3: a Traefik router naming a middleware that does not exist ────────
341
342fn rule_traefik_middleware(chunks: &[&Value], out: &mut Vec<Finding>) {
343    let defined: HashSet<String> = of_type(chunks, "traefik_middleware")
344        .iter()
345        .map(|m| s(m, "name").to_lowercase())
346        .collect();
347    for router in of_type(chunks, "traefik_router") {
348        for raw in field_all(router, "middlewares") {
349            if is_ref(raw) {
350                continue;
351            }
352            for name in split_list(raw) {
353                // `name@provider` lives in another provider; not ours to judge.
354                if name.contains('@') || defined.contains(&name.to_lowercase()) {
355                    continue;
356                }
357                out.push(finding(
358                    "traefik-middleware-missing",
359                    "warning",
360                    router,
361                    "middlewares",
362                    format!(
363                        "router uses middleware `{name}`, which no traefik_middleware chunk defines (write `{name}@file` if it lives in another file)"
364                    ),
365                    vec![],
366                ));
367            }
368        }
369    }
370}
371
372// ── Rule 4: a Deployment consuming a Secret no chunk creates ─────────────────
373//
374// A Deployment names Secrets in `secretEnv` (list) and `secretMounts`
375// (`secret:/path` list); the exporters turn them into `envFrom` and a volume.
376// Silent when the project has no `k8s_secret` chunk at all: the Secret may be
377// created by another manifest set, and a rule that fires there is a rule that
378// gets switched off. The same family also checks an Ingress's Service.
379
380fn split_list_k8s(raw: &str) -> Vec<String> {
381    split_list(raw)
382}
383
384fn rule_k8s_secrets(chunks: &[&Value], out: &mut Vec<Finding>) {
385    let secrets = of_type(chunks, "k8s_secret");
386    if secrets.is_empty() {
387        return;
388    }
389    let defined: HashSet<(String, String)> =
390        secrets.iter().map(|c| (k8s_name(c), k8s_ns(c))).collect();
391    for dep in of_type(chunks, "k8s_deployment") {
392        let ns = k8s_ns(dep);
393        let mut wanted: Vec<(&str, String)> = Vec::new();
394        for raw in field_all(dep, "secretEnv") {
395            for n in split_list_k8s(raw) {
396                wanted.push(("secretEnv", n));
397            }
398        }
399        for raw in field_all(dep, "secretMounts") {
400            for m in split_list_k8s(raw) {
401                if let Some(i) = m.find(':').filter(|i| *i > 0 && *i < m.len() - 1) {
402                    wanted.push(("secretMounts", m[..i].to_string()));
403                }
404            }
405        }
406        let mut reported: HashSet<String> = HashSet::new();
407        for (key, n) in wanted {
408            if is_ref(&n)
409                || defined.contains(&(n.clone(), ns.clone()))
410                || !reported.insert(n.clone())
411            {
412                continue;
413            }
414            out.push(finding(
415                "k8s-deployment-secret-missing",
416                "error",
417                dep,
418                key,
419                format!("Deployment uses Secret `{n}` in namespace `{ns}`, which no k8s_secret chunk creates; the Pod will not start"),
420                secrets.iter().map(|c| k8s_name(c)).collect(),
421            ));
422        }
423    }
424}
425
426// ── Rule 4b: a Kubernetes Ingress backed by a Service no chunk defines ───────
427
428fn k8s_name(chunk: &Value) -> String {
429    let n = field(chunk, "name");
430    if n.is_empty() { s(chunk, "name") } else { n }.to_string()
431}
432
433fn k8s_ns(chunk: &Value) -> String {
434    let n = field(chunk, "namespace");
435    if n.is_empty() { "default" } else { n }.to_string()
436}
437
438fn rule_k8s_ingress(chunks: &[&Value], out: &mut Vec<Finding>) {
439    let services = of_type(chunks, "k8s_service");
440    if services.is_empty() {
441        return;
442    }
443    let defined: HashSet<(String, String)> =
444        services.iter().map(|c| (k8s_name(c), k8s_ns(c))).collect();
445    for ing in of_type(chunks, "k8s_ingress") {
446        let svc = {
447            let v = field(ing, "serviceName");
448            if v.is_empty() {
449                k8s_name(ing)
450            } else {
451                v.to_string()
452            }
453        };
454        if is_ref(&svc) {
455            continue;
456        }
457        let ns = k8s_ns(ing);
458        if !defined.contains(&(svc.clone(), ns.clone())) {
459            out.push(finding(
460                "k8s-ingress-service-missing",
461                "warning",
462                ing,
463                "serviceName",
464                format!("Ingress routes to Service `{svc}` in namespace `{ns}`, which no k8s_service chunk defines"),
465                services.iter().map(|c| k8s_name(c)).collect(),
466            ));
467        }
468    }
469}
470
471// ── Rule 5: a Compose service reading a variable nothing provides ───────────
472//
473// Compose substitutes `${NAME}` anywhere in a service from the `.env` beside the
474// file and the shell. In this model that `.env` is built from the vault references
475// the exporter derives (one per environment field holding a reference) and from
476// env_file chunks. So a `${NAME}` in any service value (image tag, port, command,
477// an environment value) must be a key some env_file chunk sets, or a vault entry.
478// `${NAME:-default}` and the other operator forms carry their own fallback and
479// are not reported; `$${NAME}` is an escaped literal.
480
481/// `${NAME}` tokens in `value` whose body is a plain name or `Provider/field`,
482/// with no operator, skipping `$${…}` escapes.
483fn compose_tokens(value: &str) -> Vec<String> {
484    let b = value.as_bytes();
485    let mut out = Vec::new();
486    let mut i = 0;
487    while i + 1 < b.len() {
488        if b[i] == b'$' && b[i + 1] == b'$' {
489            i += 2;
490            continue;
491        }
492        if b[i] == b'$' && b[i + 1] == b'{' {
493            if let Some(end) = value[i + 2..].find('}') {
494                let body = &value[i + 2..i + 2 + end];
495                if !body.is_empty()
496                    && !body.contains(":-")
497                    && !body.contains(":?")
498                    && !body.contains('-')
499                    && !body.contains('?')
500                    && !body.contains('+')
501                {
502                    out.push(body.to_string());
503                }
504                i += 2 + end + 1;
505                continue;
506            }
507        }
508        i += 1;
509    }
510    out
511}
512
513/// `known` is the vault's entry names (provider, and `provider_keyid`).
514fn rule_compose_env(chunks: &[&Value], known: &[String], out: &mut Vec<Finding>) {
515    let env_keys: HashSet<String> = of_type(chunks, "env_file")
516        .iter()
517        .flat_map(|c| fields(c))
518        .map(|f| norm(s(f, "key")))
519        .collect();
520    let providers: Vec<String> = known.iter().map(|k| norm(k)).collect();
521    let resolves = |name: &str| -> bool {
522        if name.starts_with("chunk:") || name.starts_with("bundle:") {
523            return true; // resolved by machinery this module does not duplicate
524        }
525        let head = name.split('/').next().unwrap_or(name);
526        let n = norm(head);
527        env_keys.contains(&n)
528            || providers
529                .iter()
530                .any(|p| !p.is_empty() && (n == *p || n.starts_with(&format!("{p}_"))))
531    };
532    for svc in of_type(chunks, "docker_service") {
533        for f in fields(svc) {
534            let raw = s(f, "value");
535            let mut names: Vec<String> = Vec::new();
536            if !s(f, "ref_name").is_empty() {
537                names.push(s(f, "ref_name").to_string());
538            }
539            names.extend(compose_tokens(raw));
540            let mut reported: HashSet<String> = HashSet::new();
541            for name in names {
542                if resolves(&name) || !reported.insert(name.clone()) {
543                    continue;
544                }
545                out.push(finding(
546                    "compose-env-ref-unresolved",
547                    "warning",
548                    svc,
549                    s(f, "key"),
550                    format!(
551                        "`{}` reads `${{{name}}}`, which is neither a vault entry nor a key in an env_file chunk",
552                        s(f, "key")
553                    ),
554                    vec![],
555                ));
556            }
557        }
558    }
559}
560
561// ── Rule 6: a pg_connection host on a network its caller is not attached to ─
562
563fn networks_of(svc: &Value) -> Option<HashSet<String>> {
564    // `network_mode` replaces networking altogether; nothing to compare.
565    if !field(svc, "network_mode").is_empty() {
566        return None;
567    }
568    let listed: HashSet<String> = field_all(svc, "networks")
569        .iter()
570        .flat_map(|v| split_list(v))
571        .collect();
572    Some(if listed.is_empty() {
573        HashSet::from(["default".to_string()])
574    } else {
575        listed
576    })
577}
578
579fn mentions(svc: &Value, name: &str) -> bool {
580    if field_all(svc, "depends_on")
581        .iter()
582        .flat_map(|v| split_list(v))
583        .any(|d| d.to_lowercase() == name)
584    {
585        return true;
586    }
587    fields(svc)
588        .into_iter()
589        .filter(|f| s(f, "description") == "env" || s(f, "field_type") == "env_var")
590        .any(|f| {
591            s(f, "value")
592                .to_lowercase()
593                .split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')))
594                .any(|tok| tok == name)
595        })
596}
597
598/// A service that reads the connection through `${chunk:<pg chunk>/…}` consumes it
599/// even though no env value spells the host.
600fn reads_chunk(svc: &Value, pg_name: &str) -> bool {
601    let needle = format!("chunk:{}", pg_name.to_lowercase());
602    fields(svc).into_iter().any(|f| {
603        let v = s(f, "value").to_lowercase();
604        let r = s(f, "ref_name").to_lowercase();
605        v.contains(&needle) || r.contains(&needle)
606    })
607}
608
609fn rule_pg_network(chunks: &[&Value], out: &mut Vec<Finding>) {
610    let services = of_type(chunks, "docker_service");
611    for pg in of_type(chunks, "pg_connection") {
612        let host = field(pg, "host").to_lowercase();
613        if host.is_empty() || is_ref(&host) {
614            continue;
615        }
616        let Some(db) = services.iter().find(|c| service_aliases(c).contains(&host)) else {
617            continue;
618        };
619        let Some(db_nets) = networks_of(db) else {
620            continue;
621        };
622        for c in &services {
623            if std::ptr::eq(*c, *db) {
624                continue;
625            }
626            let Some(c_nets) = networks_of(c) else {
627                continue;
628            };
629            let reaches =
630                service_aliases(db).iter().any(|a| mentions(c, a)) || reads_chunk(c, s(pg, "name"));
631            if reaches && c_nets.is_disjoint(&db_nets) {
632                out.push(finding(
633                    "pg-host-network-unreachable",
634                    "warning",
635                    pg,
636                    "host",
637                    format!(
638                        "host `{host}` is Docker service `{}`, but service `{}` uses it and shares no network with it",
639                        service_name(db),
640                        service_name(c)
641                    ),
642                    vec![service_name(db), service_name(c)],
643                ));
644            }
645        }
646    }
647}
648
649// ── Phase 29.1 rules ──────────────────────────────────────────────────────────
650//
651// Each fires only on positive evidence the project defines the thing it checks
652// against, and stays silent on anything that could live somewhere unseen.
653
654/// A Traefik router naming a `service` no `traefik_service` chunk defines.
655/// Silent when the project defines no service chunk at all (Traefik can build one
656/// from labels or another file), and for `name@provider` references.
657fn rule_traefik_service(chunks: &[&Value], out: &mut Vec<Finding>) {
658    let defined: HashSet<String> = of_type(chunks, "traefik_service")
659        .iter()
660        .map(|c| s(c, "name").to_lowercase())
661        .collect();
662    if defined.is_empty() {
663        return;
664    }
665    for router in of_type(chunks, "traefik_router") {
666        for raw in field_all(router, "service") {
667            if is_ref(raw) || raw.contains('@') || defined.contains(&raw.to_lowercase()) {
668                continue;
669            }
670            out.push(finding(
671                "traefik-service-missing",
672                "warning",
673                router,
674                "service",
675                format!(
676                    "router names service `{raw}`, which no traefik_service chunk defines (write `{raw}@file` if it lives in another file)"
677                ),
678                vec![],
679            ));
680        }
681    }
682}
683
684/// An `nginx_upstream` no `proxy_pass` in this project names. Silent when the
685/// project has no server or location chunk (the upstream may be used by a
686/// config this project does not hold).
687fn rule_nginx_upstream_unused(chunks: &[&Value], out: &mut Vec<Finding>) {
688    let users: Vec<&Value> = ["nginx_location", "nginx_server"]
689        .iter()
690        .flat_map(|t| of_type(chunks, t))
691        .collect();
692    if users.is_empty() {
693        return;
694    }
695    let mut used = HashSet::new();
696    for c in &users {
697        for target in field_all(c, "proxy_pass") {
698            if is_ref(target) {
699                return; // a reference could name any upstream: cannot judge
700            }
701            if let Some(h) = proxy_host(target) {
702                used.insert(h);
703            }
704        }
705    }
706    for u in of_type(chunks, "nginx_upstream") {
707        let name = s(u, "name").to_lowercase();
708        if !name.is_empty() && !used.contains(&name) {
709            out.push(finding(
710                "nginx-upstream-unused",
711                "warning",
712                u,
713                "name",
714                format!("upstream `{name}` is not named by any proxy_pass in this project"),
715                vec![],
716            ));
717        }
718    }
719}
720
721/// `depends_on` naming a service the project does not define. Silent with no
722/// `docker_service` chunk, and for references.
723fn rule_compose_depends_on(chunks: &[&Value], out: &mut Vec<Finding>) {
724    let services = of_type(chunks, "docker_service");
725    if services.is_empty() {
726        return;
727    }
728    let known: HashSet<String> = services.iter().flat_map(|c| service_aliases(c)).collect();
729    for svc in &services {
730        for raw in field_all(svc, "depends_on") {
731            if is_ref(raw) {
732                continue;
733            }
734            for dep in split_list(raw) {
735                if !known.contains(&dep.to_lowercase()) {
736                    out.push(finding(
737                        "compose-depends-on-unknown-service",
738                        "error",
739                        svc,
740                        "depends_on",
741                        format!("depends_on names `{dep}`, which is not a service in this project"),
742                        vec![],
743                    ));
744                }
745            }
746        }
747    }
748}
749
750/// `(ip, port, proto)` of a published port mapping, or `None` for a container-only
751/// port, a range, a reference or anything unreadable.
752fn published(spec: &str) -> Option<(String, String, String)> {
753    if is_ref(spec) {
754        return None;
755    }
756    let (body, proto) = spec.split_once('/').unwrap_or((spec, "tcp"));
757    let parts: Vec<&str> = body.split(':').collect();
758    let (ip, host) = match parts.as_slice() {
759        [host, _container] => ("", *host),
760        [ip, host, _container] => (*ip, *host),
761        _ => return None,
762    };
763    if host.is_empty() || !host.chars().all(|c| c.is_ascii_digit()) {
764        return None;
765    }
766    let ip = if ip == "0.0.0.0" { "" } else { ip };
767    Some((ip.to_string(), host.to_string(), proto.to_lowercase()))
768}
769
770/// Two services publishing the same host port. Compose refuses to start the second.
771fn rule_compose_port_clash(chunks: &[&Value], out: &mut Vec<Finding>) {
772    let services = of_type(chunks, "docker_service");
773    let mut seen: Vec<((String, String, String), &Value)> = Vec::new();
774    for svc in &services {
775        for raw in field_all(svc, "ports") {
776            for spec in split_list(raw) {
777                let Some(p) = published(&spec) else {
778                    continue;
779                };
780                let clash = seen.iter().find(|(q, other)| {
781                    !std::ptr::eq(*other, *svc)
782                        && q.1 == p.1
783                        && q.2 == p.2
784                        && (q.0 == p.0 || q.0.is_empty() || p.0.is_empty())
785                });
786                if let Some((_, other)) = clash {
787                    out.push(finding(
788                        "compose-port-clash",
789                        "error",
790                        svc,
791                        "ports",
792                        format!(
793                            "host port {}/{} is also published by service `{}`",
794                            p.1,
795                            p.2,
796                            service_name(other)
797                        ),
798                        vec![service_name(other)],
799                    ));
800                }
801                seen.push((p, svc));
802            }
803        }
804    }
805}
806
807// ── Rule: a service on a network no docker_network chunk declares ───────────
808//
809// Silent unless the project declares at least one network (positive evidence the
810// author manages them here); `default` always exists in Compose.
811
812fn rule_compose_network(chunks: &[&Value], out: &mut Vec<Finding>) {
813    let nets = of_type(chunks, "docker_network");
814    if nets.is_empty() {
815        return;
816    }
817    let mut declared: HashSet<String> = HashSet::from(["default".to_string()]);
818    for n in &nets {
819        let keys: Vec<String> = fields(n)
820            .into_iter()
821            .map(|f| s(f, "key").to_lowercase())
822            .filter(|k| !k.is_empty())
823            .collect();
824        if keys.is_empty() {
825            declared.insert(s(n, "name").to_lowercase());
826        }
827        declared.extend(keys);
828    }
829    for svc in of_type(chunks, "docker_service") {
830        for raw in field_all(svc, "networks") {
831            if is_ref(raw) {
832                continue;
833            }
834            for net in split_list(raw) {
835                if !declared.contains(&net.to_lowercase()) {
836                    out.push(finding(
837                        "compose-network-undeclared",
838                        "error",
839                        svc,
840                        "networks",
841                        format!(
842                            "Service joins network `{net}`, which no docker_network chunk declares"
843                        ),
844                        vec![],
845                    ));
846                }
847            }
848        }
849    }
850}
851
852// ── Rule: a k8s Service whose selector matches no Deployment ────────────────
853//
854// The starters generate `selector: app: <name>` and a Deployment's pod label
855// `app: <name>`, so the selector matches exactly the Deployment of the same name
856// and namespace. Silent when the project has no Deployment at all.
857
858fn rule_k8s_service_selector(chunks: &[&Value], out: &mut Vec<Finding>) {
859    let deps = of_type(chunks, "k8s_deployment");
860    if deps.is_empty() {
861        return;
862    }
863    let defined: HashSet<(String, String)> =
864        deps.iter().map(|c| (k8s_name(c), k8s_ns(c))).collect();
865    for svc in of_type(chunks, "k8s_service") {
866        let (n, ns) = (k8s_name(svc), k8s_ns(svc));
867        if is_ref(&n) || n.is_empty() || defined.contains(&(n.clone(), ns.clone())) {
868            continue;
869        }
870        out.push(finding(
871            "k8s-service-selector-unmatched",
872            "warning",
873            svc,
874            "name",
875            format!("Service `{n}` selects `app: {n}` in namespace `{ns}`, which no k8s_deployment chunk labels; it will have no endpoints"),
876            deps.iter().map(|c| k8s_name(c)).collect(),
877        ));
878    }
879}
880
881/// Run every rule over one project. `vault_names` are the vault's entry names
882/// (provider, and `provider_keyid`) so a `${…}` reference to a real entry is not
883/// reported; pass an empty slice to skip nothing and report every non-env_file ref.
884pub fn check_project(project: &Value, vault_names: &[String]) -> Vec<Finding> {
885    check_project_scoped(project, vault_names, &[])
886}
887
888/// Every Compose service name (and `container_name`) any of `projects` defines,
889/// lowercased. Passed to [`check_project_scoped`] as `elsewhere` so a `proxy_pass`
890/// is resolved against the whole stack, which is how people split one.
891pub fn services_of(projects: &[Value]) -> Vec<String> {
892    let mut v: Vec<String> = projects
893        .iter()
894        .flat_map(|p| {
895            let chunks = active_chunks(p);
896            of_type(&chunks, "docker_service")
897                .into_iter()
898                .flat_map(service_aliases)
899                .collect::<Vec<_>>()
900        })
901        .collect();
902    v.sort();
903    v.dedup();
904    v
905}
906
907/// As [`check_project`], with `elsewhere` (see [`services_of`]) widening what an
908/// nginx `proxy_pass` host may resolve to. Off by default because it widens the
909/// evidence a rule may use: a name another project defines is not wired to this one.
910pub fn check_project_scoped(
911    project: &Value,
912    vault_names: &[String],
913    elsewhere: &[String],
914) -> Vec<Finding> {
915    let chunks = active_chunks(project);
916    let mut out = Vec::new();
917    rule_nginx_proxy_pass(&chunks, elsewhere, &mut out);
918    rule_wireguard_allowed_ips(&chunks, &mut out);
919    rule_traefik_middleware(&chunks, &mut out);
920    rule_k8s_secrets(&chunks, &mut out);
921    rule_k8s_ingress(&chunks, &mut out);
922    rule_compose_env(&chunks, vault_names, &mut out);
923    rule_pg_network(&chunks, &mut out);
924    rule_traefik_service(&chunks, &mut out);
925    rule_nginx_upstream_unused(&chunks, &mut out);
926    rule_compose_depends_on(&chunks, &mut out);
927    rule_compose_port_clash(&chunks, &mut out);
928    rule_compose_network(&chunks, &mut out);
929    rule_k8s_service_selector(&chunks, &mut out);
930    // A stack integration (Phase 38) brings its own rules in its descriptor.
931    if let Some(a) = crate::stack::adapter(s(project, "project_type")) {
932        out.extend(crate::stack::check(a, project, vault_names));
933    }
934    out
935}
936
937/// The push gate: the error-severity findings that must stop a node from writing
938/// this project's config to a live host. Empty means go. A warning never gates.
939pub fn gate(project: &Value, vault_names: &[String]) -> Vec<Finding> {
940    check_project(project, vault_names)
941        .into_iter()
942        .filter(|f| f.severity == "error")
943        .collect()
944}
945
946/// The rule ids, in the order they run — `unv describe` and the panel list them.
947pub const RULES: [&str; 14] = [
948    "nginx-proxy-pass-unknown-service",
949    "wireguard-allowed-ips-duplicate",
950    "wireguard-allowed-ips-overlap",
951    "traefik-middleware-missing",
952    "k8s-deployment-secret-missing",
953    "k8s-ingress-service-missing",
954    "compose-env-ref-unresolved",
955    "pg-host-network-unreachable",
956    "traefik-service-missing",
957    "nginx-upstream-unused",
958    "compose-depends-on-unknown-service",
959    "compose-port-clash",
960    "compose-network-undeclared",
961    "k8s-service-selector-unmatched",
962];
963
964#[cfg(test)]
965mod tests {
966    use super::*;
967
968    fn f(key: &str, value: &str) -> Value {
969        json!({"key": key, "value": value, "field_type": "var"})
970    }
971    fn chunk(name: &str, t: &str, fields: Vec<Value>) -> Value {
972        json!({"id": format!("id-{name}"), "name": name, "chunk_type": t, "fields": fields})
973    }
974    fn project(chunks: Vec<Value>) -> Value {
975        json!({"id": "p", "name": "p", "chunks": chunks})
976    }
977    fn rules(p: &Value, names: &[&str]) -> Vec<&'static str> {
978        let names: Vec<String> = names.iter().map(|s| s.to_string()).collect();
979        check_project(p, &names).iter().map(|x| x.rule).collect()
980    }
981
982    #[test]
983    fn proxy_pass_to_an_undefined_service_is_flagged_but_only_when_services_exist() {
984        let loc = |t: &str| {
985            chunk(
986                "loc",
987                "nginx_location",
988                vec![f("path", "/"), f("proxy_pass", t)],
989            )
990        };
991        let svc = chunk("web app", "docker_service", vec![f("image", "x")]);
992        assert_eq!(
993            rules(&project(vec![loc("http://api:8080"), svc.clone()]), &[]),
994            ["nginx-proxy-pass-unknown-service"]
995        );
996        // The service the project does define, under the name Compose gives it.
997        assert!(rules(
998            &project(vec![loc("http://web_app:8080/x"), svc.clone()]),
999            &[]
1000        )
1001        .is_empty());
1002        // No docker_service chunk at all: no evidence, no finding.
1003        assert!(rules(&project(vec![loc("http://api:8080")]), &[]).is_empty());
1004        // Not service-style names: dotted, IP, localhost, variable.
1005        for t in [
1006            "http://api.example.com",
1007            "http://10.0.0.5:80",
1008            "http://localhost:3000",
1009            "http://$backend",
1010            "http://unix:/run/x.sock",
1011        ] {
1012            assert!(
1013                rules(&project(vec![loc(t), svc.clone()]), &[]).is_empty(),
1014                "{t}"
1015            );
1016        }
1017    }
1018
1019    #[test]
1020    fn an_upstream_defined_in_the_project_satisfies_proxy_pass() {
1021        let up = chunk(
1022            "backend",
1023            "nginx_upstream",
1024            vec![f("server", "10.0.0.1:80")],
1025        );
1026        let loc = chunk(
1027            "loc",
1028            "nginx_location",
1029            vec![f("proxy_pass", "http://backend")],
1030        );
1031        let svc = chunk("web", "docker_service", vec![]);
1032        assert!(rules(&project(vec![up, loc, svc]), &[]).is_empty());
1033    }
1034
1035    #[test]
1036    fn two_peers_with_the_same_network_are_an_error_but_nesting_is_fine() {
1037        let peer = |n: &str, ips: &str| chunk(n, "wg_peer", vec![f("AllowedIPs", ips)]);
1038        assert_eq!(
1039            rules(
1040                &project(vec![peer("a", "10.0.0.2/32"), peer("b", "10.0.0.2")]),
1041                &[]
1042            ),
1043            ["wireguard-allowed-ips-duplicate"]
1044        );
1045        // Host bits are ignored: 10.0.0.5/24 and 10.0.0.9/24 are one network.
1046        assert_eq!(
1047            rules(
1048                &project(vec![peer("a", "10.0.0.5/24"), peer("b", "10.0.0.9/24")]),
1049                &[]
1050            )
1051            .len(),
1052            1
1053        );
1054        // Longest-prefix routing makes a catch-all beside a host route valid.
1055        assert!(rules(
1056            &project(vec![peer("a", "0.0.0.0/0, ::/0"), peer("b", "10.0.0.2/32")]),
1057            &[]
1058        )
1059        .is_empty());
1060        // One peer repeating itself is its own business; references are skipped.
1061        assert!(rules(&project(vec![peer("a", "10.0.0.2/32, 10.0.0.2/32")]), &[]).is_empty());
1062        assert!(rules(&project(vec![peer("a", "${X}"), peer("b", "${X}")]), &[]).is_empty());
1063    }
1064
1065    #[test]
1066    fn a_disabled_peer_is_not_in_the_export_and_is_not_checked() {
1067        let mut b = chunk("b", "wg_peer", vec![f("AllowedIPs", "10.0.0.2/32")]);
1068        b["disabled"] = json!(true);
1069        let a = chunk("a", "wg_peer", vec![f("AllowedIPs", "10.0.0.2/32")]);
1070        assert!(rules(&project(vec![a, b]), &[]).is_empty());
1071    }
1072
1073    #[test]
1074    fn traefik_middleware_must_exist_unless_it_names_another_provider() {
1075        let router = |m: &str| chunk("r", "traefik_router", vec![f("middlewares", m)]);
1076        let mw = chunk("auth", "traefik_middleware", vec![f("type", "basicAuth")]);
1077        assert_eq!(
1078            rules(&project(vec![router("auth, gone"), mw.clone()]), &[]),
1079            ["traefik-middleware-missing"]
1080        );
1081        assert!(rules(&project(vec![router("AUTH"), mw.clone()]), &[]).is_empty());
1082        assert!(rules(&project(vec![router("sso@docker, api@internal")]), &[]).is_empty());
1083    }
1084
1085    #[test]
1086    fn an_ingress_needs_a_service_in_the_same_namespace_but_only_when_services_exist() {
1087        let svc = chunk(
1088            "s",
1089            "k8s_service",
1090            vec![f("name", "my-app"), f("namespace", "prod")],
1091        );
1092        let ing = |n: &str, ns: &str| {
1093            chunk(
1094                "i",
1095                "k8s_ingress",
1096                vec![f("serviceName", n), f("namespace", ns)],
1097            )
1098        };
1099        assert!(rules(&project(vec![svc.clone(), ing("my-app", "prod")]), &[]).is_empty());
1100        assert_eq!(
1101            rules(&project(vec![svc.clone(), ing("my-app", "default")]), &[]),
1102            ["k8s-ingress-service-missing"]
1103        );
1104        assert_eq!(
1105            rules(&project(vec![svc, ing("other", "prod")]), &[]),
1106            ["k8s-ingress-service-missing"]
1107        );
1108        assert!(rules(&project(vec![ing("anything", "prod")]), &[]).is_empty());
1109    }
1110
1111    #[test]
1112    fn a_compose_env_ref_must_resolve_to_a_vault_entry_or_an_env_file_key() {
1113        let env = |v: &str| json!({"key": "DB_PASS", "value": v, "field_type": "env_var", "description": "env"});
1114        let svc = |v: &str| chunk("web", "docker_service", vec![env(v)]);
1115        assert_eq!(
1116            rules(&project(vec![svc("${NOPE}")]), &["GitHub"]),
1117            ["compose-env-ref-unresolved"]
1118        );
1119        assert!(rules(&project(vec![svc("${GitHub/key}")]), &["GitHub"]).is_empty());
1120        assert!(rules(&project(vec![svc("${GITHUB_PROD}")]), &["GitHub"]).is_empty());
1121        let envf = chunk("e", "env_file", vec![f("NOPE", "1")]);
1122        assert!(rules(&project(vec![svc("${NOPE}"), envf]), &[]).is_empty());
1123        assert!(rules(&project(vec![svc("${chunk:x/y}")]), &[]).is_empty());
1124        assert!(rules(&project(vec![svc("plain")]), &[]).is_empty());
1125    }
1126
1127    #[test]
1128    fn a_pg_host_service_must_share_a_network_with_the_service_that_uses_it() {
1129        let pg = chunk("p", "pg_connection", vec![f("host", "db")]);
1130        let db = |nets: &str| chunk("db", "docker_service", vec![f("networks", nets)]);
1131        let app = |nets: &str| {
1132            chunk(
1133                "app",
1134                "docker_service",
1135                vec![f("networks", nets), f("depends_on", "db")],
1136            )
1137        };
1138        assert_eq!(
1139            rules(&project(vec![pg.clone(), db("back"), app("front")]), &[]),
1140            ["pg-host-network-unreachable"]
1141        );
1142        assert!(rules(
1143            &project(vec![pg.clone(), db("back"), app("front, back")]),
1144            &[]
1145        )
1146        .is_empty());
1147        // Both on the implicit default network.
1148        assert!(rules(&project(vec![pg.clone(), db(""), app("")]), &[]).is_empty());
1149        // Nothing uses the db: nothing to say.
1150        let idle = chunk("idle", "docker_service", vec![f("networks", "front")]);
1151        assert!(rules(&project(vec![pg.clone(), db("back"), idle]), &[]).is_empty());
1152        // network_mode opts out of comparison.
1153        let host_mode = chunk(
1154            "app",
1155            "docker_service",
1156            vec![f("network_mode", "host"), f("depends_on", "db")],
1157        );
1158        assert!(rules(&project(vec![pg, db("back"), host_mode]), &[]).is_empty());
1159    }
1160
1161    #[test]
1162    fn findings_carry_names_and_never_field_values_that_could_be_secret() {
1163        let pg = chunk(
1164            "p",
1165            "pg_connection",
1166            vec![
1167                f("host", "db"),
1168                json!({"key":"password","value":"hunter2-SECRET","field_type":"secret"}),
1169            ],
1170        );
1171        let db = chunk("db", "docker_service", vec![f("networks", "back")]);
1172        let app = chunk(
1173            "app",
1174            "docker_service",
1175            vec![f("networks", "front"), f("depends_on", "db")],
1176        );
1177        let out = check_project(&project(vec![pg, db, app]), &[]);
1178        let text =
1179            serde_json::to_string(&out.iter().map(Finding::to_json).collect::<Vec<_>>()).unwrap();
1180        assert!(!text.contains("hunter2"));
1181    }
1182
1183    #[test]
1184    fn nested_allowed_ips_are_a_warning_and_a_default_route_is_not_reported() {
1185        let peer = |n: &str, ips: &str| chunk(n, "wg_peer", vec![f("AllowedIPs", ips)]);
1186        assert_eq!(
1187            rules(
1188                &project(vec![peer("a", "10.0.0.0/24"), peer("b", "10.0.0.7/32")]),
1189                &[]
1190            ),
1191            ["wireguard-allowed-ips-overlap"]
1192        );
1193        // Disjoint networks, and a catch-all beside host routes, are fine.
1194        assert!(rules(
1195            &project(vec![peer("a", "10.0.0.0/24"), peer("b", "10.0.1.7/32")]),
1196            &[]
1197        )
1198        .is_empty());
1199        assert!(rules(
1200            &project(vec![peer("a", "0.0.0.0/0"), peer("b", "10.0.0.7/32")]),
1201            &[]
1202        )
1203        .is_empty());
1204        // Different families never nest.
1205        assert!(rules(
1206            &project(vec![peer("a", "10.0.0.0/8"), peer("b", "fd00::1/128")]),
1207            &[]
1208        )
1209        .is_empty());
1210        // IPv6 nesting.
1211        assert_eq!(
1212            rules(
1213                &project(vec![peer("a", "fd00::/64"), peer("b", "fd00::5/128")]),
1214                &[]
1215            ),
1216            ["wireguard-allowed-ips-overlap"]
1217        );
1218    }
1219
1220    #[test]
1221    fn a_deployment_must_use_secrets_some_chunk_creates() {
1222        let secret = chunk(
1223            "app-secrets",
1224            "k8s_secret",
1225            vec![f("name", "app-secrets"), f("namespace", "prod")],
1226        );
1227        let dep = |env: &str, mounts: &str, ns: &str| {
1228            chunk(
1229                "web",
1230                "k8s_deployment",
1231                vec![
1232                    f("secretEnv", env),
1233                    f("secretMounts", mounts),
1234                    f("namespace", ns),
1235                ],
1236            )
1237        };
1238        assert!(rules(
1239            &project(vec![
1240                secret.clone(),
1241                dep("app-secrets", "app-secrets:/etc/a", "prod")
1242            ]),
1243            &[]
1244        )
1245        .is_empty());
1246        assert_eq!(
1247            rules(&project(vec![secret.clone(), dep("gone", "", "prod")]), &[]),
1248            ["k8s-deployment-secret-missing"]
1249        );
1250        assert_eq!(
1251            rules(
1252                &project(vec![secret.clone(), dep("", "gone:/x", "prod")]),
1253                &[]
1254            ),
1255            ["k8s-deployment-secret-missing"]
1256        );
1257        // Wrong namespace is a missing Secret.
1258        assert_eq!(
1259            rules(
1260                &project(vec![secret.clone(), dep("app-secrets", "", "default")]),
1261                &[]
1262            ),
1263            ["k8s-deployment-secret-missing"]
1264        );
1265        // Named twice, reported once. A malformed mount (no path) names nothing.
1266        assert_eq!(
1267            rules(
1268                &project(vec![
1269                    secret.clone(),
1270                    dep("gone gone", "gone:/x, nopath:", "prod")
1271                ]),
1272                &[]
1273            )
1274            .len(),
1275            1
1276        );
1277        // No k8s_secret chunk at all: another manifest set may create it.
1278        assert!(rules(&project(vec![dep("gone", "gone:/x", "prod")]), &[]).is_empty());
1279    }
1280
1281    #[test]
1282    fn compose_substitution_tokens_anywhere_in_a_service_must_resolve() {
1283        let svc = |fields: Vec<Value>| chunk("web", "docker_service", fields);
1284        // An image tag reading ${TAG} that nothing sets.
1285        assert_eq!(
1286            rules(&project(vec![svc(vec![f("image", "app:${TAG}")])]), &[]),
1287            ["compose-env-ref-unresolved"]
1288        );
1289        // Set by an env_file chunk, case-insensitively.
1290        let envf = chunk("e", "env_file", vec![f("tag", "1")]);
1291        assert!(rules(
1292            &project(vec![svc(vec![f("image", "app:${TAG}")]), envf]),
1293            &[]
1294        )
1295        .is_empty());
1296        // Defaults, escapes and operators are the author's own fallback.
1297        for v in [
1298            "app:${TAG:-latest}",
1299            "app:${TAG-latest}",
1300            "$${TAG}",
1301            "app:${TAG:?need it}",
1302            "a:${TAG+x}",
1303        ] {
1304            assert!(
1305                rules(&project(vec![svc(vec![f("image", v)])]), &[]).is_empty(),
1306                "{v}"
1307            );
1308        }
1309        // Two tokens in one value, one reported per unknown name.
1310        assert_eq!(
1311            rules(
1312                &project(vec![svc(vec![f("command", "run ${A} ${B} ${A}")])]),
1313                &[]
1314            )
1315            .len(),
1316            2
1317        );
1318    }
1319
1320    #[test]
1321    fn a_service_that_reads_the_pg_chunk_by_reference_is_a_consumer() {
1322        let pg = chunk("primary", "pg_connection", vec![f("host", "db")]);
1323        let db = chunk("db", "docker_service", vec![f("networks", "back")]);
1324        let env = json!({"key":"DB","value":"${chunk:primary/host}","field_type":"env_var","description":"env"});
1325        let app = chunk("app", "docker_service", vec![f("networks", "front"), env]);
1326        let got = rules(&project(vec![pg, db, app]), &[]);
1327        assert!(got.contains(&"pg-host-network-unreachable"), "{got:?}");
1328    }
1329    // ── Phase 29.1 ────────────────────────────────────────────────────────────
1330
1331    #[test]
1332    fn traefik_service_missing_fires_and_stays_silent() {
1333        let router = |svc: &str| {
1334            chunk(
1335                "r",
1336                "traefik_router",
1337                vec![f("rule", "Host(`a`)"), f("service", svc)],
1338            )
1339        };
1340        let svc = chunk("api", "traefik_service", vec![f("url", "http://x")]);
1341        assert_eq!(
1342            rules(&project(vec![router("web"), svc.clone()]), &[]),
1343            ["traefik-service-missing"]
1344        );
1345        assert!(rules(&project(vec![router("API"), svc.clone()]), &[]).is_empty());
1346        assert!(rules(&project(vec![router("web@docker"), svc.clone()]), &[]).is_empty());
1347        assert!(rules(&project(vec![router("${svc}"), svc]), &[]).is_empty());
1348        // No service chunk at all: no evidence.
1349        assert!(rules(&project(vec![router("web")]), &[]).is_empty());
1350    }
1351
1352    #[test]
1353    fn an_unused_upstream_fires_only_when_proxy_passes_can_be_read() {
1354        let up = chunk("backend", "nginx_upstream", vec![f("server", "x:1")]);
1355        let loc = |t: &str| {
1356            chunk(
1357                "l",
1358                "nginx_location",
1359                vec![f("path", "/"), f("proxy_pass", t)],
1360            )
1361        };
1362        assert_eq!(
1363            rules(&project(vec![up.clone(), loc("http://other")]), &[]),
1364            ["nginx-upstream-unused"]
1365        );
1366        assert!(rules(&project(vec![up.clone(), loc("http://backend/")]), &[]).is_empty());
1367        // A reference could name anything.
1368        assert!(rules(&project(vec![up.clone(), loc("${x}")]), &[]).is_empty());
1369        // No server/location chunk: the upstream may be used elsewhere.
1370        assert!(rules(&project(vec![up]), &[]).is_empty());
1371    }
1372
1373    #[test]
1374    fn depends_on_an_unknown_service_is_an_error_but_not_without_services_or_for_refs() {
1375        let svc = |n: &str, dep: &str| {
1376            chunk(
1377                n,
1378                "docker_service",
1379                vec![f("image", "x"), f("depends_on", dep)],
1380            )
1381        };
1382        let db = chunk("db", "docker_service", vec![f("image", "pg")]);
1383        assert_eq!(
1384            rules(&project(vec![svc("web", "db, cache"), db.clone()]), &[]),
1385            ["compose-depends-on-unknown-service"]
1386        );
1387        assert!(rules(&project(vec![svc("web", "DB"), db.clone()]), &[]).is_empty());
1388        assert!(rules(&project(vec![svc("web", "${deps}"), db]), &["deps"]).is_empty());
1389    }
1390
1391    #[test]
1392    fn a_published_port_two_services_bind_is_an_error() {
1393        let svc =
1394            |n: &str, p: &str| chunk(n, "docker_service", vec![f("image", "x"), f("ports", p)]);
1395        assert_eq!(
1396            rules(
1397                &project(vec![svc("a", "8080:80"), svc("b", "8080:3000")]),
1398                &[]
1399            ),
1400            ["compose-port-clash"]
1401        );
1402        // Different protocol, different host ip, container-only, range, one service twice.
1403        assert!(rules(
1404            &project(vec![svc("a", "8080:80"), svc("b", "8080:80/udp")]),
1405            &[]
1406        )
1407        .is_empty());
1408        assert!(rules(
1409            &project(vec![
1410                svc("a", "127.0.0.1:8080:80"),
1411                svc("b", "127.0.0.2:8080:80")
1412            ]),
1413            &[]
1414        )
1415        .is_empty());
1416        assert_eq!(
1417            rules(
1418                &project(vec![
1419                    svc("a", "127.0.0.1:8080:80"),
1420                    svc("b", "0.0.0.0:8080:80")
1421                ]),
1422                &[]
1423            ),
1424            ["compose-port-clash"]
1425        );
1426        assert!(rules(&project(vec![svc("a", "80"), svc("b", "80")]), &[]).is_empty());
1427        assert!(rules(
1428            &project(vec![svc("a", "8000-8010:80"), svc("b", "8000-8010:80")]),
1429            &[]
1430        )
1431        .is_empty());
1432        assert!(rules(&project(vec![svc("a", "8080:80, 9090:80")]), &[]).is_empty());
1433    }
1434
1435    #[test]
1436    fn a_service_network_must_be_declared_once_networks_are_managed_here() {
1437        let svc = |n: &str| chunk("web", "docker_service", vec![f("networks", n)]);
1438        let net = chunk("n", "docker_network", vec![f("backend", "bridge")]);
1439        assert!(rules(&project(vec![svc("backend"), net.clone()]), &[]).is_empty());
1440        assert!(rules(&project(vec![svc("default, backend"), net.clone()]), &[]).is_empty());
1441        assert_eq!(
1442            rules(&project(vec![svc("backend, other"), net]), &[]),
1443            ["compose-network-undeclared"]
1444        );
1445        assert!(rules(&project(vec![svc("anything")]), &[]).is_empty());
1446    }
1447
1448    #[test]
1449    fn a_k8s_service_needs_the_deployment_its_selector_names() {
1450        let dep = chunk(
1451            "d",
1452            "k8s_deployment",
1453            vec![f("name", "app"), f("namespace", "prod")],
1454        );
1455        let svc =
1456            |n: &str, ns: &str| chunk("s", "k8s_service", vec![f("name", n), f("namespace", ns)]);
1457        assert!(rules(&project(vec![dep.clone(), svc("app", "prod")]), &[]).is_empty());
1458        assert_eq!(
1459            rules(&project(vec![dep.clone(), svc("app", "dev")]), &[]),
1460            ["k8s-service-selector-unmatched"]
1461        );
1462        assert_eq!(
1463            rules(&project(vec![dep, svc("web", "prod")]), &[]),
1464            ["k8s-service-selector-unmatched"]
1465        );
1466        assert!(rules(&project(vec![svc("web", "prod")]), &[]).is_empty());
1467    }
1468
1469    #[test]
1470    fn a_proxy_pass_host_may_be_a_service_of_another_project_only_in_wide_scope() {
1471        let web = project(vec![chunk(
1472            "n",
1473            "nginx_location",
1474            vec![f("proxy_pass", "http://api:8080")],
1475        )]);
1476        let own = chunk("web", "docker_service", vec![]);
1477        let other = project(vec![chunk("api", "docker_service", vec![])]);
1478        // Alone, the only evidence is this project's own service: `api` is unknown.
1479        let alone = project(vec![
1480            chunk(
1481                "n",
1482                "nginx_location",
1483                vec![f("proxy_pass", "http://api:8080")],
1484            ),
1485            own,
1486        ]);
1487        assert_eq!(
1488            check_project(&alone, &[])
1489                .iter()
1490                .map(|x| x.rule)
1491                .collect::<Vec<_>>(),
1492            ["nginx-proxy-pass-unknown-service"]
1493        );
1494        let els = services_of(&[other]);
1495        assert_eq!(els, ["api"]);
1496        assert!(check_project_scoped(&alone, &[], &els).is_empty());
1497        // With no service in this project, the other projects are the evidence.
1498        assert!(check_project_scoped(&web, &[], &els).is_empty());
1499        assert!(
1500            check_project(&web, &[]).is_empty(),
1501            "no evidence, no finding"
1502        );
1503        // A name nobody defines is still reported in wide scope.
1504        let missing = project(vec![chunk(
1505            "n",
1506            "nginx_location",
1507            vec![f("proxy_pass", "http://ghost:1")],
1508        )]);
1509        assert_eq!(check_project_scoped(&missing, &[], &els).len(), 1);
1510    }
1511
1512    #[test]
1513    fn the_gate_lets_warnings_through_and_stops_errors() {
1514        let net = chunk("web", "docker_service", vec![f("networks", "nope")]);
1515        let decl = chunk("n", "docker_network", vec![f("backend", "bridge")]);
1516        assert_eq!(gate(&project(vec![net, decl]), &[]).len(), 1);
1517        let warn = project(vec![
1518            chunk(
1519                "n",
1520                "nginx_location",
1521                vec![f("proxy_pass", "http://ghost:1")],
1522            ),
1523            chunk("web", "docker_service", vec![]),
1524        ]);
1525        assert_eq!(check_project(&warn, &[]).len(), 1);
1526        assert!(gate(&warn, &[]).is_empty());
1527    }
1528}