cageforge-policy 0.7.0

Filesystem and network policies for Rust process sandboxes
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
// SPDX-License-Identifier: Apache-2.0

//! Filesystem ownership, rules, selectors, and access evaluation.
//!
//! [`crate::FilesystemPolicy`] combines [`crate::FilesystemRule`] values and
//! returns [`crate::FilesystemDecision`] for selectors or concrete paths. The
//! lexical result must still be paired with native filesystem enforcement by
//! the backend.

use crate::AccessMode;
use crate::FilesystemDecision;
use crate::PathPattern;
use crate::PathResolutionContext;
use crate::PathSelector;
use crate::PolicyError;
use crate::path::normal_component_count;
use cageforge_path::{contains_component_path, contains_parent_traversal, is_within, paths_equal};
use std::collections::HashMap;
use std::num::NonZeroUsize;
use std::path::{Component, Path, PathBuf};

/// Filesystem restrictions passed to a platform backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilesystemPolicy {
    mode: FilesystemMode,
    entries: Vec<FilesystemRule>,
    glob_scan_max_depth: Option<NonZeroUsize>,
    protected_relative_paths: Vec<PathBuf>,
}

/// The enforcement ownership for filesystem access.
///
/// The modes are ownership states, not a permission scale, so this type does
/// not implement [`Ord`]. Composition uses explicit ownership checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FilesystemMode {
    /// Cageforge must enforce the listed restrictions through its backend.
    Restricted,
    /// The command runs without a Cageforge filesystem boundary.
    Unrestricted,
    /// Another trusted sandbox is responsible for enforcement.
    External,
}

/// What a filesystem rule targets.
///
/// Target equality and hashing remain available for canonical deduplication;
/// variant declaration order is not exposed as a policy precedence.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum FilesystemTarget {
    /// A concrete or runtime-defined filesystem scope.
    Scope(PathSelector),
    /// A validated absolute or workspace-relative path glob.
    Glob(PathPattern),
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum FilesystemTargetKey {
    Scope(PathSelector),
    Glob {
        absolute: bool,
        prefix: Option<String>,
        components: Vec<String>,
    },
}

/// What a backend should do when a concrete rule target is absent.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MissingPathBehavior {
    /// Treat an absent target as an error during backend preparation.
    Error,
    /// Ignore an absent target without creating it.
    Skip,
}

/// One filesystem target and its access mode.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FilesystemRule {
    target: FilesystemTarget,
    access: AccessMode,
    missing_path_behavior: MissingPathBehavior,
    read_only_subpaths: Vec<PathSelector>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct RuleMatch {
    specificity: usize,
    access: AccessMode,
}

impl MissingPathBehavior {
    /// Returns the safer result when two rules disagree about a missing path.
    ///
    /// This is intentionally an explicit operation instead of an `Ord`
    /// implementation: `Error` is more conservative than `Skip`, but that
    /// relationship is specific to this merge operation and is not a general
    /// ordering for filesystem policy values.
    pub const fn most_conservative(self, other: Self) -> Self {
        match (self, other) {
            (Self::Error, _) | (_, Self::Error) => Self::Error,
            (Self::Skip, Self::Skip) => Self::Skip,
        }
    }
}

impl FilesystemRule {
    /// Creates a rule from an already validated path selector.
    pub const fn new(selector: PathSelector, access: AccessMode) -> Self {
        Self {
            target: FilesystemTarget::Scope(selector),
            access,
            missing_path_behavior: MissingPathBehavior::Error,
            read_only_subpaths: Vec::new(),
        }
    }

    /// Creates a rule from a validated target.
    pub fn from_target(target: FilesystemTarget, access: AccessMode) -> Result<Self, PolicyError> {
        if matches!(target, FilesystemTarget::Glob(_)) && access != AccessMode::Deny {
            return Err(PolicyError::UnsupportedGlobAccess { access });
        }
        Ok(Self {
            target,
            access,
            missing_path_behavior: MissingPathBehavior::Error,
            read_only_subpaths: Vec::new(),
        })
    }

    /// Creates an absolute-path glob rule.
    pub fn absolute_glob(
        pattern: impl Into<String>,
        access: AccessMode,
    ) -> Result<Self, PolicyError> {
        Self::from_target(
            FilesystemTarget::Glob(PathPattern::absolute(pattern)?),
            access,
        )
    }

    /// Creates a workspace-relative glob rule.
    pub fn workspace_glob(
        pattern: impl Into<String>,
        access: AccessMode,
    ) -> Result<Self, PolicyError> {
        Self::from_target(
            FilesystemTarget::Glob(PathPattern::workspace(pattern)?),
            access,
        )
    }

