mxc-sdk 1.2.0

Importable library for starting MXC sandboxes in-process, with streaming stdio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Filesystem-policy **most-specific-path-wins** mount ordering.
//!
//! The Linux containment backends (Bubblewrap, LXC) realise the filesystem
//! policy as an ordered list of mounts, and the kernel applies "the last mount
//! at a path wins". Overlap between a `readwritePaths` / `readonlyPaths` /
//! `deniedPaths` entry and one of its ancestors or descendants is therefore
//! resolved by **emission order**, not by path specificity.
//!
//! This module normalizes policy paths by component, collapses exact-path
//! conflicts with **most-restrictive-wins** (`denied` > `readonly` >
//! `readwrite`), and returns a **shallow-to-deep** plan so that a backend which
//! emits the plan in order has the deepest (most specific) intent win at every
//! path, regardless of which list it came from.

use crate::mxc_common::models::ContainerPolicy;

/// Reject parent components before a Linux backend orders or mounts policy paths.
pub(crate) fn validate_mount_paths(policy: &ContainerPolicy) -> Result<(), String> {
    for (paths, field) in [
        (&policy.readwrite_paths, "readwritePaths"),
        (&policy.readonly_paths, "readonlyPaths"),
        (&policy.denied_paths, "deniedPaths"),
    ] {
        for path in paths {
            // Lexically collapsing ".." can disagree with host symlink resolution.
            if path.split('/').any(|component| component == "..") {
                return Err(format!(
                    "Filesystem path '{}' (filesystem.{field}) contains a '..' segment; \
                     specify a fully resolved path without '..'.",
                    crate::mxc_common::config_deserialize::escape_diagnostic_text(path)
                ));
            }
        }
    }
    Ok(())
}

/// The access intent a resolved mount carries into the backend, mapped from the
/// policy list the path came from. Ordered least- to most-restrictive so an
/// exact same-path tie resolves most-restrictive-wins.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum FsIntent {
    /// From `readwritePaths` — read+write bind.
    ReadWrite,
    /// From `readonlyPaths` — read-only bind.
    ReadOnly,
    /// From `deniedPaths` — masked (invisible) inside the sandbox.
    Denied,
}

/// A single policy path paired with its intent, ready for a backend to emit as
/// a mount. Ordered relative to its peers by [`resolve_path_plan`].
#[derive(Clone, PartialEq, Eq, Debug)]
pub struct ResolvedMount {
    /// The host path exactly as it appears in the policy (not normalized — the
    /// backend still owns path-to-mount translation).
    pub path: String,
    /// The intent this path was declared with.
    pub intent: FsIntent,
}

/// Unix path components, excluding empty and current-directory segments.
/// These mounts target Unix backends even when tests run on Windows;
/// backslashes remain part of filenames.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
struct PathKey(Vec<String>);

impl PathKey {
    fn from_path(path: &str) -> Self {
        Self(
            path.split('/')
                .filter(|component| !component.is_empty() && *component != ".")
                .map(str::to_string)
                .collect(),
        )
    }

    fn depth(&self) -> usize {
        self.0.len()
    }

    /// Test-only: whether `self` is an ancestor of (or equal to) `other`. Only
    /// the semantic-check oracle in the tests uses this, so it is gated to test
    /// builds to keep the production surface free of dead code.
    #[cfg(test)]
    fn is_prefix_of(&self, other: &Self) -> bool {
        self.0.len() <= other.0.len() && self.0.iter().zip(other.0.iter()).all(|(a, b)| a == b)
    }
}

#[derive(Clone, Debug)]
struct Candidate {
    path: String,
    key: PathKey,
    intent: FsIntent,
    sequence: usize,
}

