Skip to main content

podbox/config/
validation.rs

1use anyhow::Result;
2
3use crate::config::Config;
4use crate::error::PodboxError;
5
6impl Config {
7    pub fn validate(&self) -> Result<()> {
8        let mut errors: Vec<String> = Vec::new();
9
10        if self.image.base.trim().is_empty() {
11            errors.push("image.base: must not be empty".into());
12        }
13        if self.image.name.trim().is_empty() {
14            errors.push("image.name: must not be empty".into());
15        } else if !is_valid_name(&self.image.name) {
16            errors.push(format!(
17                "image.name: '{}' contains invalid characters (use letters, digits, hyphens, underscores, dots)",
18                self.image.name
19            ));
20        }
21        if let Some(ref r) = self.image.image_ref {
22            if r.trim().is_empty() {
23                errors.push("image.image: must not be empty when set".into());
24            } else if !r.contains(':') && !r.contains('/') {
25                errors.push(format!(
26                    "image.image: '{r}' does not look like a valid image reference (missing ':' or '/')"
27                ));
28            }
29        }
30
31        if self.container.name.trim().is_empty() {
32            errors.push("container.name: must not be empty".into());
33        } else if !is_valid_name(&self.container.name) {
34            errors.push(format!(
35                "container.name: '{}' contains invalid characters (use letters, digits, hyphens, underscores, dots)",
36                self.container.name
37            ));
38        }
39        if self.container.home.as_os_str().is_empty() {
40            errors.push("container.home: must not be empty".into());
41        }
42        if self.container.shell.trim().is_empty() {
43            errors.push("container.shell: must not be empty".into());
44        }
45        if let Some(ref mem) = self.container.memory {
46            if !is_valid_memory(mem) {
47                errors.push(format!(
48                    "container.memory: '{mem}' is not a valid memory limit (e.g. '2g', '512m')"
49                ));
50            }
51        }
52        if let Some(ref cpus) = self.container.cpus {
53            if cpus.parse::<f64>().is_err() || cpus.parse::<f64>().unwrap_or(0.0) <= 0.0 {
54                errors.push(format!(
55                    "container.cpus: '{cpus}' is not a valid CPU count (e.g. '2.0', '0.5')"
56                ));
57            }
58        }
59        for (i, mount) in self.container.mounts.extra.iter().enumerate() {
60            if !mount.contains(':') {
61                errors.push(format!(
62                    "container.mounts.extra[{i}]: '{mount}' missing ':' separator (expected host:container[:options])"
63                ));
64            }
65        }
66        for (key, val) in &self.container.env {
67            if key.contains('\n') {
68                errors.push(format!("container.env: key {key:?} contains newline"));
69            }
70            if val.contains('\n') {
71                errors.push(format!("container.env: value for {key:?} contains newline"));
72            }
73        }
74
75        if let Some(ref userns) = self.security.userns {
76            let valid_userns = ["keep-id", "nomap", "private"];
77            if !valid_userns.contains(&userns.as_str()) {
78                errors.push(format!(
79                    "security.userns: '{}' is invalid (expected one of: {})",
80                    userns,
81                    valid_userns.join(", ")
82                ));
83            }
84        }
85
86        // Network validation
87        let valid_modes = ["host", "bridge", "none", "pasta", "slirp4netns", "private"];
88        if !valid_modes.contains(&self.network.mode.as_str()) {
89            errors.push(format!(
90                "network.mode: '{}' is invalid (expected one of: {})",
91                self.network.mode,
92                valid_modes.join(", ")
93            ));
94        }
95
96        for (i, port) in self.network.ports.iter().enumerate() {
97            if !port.contains(':') {
98                errors.push(format!(
99                    "network.ports[{i}]: '{port}' is invalid (expected 'hostPort:containerPort' or 'ip:hostPort:containerPort')"
100                ));
101            }
102        }
103
104        if let Some(ref map) = self.integration.host_exec.allowlist {
105            for (alias, path) in map {
106                if !is_absolute_path(path) {
107                    errors.push(format!(
108                        "integration.host_exec.allowlist.{alias}: path '{path}' is not absolute (must start with '/')"
109                    ));
110                }
111            }
112        }
113
114        if self.integration.host_exec.enabled {
115            let has_allowlist = self
116                .integration
117                .host_exec
118                .allowlist
119                .as_ref()
120                .is_some_and(|m| !m.is_empty());
121            if !has_allowlist {
122                errors.push(
123                    "integration.host_exec: 'enabled' is true, but 'allowlist' is missing or empty. \
124                     For security, legacy open execution is blocked; you must explicitly define \
125                     allowed host commands."
126                        .into(),
127                );
128            }
129        }
130
131        for svc in &self.dbus.talk {
132            if is_portal_family(svc) {
133                eprintln!(
134                    "warning: dbus.talk entry '{svc}' grants the container access to the full \
135                     xdg-desktop-portal bus surface (DynamicLauncher, Screenshot, ScreenCast, \
136                     Settings, ...). Prefer relying on the built-in interface-scoped portal rules \
137                     from integration.notify / integration.xdg_open instead."
138                );
139            }
140        }
141
142        let t = &self.lifecycle.idle_timeout;
143        if t != "off" {
144            let (digits, suffix) = parse_duration_suffix(t);
145            if digits.is_empty() || !matches!(suffix, Some('s' | 'm' | 'h')) {
146                errors.push(format!(
147                    "lifecycle.idle_timeout: '{t}' is invalid (expected 'off', '30s', '5m', '1h')"
148                ));
149            }
150        }
151
152        if errors.is_empty() {
153            Ok(())
154        } else {
155            Err(PodboxError::ConfigValidationFailed {
156                details: errors.join("\n  - "),
157            }
158            .into())
159        }
160    }
161}
162
163fn is_valid_name(s: &str) -> bool {
164    !s.is_empty()
165        && s.chars()
166            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.')
167}
168
169fn is_absolute_path(s: &str) -> bool {
170    s.starts_with('/')
171}
172
173/// True when `svc` names the xdg-desktop-portal bus surface (the Desktop
174/// service itself or anything under its name prefix).
175fn is_portal_family(svc: &str) -> bool {
176    svc == "org.freedesktop.portal.Desktop"
177        || svc.starts_with("org.freedesktop.portal")
178        || svc.starts_with("org.freedesktop.impl.portal")
179}
180
181/// Parse a duration string into (digit_part, suffix_char).
182fn parse_duration_suffix(s: &str) -> (String, Option<char>) {
183    let trimmed = s.trim();
184    let digits: String = trimmed.chars().take_while(|c| c.is_ascii_digit()).collect();
185    let suffix = trimmed.chars().nth(digits.len());
186    (digits, suffix)
187}
188
189/// Convert an idle_timeout config string to seconds.
190/// Returns 0 for "off".
191pub fn parse_idle_timeout_secs(s: &str) -> u64 {
192    if s == "off" {
193        return 0;
194    }
195    let (digits, suffix) = parse_duration_suffix(s);
196    let value: u64 = digits.parse().unwrap_or(0);
197    match suffix {
198        Some('s') => value,
199        Some('m') => value.saturating_mul(60),
200        Some('h') => value.saturating_mul(3600),
201        _ => 0,
202    }
203}
204
205fn is_valid_memory(s: &str) -> bool {
206    let s = s.trim();
207    if s.is_empty() {
208        return false;
209    }
210    let digits: String = s.chars().take_while(|c| c.is_ascii_digit()).collect();
211    let suffix: String = s.chars().skip(digits.len()).collect();
212    if digits.is_empty() {
213        return false;
214    }
215    suffix.is_empty()
216        || matches!(
217            suffix.as_str(),
218            "k" | "K" | "m" | "M" | "g" | "G" | "t" | "T"
219        )
220}