    /// Sets how the backend handles an absent concrete target.
    pub const fn with_missing_path_behavior(mut self, behavior: MissingPathBehavior) -> Self {
        self.missing_path_behavior = behavior;
        self
    }

    /// Adds a read-only carve-out below a writable rule.
    pub fn with_read_only_subpath(mut self, selector: PathSelector) -> Result<Self, PolicyError> {
        if self.access != AccessMode::Write {
            return Err(PolicyError::InvalidRule {
                message: "read-only subpaths require a writable parent rule".to_string(),
            });
        }
        if let FilesystemTarget::Scope(parent) = &self.target
            && selector.is_definitely_outside(parent)
        {
            return Err(PolicyError::InvalidRule {
                message: "read-only subpath must be below the writable parent rule".to_string(),
            });
        }
        self.read_only_subpaths.push(selector);
        Ok(self)
    }

    /// Returns the rule target.
    pub const fn target(&self) -> &FilesystemTarget {
        &self.target
    }

    /// Returns the access mode of this rule.
    pub const fn access(&self) -> AccessMode {
        self.access
    }

    /// Returns the missing-target behavior.
    pub const fn missing_path_behavior(&self) -> MissingPathBehavior {
        self.missing_path_behavior
    }

    /// Returns read-only carve-outs below this rule.
    pub fn read_only_subpaths(&self) -> &[PathSelector] {
        &self.read_only_subpaths
    }

    fn matches_path(&self, path: &Path, context: &PathResolutionContext) -> Option<RuleMatch> {
        let (specificity, target_matches) = match &self.target {
            FilesystemTarget::Scope(selector) => selector
                .resolve(context)
                .into_iter()
                .filter(|root| is_within(path, root))
                .map(|root| (normal_component_count(&root), true))
                .max_by_key(|(specificity, _)| *specificity)
                .unwrap_or((0, false)),
            FilesystemTarget::Glob(pattern) => {
                (pattern.specificity(), pattern.matches(path, context))
            }
        };
        if !target_matches {
            return None;
        }

        let mut access = self.access;
        let mut specificity = specificity;
        if access == AccessMode::Write {
            for subpath in &self.read_only_subpaths {
                let matches = subpath
                    .resolve(context)
                    .into_iter()
                    .filter(|root| is_within(path, root))
                    .map(|root| normal_component_count(&root))
                    .max();
                if let Some(subpath_specificity) = matches {
                    access = AccessMode::Read;
                    specificity = specificity.max(subpath_specificity);
                }
            }
        }
        Some(RuleMatch {
            specificity,
            access,
        })
    }

    fn validate(&self) -> Result<(), PolicyError> {
        if matches!(self.target, FilesystemTarget::Glob(_)) && self.access != AccessMode::Deny {
            return Err(PolicyError::UnsupportedGlobAccess {
                access: self.access,
            });
        }
        Ok(())
    }
}

impl FilesystemPolicy {
    /// Creates a restricted policy from filesystem rules.
    pub fn restricted(entries: impl IntoIterator<Item = FilesystemRule>) -> Self {
        Self {
            mode: FilesystemMode::Restricted,
            entries: entries.into_iter().collect(),
            glob_scan_max_depth: None,
            protected_relative_paths: vec![PathBuf::from(".git")],
        }
    }

    /// Creates a policy with no Cageforge filesystem restrictions.
    pub const fn unrestricted() -> Self {
        Self {
            mode: FilesystemMode::Unrestricted,
            entries: Vec::new(),
            glob_scan_max_depth: None,
            protected_relative_paths: Vec::new(),
        }
    }

    /// Creates a policy whose filesystem boundary is owned by another sandbox.
    pub const fn external() -> Self {
        Self {
            mode: FilesystemMode::External,
            entries: Vec::new(),
            glob_scan_max_depth: None,
            protected_relative_paths: Vec::new(),
        }
    }

    /// Sets the maximum depth used when a backend expands glob targets.
    pub fn with_glob_scan_max_depth(mut self, depth: NonZeroUsize) -> Result<Self, PolicyError> {
        if self.mode != FilesystemMode::Restricted {
            return Err(PolicyError::InvalidRule {
                message: "glob scan depth requires a restricted filesystem policy".to_string(),
            });
        }
        self.glob_scan_max_depth = Some(depth);
        Ok(self)
    }

    /// Returns the enforcement mode.
    pub const fn mode(&self) -> FilesystemMode {
        self.mode
    }

    /// Returns the configured filesystem rules in declaration order.
    pub fn entries(&self) -> &[FilesystemRule] {
        &self.entries
    }