/// Resolve the three policy lists into a single shallow-to-deep ordered plan.
///
/// Exact same-path conflicts are resolved *upstream* — the config parser's
/// string-level `normalize_filesystem_paths` and each runner's object-identity
/// `filesystem_object::normalize_object_conflicts` — so this function only
/// **orders**. It emits shallow-to-deep and, for any same-path entries that still
/// arrive, places the most-restrictive intent last, so a backend applying "the
/// last mount at a path wins" resolves the tie most-restrictive-wins.
pub fn resolve_path_plan(
    readwrite_paths: &[String],
    readonly_paths: &[String],
    denied_paths: &[String],
) -> Vec<ResolvedMount> {
    let mut candidates =
        Vec::with_capacity(readwrite_paths.len() + readonly_paths.len() + denied_paths.len());
    let mut sequence = 0;
    for (paths, intent) in [
        (readwrite_paths, FsIntent::ReadWrite),
        (readonly_paths, FsIntent::ReadOnly),
        (denied_paths, FsIntent::Denied),
    ] {
        for path in paths {
            candidates.push(Candidate {
                path: path.clone(),
                key: PathKey::from_path(path),
                intent,
                sequence,
            });
            sequence += 1;
        }
    }

    // Order shallow-to-deep so a backend that emits the plan in order lets the
    // deepest (most specific) intent win at every path. Equal-depth ties keep
    // their original category order (read-write, then read-only, then denied),
    // so an exact same-path duplicate that survives upstream normalization is
    // still resolved most-restrictive-wins by emission order: denied is added
    // last, sorts last among equal-depth peers, and a backend applying "the last
    // mount at a path wins" therefore lands on it.
    //
    // This resolver deliberately does *not* re-collapse exact same-path
    // conflicts — that is already done upstream and duplicating it here adds no
    // correctness: the config parser's `normalize_filesystem_paths` drops a
    // string-equal path from a looser list, and each runner's
    // `filesystem_object::normalize_object_conflicts` tightens same-object
    // aliases to the strictest intent before this runs.
    candidates.sort_by(|a, b| {
        a.key
            .depth()
            .cmp(&b.key.depth())
            .then_with(|| a.sequence.cmp(&b.sequence))
    });

    candidates
        .into_iter()
        .map(|candidate| ResolvedMount {
            path: candidate.path,
            intent: candidate.intent,
        })
        .collect()
}

