substrate_kit/mount.rs
1//! `mount` — Mount / volume attach primitives.
2//!
3//! **This slice's concrete target:** resolving the real mount-namespace
4//! handle of an already-running process on the host, by pid — filling
5//! `principal::ContainerRef::mount_ns`, which is unconditionally `None`
6//! until something actually resolves it. `lifecycle::Lifecycle::container_ref`
7//! is the caller that wires this in for a real dockerd container.
8//!
9//! **Scope boundary (hard constraint, same as every substrate-kit
10//! module):** this resolves *what a container's mount namespace is*,
11//! never *who* should be allowed to bind-mount into it or *why* — that's
12//! an authorization/policy question for identity-kit, not this
13//! crate. See `principal.rs`'s module doc for the full hard-constraint
14//! statement.
15//!
16//! **Real, environment-dependent permission boundary — not a bug:**
17//! reading another user's `/proc/<pid>/ns/*` requires the same real/
18//! effective/saved uid as the target process, or `CAP_SYS_PTRACE`. A
19//! dockerd container's process typically runs as `root` on the host; a
20//! non-root caller resolving its mount namespace gets a real
21//! permission-denied `SubstrateError::Io` here, and that is the *correct*
22//! answer for this function to give, not a defect. `lifecycle`'s live
23//! tests document exactly what they can and can't prove on a non-root
24//! test run — see that module's `mod live` doc.
25//!
26//! ## Volume attach: [`VolumeMount`]
27//!
28//! The second half of this module is the *declarative* volume seam a
29//! [`crate::lifecycle::ContainerSpec`] carries: [`VolumeMount`] describes a
30//! **named Docker volume** to attach to a container, optionally backed by a
31//! volume-plugin driver (for example a content-addressed storage
32//! driver). dockerd creates the volume on first reference
33//! (`docker run --mount type=volume,...` semantics).
34//!
35//! **Deliberately no host bind mounts.** An arbitrary host path is a
36//! different trust decision from a named volume (it can expose any part of
37//! the host filesystem to a container), so a host path must never be derived
38//! from untrusted input. Bind mounts, tmpfs and anything that names a
39//! host path are therefore not representable here; they would arrive as a
40//! separate, explicitly-reviewed type, not as a string convention on this
41//! one.
42//!
43//! **Enforced, not just documented.** [`VolumeMount::validate`] rejects the
44//! `local` driver (case-insensitive) and the driver option keys `device`,
45//! `o` and `type` (case-insensitive), because the `local` driver turns
46//! `type=none,o=bind,device=/host/path` into a host bind mount of any path.
47//! A third-party plugin driver is trusted to be a plugin; this crate cannot
48//! inspect what a plugin does with its options.
49//!
50//! Driver options (`with_driver`) are stored in dockerd's volume metadata
51//! and are visible to anyone who can `docker volume inspect`: **never put a
52//! credential in them**.
53//!
54//! Full mount/volume *attach* primitives beyond that (bind-mounting into a
55//! running container's namespace, rather than reading its handle back)
56//! remain deferred; no epic exists for them.
57
58use std::collections::HashMap;
59
60use bollard::models::{Mount, MountTypeEnum, MountVolumeOptions, MountVolumeOptionsDriverConfig};
61
62use crate::error::SubstrateError;
63
64/// A named Docker volume to attach to a container at `target`.
65///
66/// Built with [`VolumeMount::named`] and the `with_*` builders; validated by
67/// [`VolumeMount::validate`] (called for you by
68/// [`crate::lifecycle::Lifecycle::run`]).
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct VolumeMount {
71 /// Docker volume name (not a path). Created by dockerd on first use.
72 pub name: String,
73 /// Absolute path inside the container.
74 pub target: String,
75 /// Mount read-only inside the container.
76 pub read_only: bool,
77 /// Optional volume-plugin driver (`name`, driver options). `None` uses
78 /// dockerd's default `local` driver, or whatever driver an
79 /// already-existing volume of this name was created with.
80 pub driver: Option<VolumeDriver>,
81}
82
83/// Driver option keys that name a host path or a mount type (the `local`
84/// driver's `device` / `o` / `type`). Compared lowercase.
85const FORBIDDEN_DRIVER_OPTION_KEYS: [&str; 3] = ["device", "o", "type"];
86
87/// A volume-plugin driver selection for a [`VolumeMount`].
88#[derive(Debug, Clone, PartialEq, Eq)]
89pub struct VolumeDriver {
90 pub name: String,
91 pub options: HashMap<String, String>,
92}
93
94impl VolumeMount {
95 /// A read-write named volume at `target`, default driver.
96 pub fn named(name: impl Into<String>, target: impl Into<String>) -> Self {
97 Self {
98 name: name.into(),
99 target: target.into(),
100 read_only: false,
101 driver: None,
102 }
103 }
104
105 pub fn read_only(mut self) -> Self {
106 self.read_only = true;
107 self
108 }
109
110 /// Back the volume with a volume-plugin driver (for example
111 /// `my-driver`). Options must not contain credentials; see the module doc.
112 pub fn with_driver(
113 mut self,
114 driver: impl Into<String>,
115 options: HashMap<String, String>,
116 ) -> Self {
117 self.driver = Some(VolumeDriver {
118 name: driver.into(),
119 options,
120 });
121 self
122 }
123
124 /// Reject mounts dockerd would refuse, or that would silently mean
125 /// something other than a named volume, before any Docker call is made.
126 pub fn validate(&self) -> Result<(), SubstrateError> {
127 if !is_valid_volume_name(&self.name) {
128 return Err(SubstrateError::InvalidSpec(format!(
129 "volume name {:?} is not a valid Docker volume name \
130 (must start with a letter or digit and contain only [a-zA-Z0-9_.-]; \
131 host paths are not accepted)",
132 self.name
133 )));
134 }
135 if !self.target.starts_with('/') {
136 return Err(SubstrateError::InvalidSpec(format!(
137 "volume {:?} target {:?} must be an absolute container path",
138 self.name, self.target
139 )));
140 }
141 if let Some(driver) = &self.driver {
142 if driver.name.is_empty() {
143 return Err(SubstrateError::InvalidSpec(format!(
144 "volume {:?} has an empty driver name",
145 self.name
146 )));
147 }
148 // The `local` driver accepts `type=none,o=bind,device=/host/path`,
149 // which is a host bind mount spelled as a named volume. Reject it
150 // (and the option keys that express it) so "no host bind mounts"
151 // holds for every input this type accepts. Case-insensitive and
152 // whitespace-trimmed so `Local` / ` Device` cannot slip past.
153 if driver.name.trim().eq_ignore_ascii_case("local") {
154 return Err(SubstrateError::InvalidSpec(format!(
155 "volume {:?}: driver `local` is not accepted (it can bind-mount a host \
156 path via driver options); omit the driver to use the default",
157 self.name
158 )));
159 }
160 if let Some(key) = driver.options.keys().find(|k| {
161 FORBIDDEN_DRIVER_OPTION_KEYS.contains(&k.trim().to_ascii_lowercase().as_str())
162 }) {
163 return Err(SubstrateError::InvalidSpec(format!(
164 "volume {:?}: driver option {:?} is not accepted (it can name a host \
165 path or mount type)",
166 self.name, key
167 )));
168 }
169 }
170 Ok(())
171 }
172
173 pub(crate) fn to_docker(&self) -> Mount {
174 let volume_options = self.driver.as_ref().map(|d| MountVolumeOptions {
175 driver_config: Some(MountVolumeOptionsDriverConfig {
176 name: Some(d.name.clone()),
177 options: Some(d.options.clone()),
178 }),
179 ..Default::default()
180 });
181 Mount {
182 target: Some(self.target.clone()),
183 source: Some(self.name.clone()),
184 typ: Some(MountTypeEnum::VOLUME),
185 read_only: Some(self.read_only),
186 volume_options,
187 ..Default::default()
188 }
189 }
190}
191
192/// Docker's own volume-name rule: `[a-zA-Z0-9][a-zA-Z0-9_.-]*`.
193fn is_valid_volume_name(name: &str) -> bool {
194 let mut chars = name.chars();
195 match chars.next() {
196 Some(c) if c.is_ascii_alphanumeric() => {}
197 _ => return false,
198 }
199 chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '.' | '-'))
200}
201
202/// Resolve the mount-namespace handle for a running process on the host,
203/// by pid — the `/proc/<pid>/ns/mnt` symlink target (`mnt:[<inode>]`),
204/// exactly the opaque handle format `ContainerRef::mount_ns`'s own doc
205/// example (`/proc/4242/ns/mnt`) points at.
206///
207/// See this module's doc for the real permission boundary this hits
208/// against a root-owned container process when called by a non-root
209/// caller — that failure is surfaced as `SubstrateError::Io`, not masked.
210pub fn resolve_mount_namespace(pid: u32) -> Result<String, SubstrateError> {
211 let link = std::fs::read_link(format!("/proc/{pid}/ns/mnt"))?;
212 link.into_os_string().into_string().map_err(|_| {
213 SubstrateError::Resolve(format!("non-utf8 mount namespace handle for pid {pid}"))
214 })
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 #[test]
222 fn named_volume_maps_to_a_docker_volume_mount() {
223 let m = VolumeMount::named("jellyfin-config", "/config")
224 .read_only()
225 .to_docker();
226 assert_eq!(m.typ, Some(MountTypeEnum::VOLUME));
227 assert_eq!(m.source.as_deref(), Some("jellyfin-config"));
228 assert_eq!(m.target.as_deref(), Some("/config"));
229 assert_eq!(m.read_only, Some(true));
230 assert!(m.volume_options.is_none());
231 assert!(m.bind_options.is_none());
232 }
233
234 #[test]
235 fn driver_selection_maps_to_volume_options_driver_config() {
236 let mut opts = HashMap::new();
237 opts.insert("pool".to_string(), "pool-a".to_string());
238 let m = VolumeMount::named("state", "/state")
239 .with_driver("example-driver", opts.clone())
240 .to_docker();
241 let cfg = m.volume_options.unwrap().driver_config.unwrap();
242 assert_eq!(cfg.name.as_deref(), Some("example-driver"));
243 assert_eq!(cfg.options, Some(opts));
244 }
245
246 #[test]
247 fn validate_accepts_a_plain_named_volume() {
248 VolumeMount::named("data_1.x-y", "/data")
249 .validate()
250 .unwrap();
251 }
252
253 #[test]
254 fn validate_rejects_host_paths_and_bad_names() {
255 for bad in ["", "/etc", "./rel", "../up", "-lead", "has space", "a/b"] {
256 let err = VolumeMount::named(bad, "/data").validate().expect_err(bad);
257 assert!(matches!(err, SubstrateError::InvalidSpec(_)), "{bad}");
258 }
259 }
260
261 #[test]
262 fn validate_rejects_a_relative_target() {
263 let err = VolumeMount::named("data", "data").validate().unwrap_err();
264 assert!(matches!(err, SubstrateError::InvalidSpec(_)));
265 }
266
267 #[test]
268 fn validate_rejects_an_empty_driver_name() {
269 let err = VolumeMount::named("data", "/data")
270 .with_driver("", HashMap::new())
271 .validate()
272 .unwrap_err();
273 assert!(matches!(err, SubstrateError::InvalidSpec(_)));
274 }
275
276 fn bind_options(pairs: &[(&str, &str)]) -> HashMap<String, String> {
277 pairs
278 .iter()
279 .map(|(k, v)| (k.to_string(), v.to_string()))
280 .collect()
281 }
282
283 #[test]
284 fn validate_rejects_a_local_driver_bind_of_a_host_path() {
285 // The bypass: a `local` volume with type=none,o=bind,device=/etc is a
286 // host bind mount. This passed validate() before the fix.
287 let err = VolumeMount::named("data", "/data")
288 .with_driver(
289 "local",
290 bind_options(&[("type", "none"), ("o", "bind"), ("device", "/etc")]),
291 )
292 .validate()
293 .unwrap_err();
294 assert!(matches!(err, SubstrateError::InvalidSpec(_)));
295 }
296
297 #[test]
298 fn validate_rejects_the_local_driver_in_any_spelling() {
299 for name in ["local", "Local", "LOCAL", " local ", "local\t"] {
300 let err = VolumeMount::named("data", "/data")
301 .with_driver(name, HashMap::new())
302 .validate()
303 .expect_err(name);
304 assert!(matches!(err, SubstrateError::InvalidSpec(_)), "{name:?}");
305 }
306 }
307
308 #[test]
309 fn validate_rejects_host_path_option_keys_on_any_driver() {
310 for key in [
311 "device", "Device", "DEVICE", "o", "O", "type", "Type", " type ",
312 ] {
313 let err = VolumeMount::named("data", "/data")
314 .with_driver("example-driver", bind_options(&[(key, "x")]))
315 .validate()
316 .expect_err(key);
317 assert!(matches!(err, SubstrateError::InvalidSpec(_)), "{key:?}");
318 }
319 }
320
321 #[test]
322 fn validate_still_accepts_a_plugin_driver_with_ordinary_options() {
323 VolumeMount::named("state", "/state")
324 .with_driver("example-driver", bind_options(&[("pool", "pool-a")]))
325 .validate()
326 .unwrap();
327 }
328
329 #[test]
330 #[cfg(target_os = "linux")]
331 fn resolve_mount_namespace_resolves_this_process_own_handle_for_real() {
332 // A real `/proc` read against this test process itself, which it
333 // always has permission to read regardless of privilege — the
334 // permission-gated, root-owned-container case is exercised (and
335 // its exact failure mode documented) by `lifecycle`'s live tests.
336 let pid = std::process::id();
337 let handle = resolve_mount_namespace(pid).expect("resolve own mount namespace");
338 assert!(
339 handle.starts_with("mnt:["),
340 "expected an `mnt:[...]` handle, got: {handle}"
341 );
342 }
343
344 #[test]
345 fn resolve_mount_namespace_fails_cleanly_for_a_nonexistent_pid() {
346 let bogus_pid = u32::MAX;
347 let err = resolve_mount_namespace(bogus_pid).expect_err("nonexistent pid must fail");
348 assert!(matches!(err, SubstrateError::Io(_)));
349 }
350}