    /// Returns the optional backend glob expansion depth.
    pub const fn glob_scan_max_depth(&self) -> Option<NonZeroUsize> {
        self.glob_scan_max_depth
    }

    /// Returns protected relative paths applied below writable scopes.
    pub fn protected_relative_paths(&self) -> &[PathBuf] {
        &self.protected_relative_paths
    }

    /// Adds a protected relative path without changing the default `.git`
    /// protection setting.
    pub fn with_additional_protected_relative_path(
        mut self,
        path: impl Into<PathBuf>,
    ) -> Result<Self, PolicyError> {
        if self.mode != FilesystemMode::Restricted {
            return Err(PolicyError::InvalidRule {
                message: "protected paths require a restricted filesystem policy".to_string(),
            });
        }
        let path = validate_protected_relative_path(path.into())?;
        if !self
            .protected_relative_paths
            .iter()
            .any(|existing| paths_equal(existing, &path))
        {
            self.protected_relative_paths.push(path);
        }
        Ok(self)
    }

    /// Explicitly disables the default `.git` write protection.
    ///
    /// This opt-out is intentionally named as a dangerous operation. A
    /// backend or policy composer may still reject the resulting request.
    pub fn dangerously_allow_git_write(mut self) -> Self {
        self.protected_relative_paths
            .retain(|path| !paths_equal(path, Path::new(".git")));
        self
    }

    /// Adds one rule while retaining the existing policy.
    pub fn with_rule(mut self, rule: FilesystemRule) -> Result<Self, PolicyError> {
        if self.mode != FilesystemMode::Restricted {
            return Err(PolicyError::InvalidRule {
                message: "filesystem rules require a restricted filesystem policy".to_string(),
            });
        }
        rule.validate()?;
        self.entries.push(rule);
        Ok(self)
    }

    /// Validates the policy and rejects rules that are meaningless for its mode.
    pub fn validate(&self) -> Result<(), PolicyError> {
        if self.mode != FilesystemMode::Restricted
            && (!self.entries.is_empty()
                || self.glob_scan_max_depth.is_some()
                || !self.protected_relative_paths.is_empty())
        {
            return Err(PolicyError::InvalidRule {
                message:
                    "unrestricted and external filesystem policies cannot contain local settings"
                        .to_string(),
            });
        }
        for rule in &self.entries {
            rule.validate()?;
            if rule.access != AccessMode::Write && !rule.read_only_subpaths.is_empty() {
                return Err(PolicyError::InvalidRule {
                    message: "read-only subpaths require a writable parent rule".to_string(),
                });
            }
        }
        for path in &self.protected_relative_paths {
            validate_protected_relative_path(path.clone())?;
        }
        Ok(())
    }

    /// Returns a normalized policy with duplicate targets collapsed conservatively.
    pub fn normalized(&self) -> Result<Self, PolicyError> {
        self.validate()?;
        if self.mode != FilesystemMode::Restricted {
            return Ok(self.clone());
        }

        let mut entries: Vec<FilesystemRule> = Vec::with_capacity(self.entries.len());
        let mut positions: HashMap<FilesystemTargetKey, usize> =
            HashMap::with_capacity(self.entries.len());
        for rule in &self.entries {
            let key = target_key(rule.target());
            if let Some(&index) = positions.get(&key) {
                let existing = &mut entries[index];
                existing.access = existing.access.most_restrictive(rule.access);
                existing.missing_path_behavior = existing
                    .missing_path_behavior
                    .most_conservative(rule.missing_path_behavior);
                for selector in &rule.read_only_subpaths {
                    if !existing
                        .read_only_subpaths
                        .iter()
                        .any(|existing| crate::path::selectors_equal(existing, selector))
                    {
                        existing.read_only_subpaths.push(selector.clone());
                    }
                }
                if existing.access != AccessMode::Write {
                    existing.read_only_subpaths.clear();
                }
            } else {
                positions.insert(key, entries.len());
                entries.push(rule.clone());
            }
        }
        Ok(Self {
            entries,
            ..self.clone()
        })
    }