/// Convenience wrapper over [`resolve_path_plan`] for a whole [`ContainerPolicy`].
pub fn resolve_mount_order(policy: &ContainerPolicy) -> Vec<ResolvedMount> {
    resolve_path_plan(
        &policy.readwrite_paths,
        &policy.readonly_paths,
        &policy.denied_paths,
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    fn strings(paths: &[&str]) -> Vec<String> {
        paths.iter().map(|path| (*path).to_string()).collect()
    }

    fn plan(rw: &[&str], ro: &[&str], denied: &[&str]) -> Vec<ResolvedMount> {
        resolve_path_plan(&strings(rw), &strings(ro), &strings(denied))
    }

    fn order(mounts: &[ResolvedMount]) -> Vec<(&str, FsIntent)> {
        mounts
            .iter()
            .map(|mount| (mount.path.as_str(), mount.intent))
            .collect()
    }

    #[test]
    fn mount_validation_accepts_linux_names_without_parent_components() {
        let policy = ContainerPolicy {
            readwrite_paths: strings(&["/work", "/work/report..txt", "/work/..\\file"]),
            readonly_paths: strings(&["/tools/./bin", "/tools//lib/", "/tools\\..\\bin"]),
            denied_paths: strings(&["/work/secret"]),
            ..Default::default()
        };
        assert_eq!(validate_mount_paths(&policy), Ok(()));
    }

    #[test]
    fn mount_validation_rejects_parent_components_and_escapes_diagnostics() {
        for path in [
            "..",
            "../work",
            "/work/../",
            "/work/a/../b/../",
            "/work\n/..",
        ] {
            let policy = ContainerPolicy {
                readwrite_paths: strings(&[path]),
                ..Default::default()
            };
            let error = validate_mount_paths(&policy).expect_err("parent component");
            assert!(error.contains("filesystem.readwritePaths"), "{error}");
            assert!(error.contains("'..'"), "{error}");
            assert!(!error.contains('\n'), "{error}");
        }
    }

    /// Test oracle: the effective intent a resolved `plan` assigns to `path` —
    /// the intent of the deepest plan entry that is an ancestor of (or equal to)
    /// `path`, with most-restrictive-wins breaking an exact-depth tie. `None` if
    /// no entry covers the path. This models what a backend's "last mount at a
    /// path wins" ultimately resolves to, so tests can assert semantics instead
    /// of raw emission order.
    fn effective_intent(plan: &[ResolvedMount], path: &str) -> Option<FsIntent> {
        let query = PathKey::from_path(path);
        plan.iter()
            .filter_map(|mount| {
                let key = PathKey::from_path(&mount.path);
                key.is_prefix_of(&query)
                    .then_some((key.depth(), mount.intent))
            })
            .max_by(|(left_depth, left_intent), (right_depth, right_intent)| {
                left_depth
                    .cmp(right_depth)
                    .then_with(|| left_intent.cmp(right_intent))
            })
            .map(|(_, intent)| intent)
    }

    #[test]
    fn nested_paths_are_ordered_shallow_to_deep() {
        let resolved = plan(&["/workspace"], &["/workspace/.git"], &["/workspace/.env"]);
        assert_eq!(
            order(&resolved),
            vec![
                ("/workspace", FsIntent::ReadWrite),
                ("/workspace/.git", FsIntent::ReadOnly),
                ("/workspace/.env", FsIntent::Denied),
            ]
        );
        assert_eq!(
            effective_intent(&resolved, "/workspace/src/main.rs"),
            Some(FsIntent::ReadWrite)
        );
        assert_eq!(
            effective_intent(&resolved, "/workspace/.git/config"),
            Some(FsIntent::ReadOnly)
        );
        assert_eq!(
            effective_intent(&resolved, "/workspace/.env"),
            Some(FsIntent::Denied)
        );
    }

    #[test]
    fn exact_path_duplicates_emit_most_restrictive_last() {
        // Exact same-path conflicts are collapsed upstream (config-parser string
        // normalization + object-identity normalization), so the resolver no
        // longer re-collapses them. When identical paths do reach it, it orders
        // them so the most-restrictive intent is emitted LAST — a backend
        // applying "the last mount at a path wins" therefore lands on denied,
        // and the semantic oracle agrees.
        let resolved = plan(&["/workspace"], &["/workspace"], &["/workspace"]);
        assert_eq!(
            resolved
                .last()
                .map(|mount| (mount.path.as_str(), mount.intent)),
            Some(("/workspace", FsIntent::Denied))
        );
        assert_eq!(
            effective_intent(&resolved, "/workspace/file"),
            Some(FsIntent::Denied)
        );
    }

    #[test]
    fn readonly_emitted_after_readwrite_for_same_path() {
        // Same path in read-write and read-only: read-only is emitted last so it
        // wins by emission order, and the oracle resolves to read-only.
        let resolved = plan(&["/workspace/"], &["/workspace"], &[]);
        assert_eq!(
            resolved.last().map(|mount| mount.intent),
            Some(FsIntent::ReadOnly)
        );
        assert_eq!(
            effective_intent(&resolved, "/workspace/file"),
            Some(FsIntent::ReadOnly)
        );
    }

    #[test]
    fn trailing_slash_variants_resolve_most_restrictive_by_order() {
        // "/data" (read-write) and "/data/" (denied) are the same logical path
        // but differ by a trailing slash, so the upstream string-level
        // normalization does not merge them. The resolver does not collapse them
        // either (that would duplicate the upstream / object-identity
        // normalization); instead it emits denied last, so emission order yields
        // most-restrictive-wins and the semantic oracle agrees.
        let resolved = plan(&["/data"], &[], &["/data/"]);
        assert_eq!(
            resolved.last().map(|mount| mount.intent),
            Some(FsIntent::Denied)
        );
        assert_eq!(
            effective_intent(&resolved, "/data/file"),
            Some(FsIntent::Denied)
        );

        // Swap the trailing slash onto the read-write spelling: denied still
        // sorts last and wins.
        let resolved = plan(&["/data/"], &[], &["/data"]);
        assert_eq!(
            resolved.last().map(|mount| mount.intent),
            Some(FsIntent::Denied)
        );
    }

    #[test]
    fn siblings_do_not_override_each_other() {
        let resolved = plan(&["/workspace/src"], &["/workspace/docs"], &[]);
        assert_eq!(
            effective_intent(&resolved, "/workspace/src/lib.rs"),
            Some(FsIntent::ReadWrite)
        );
        assert_eq!(
            effective_intent(&resolved, "/workspace/docs/index.md"),
            Some(FsIntent::ReadOnly)
        );
        assert_eq!(
            effective_intent(&resolved, "/workspace/tests/test.rs"),
            None
        );
    }

    #[test]
    fn unrelated_paths_remain_independent() {
        let resolved = plan(&["/srv/app/data"], &["/usr"], &["/opt/secret"]);
        assert_eq!(
            order(&resolved),
            vec![
                ("/usr", FsIntent::ReadOnly),
                ("/opt/secret", FsIntent::Denied),
                ("/srv/app/data", FsIntent::ReadWrite),
            ]
        );
        assert_eq!(effective_intent(&resolved, "/var/log/app.log"), None);
    }

    #[test]
    fn deep_override_of_shallow_deny_wins_for_child_only() {
        let resolved = plan(&["/data/secrets"], &[], &["/data"]);
        assert_eq!(
            order(&resolved),
            vec![
                ("/data", FsIntent::Denied),
                ("/data/secrets", FsIntent::ReadWrite),
            ]
        );
        assert_eq!(effective_intent(&resolved, "/data"), Some(FsIntent::Denied));
        assert_eq!(
            effective_intent(&resolved, "/data/secrets/file"),
            Some(FsIntent::ReadWrite)
        );
    }

    #[test]
    fn component_prefix_does_not_match_partial_component() {
        let resolved = plan(&["/workspace"], &[], &[]);
        assert_eq!(effective_intent(&resolved, "/workspace2/file"), None);
    }

    #[test]
    fn current_directory_components_preserve_nested_policy_order() {
        let parent = "/work/././";
        for (rw, ro, intent) in [
            (vec![parent], vec![], FsIntent::ReadWrite),
            (vec![], vec![parent], FsIntent::ReadOnly),
        ] {
            let resolved = plan(&rw, &ro, &["/work/secret"]);
            assert_eq!(
                order(&resolved),
                vec![(parent, intent), ("/work/secret", FsIntent::Denied)]
            );
        }

        let resolved = plan(&["/work/./public"], &[], &[parent]);
        assert_eq!(
            order(&resolved),
            vec![
                (parent, FsIntent::Denied),
                ("/work/./public", FsIntent::ReadWrite),
            ]
        );
    }

    #[test]
    fn current_directory_aliases_keep_most_restrictive_last() {
        let resolved = plan(&["/work/././"], &["/work"], &["/work/."]);
        assert_eq!(
            order(&resolved),
            vec![
                ("/work/././", FsIntent::ReadWrite),
                ("/work", FsIntent::ReadOnly),
                ("/work/.", FsIntent::Denied),
            ]
        );
    }

    #[test]
    fn backslashes_and_dotted_names_are_literal_unix_components() {
        let resolved = plan(
            &[r"/work/team\notes\archive"],
            &["/work/.config"],
            &["/work/team/secret"],
        );
        assert_eq!(
            order(&resolved),
            vec![
                (r"/work/team\notes\archive", FsIntent::ReadWrite),
                ("/work/.config", FsIntent::ReadOnly),
                ("/work/team/secret", FsIntent::Denied),
            ]
        );
        assert_eq!(
            effective_intent(&resolved, "/work/team/notes/archive/file"),
            None
        );
        assert_eq!(
            effective_intent(&resolved, r"/work/team\notes\archive/file"),
            Some(FsIntent::ReadWrite)
        );

        for child in ["/work/.config", "/work/report..txt", r"/work/team\."] {
            assert_eq!(
                order(&plan(&[child], &[], &["/work"])),
                vec![("/work", FsIntent::Denied), (child, FsIntent::ReadWrite)]
            );
        }
    }

    #[test]
    fn empty_policy_yields_no_mounts() {
        assert!(plan(&[], &[], &[]).is_empty());
    }
}