    /// Resolves a symbolic selector through a caller-provided runtime
    /// context.
    ///
    /// An unresolvable symbolic selector is denied. This context requirement
    /// prevents a static declaration such as `workspace-root` from being
    /// mistaken for an actual runtime path.
    pub fn access_for(
        &self,
        selector: &PathSelector,
        context: &PathResolutionContext,
    ) -> Result<FilesystemDecision, PolicyError> {
        if self.mode == FilesystemMode::External {
            return Ok(FilesystemDecision::ExternallyEnforced);
        }
        let mut result = None;
        for path in selector.resolve(context) {
            let decision = self.access_for_path(&path, context)?;
            result = Some(match (result, decision) {
                (Some(FilesystemDecision::Deny), _) | (_, FilesystemDecision::Deny) => {
                    FilesystemDecision::Deny
                }
                (Some(FilesystemDecision::Read), _) | (_, FilesystemDecision::Read) => {
                    FilesystemDecision::Read
                }
                (Some(FilesystemDecision::Write), FilesystemDecision::Write) => {
                    FilesystemDecision::Write
                }
                (None, decision) => decision,
                (Some(FilesystemDecision::ExternallyEnforced), decision) => decision,
                (Some(decision), FilesystemDecision::ExternallyEnforced) => decision,
            });
        }
        Ok(result.unwrap_or(FilesystemDecision::Deny))
    }

    /// Resolves access for an absolute path using recursive and most-specific matching.
    ///
    /// This is a lexical policy decision, not native filesystem enforcement.
    /// A backend must additionally protect symlink, junction/reparse-point,
    /// mount, and TOCTOU boundaries before opening or mutating the path.
    pub fn access_for_path(
        &self,
        path: &Path,
        context: &PathResolutionContext,
    ) -> Result<FilesystemDecision, PolicyError> {
        if crate::path::contains_nul(path) {
            return Err(PolicyError::PathContainsNul {
                path: path.to_path_buf(),
            });
        }
        if !path.is_absolute() {
            return Err(PolicyError::ExpectedAbsolute {
                path: path.to_path_buf(),
            });
        }
        if contains_parent_traversal(path) {
            return Err(PolicyError::ParentTraversal {
                path: path.to_path_buf(),
            });
        }
        match self.mode {
            FilesystemMode::Unrestricted => Ok(FilesystemDecision::Write),
            FilesystemMode::External => Ok(FilesystemDecision::ExternallyEnforced),
            FilesystemMode::Restricted => {
                let mut best: Option<RuleMatch> = None;
                let mut writable_match = false;
                for rule in &self.entries {
                    if let Some(candidate) = rule.matches_path(path, context) {
                        if candidate.access == AccessMode::Deny {
                            return Ok(FilesystemDecision::Deny);
                        }
                        writable_match |= candidate.access == AccessMode::Write;
                        best = Some(match best {
                            Some(current) if current.specificity > candidate.specificity => current,
                            Some(current) if current.specificity == candidate.specificity => {
                                RuleMatch {
                                    specificity: current.specificity,
                                    access: current.access.most_restrictive(candidate.access),
                                }
                            }
                            _ => candidate,
                        });
                    }
                }
                let access = best.map_or(AccessMode::Deny, |matched| matched.access);
                if writable_match && access == AccessMode::Write && self.is_protected_path(path) {
                    Ok(FilesystemDecision::Read)
                } else {
                    Ok(access.into())
                }
            }
        }
    }

    fn is_protected_path(&self, path: &Path) -> bool {
        self.protected_relative_paths
            .iter()
            .any(|protected| contains_component_path(path, protected))
    }
}

fn target_key(target: &FilesystemTarget) -> FilesystemTargetKey {
    match target {
        FilesystemTarget::Scope(selector) => FilesystemTargetKey::Scope(selector.clone()),
        FilesystemTarget::Glob(pattern) => {
            let (absolute, prefix, components) = pattern.semantic_key();
            FilesystemTargetKey::Glob {
                absolute,
                prefix,
                components,
            }
        }
    }
}

fn validate_protected_relative_path(path: PathBuf) -> Result<PathBuf, PolicyError> {
    if path.as_os_str().is_empty() {
        return Err(PolicyError::InvalidProtectedPath {
            path,
            reason: "path must not be empty".to_string(),
        });
    }
    if crate::path::contains_nul(&path) {
        return Err(PolicyError::InvalidProtectedPath {
            path,
            reason: "path must not contain a NUL character".to_string(),
        });
    }
    if path.is_absolute() {
        return Err(PolicyError::InvalidProtectedPath {
            path,
            reason: "path must be relative".to_string(),
        });
    }
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::Normal(value) => normalized.push(value),
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => {
                return Err(PolicyError::InvalidProtectedPath {
                    path,
                    reason: "path must not contain parent traversal or a root".to_string(),
                });
            }
        }
    }
    if normalized.as_os_str().is_empty() {
        return Err(PolicyError::InvalidProtectedPath {
            path,
            reason: "path must name a descendant".to_string(),
        });
    }
    Ok(normalized)
}