cageforge-command 0.7.1

Validated command, environment, and stdio requests for Rust 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
// SPDX-License-Identifier: Apache-2.0

//! Environment bases, filters, and overrides for [`crate::EnvironmentSpec`].
//!
//! This module describes transformations but does not discover the operating
//! system's core variables. A backend supplies that base when it applies the
//! [`crate::EnvironmentBase::Core`] request.

use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap};
use std::ffi::{OsStr, OsString};
use std::hash::{Hash, Hasher};

#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;
#[cfg(windows)]
use std::os::windows::ffi::OsStrExt;

use wildmatch::WildMatch;

use crate::CommandError;
use crate::command::contains_nul;

mod model;

use model::{CaseFoldedText, EnvironmentNameIdentity};
pub use model::{
    CoreEnvironment, EnvironmentBase, EnvironmentFilterAction, EnvironmentInput,
    EnvironmentNameKey, EnvironmentOverride, EnvironmentPattern, EnvironmentSpec,
};

impl PartialEq for EnvironmentPattern {
    fn eq(&self, other: &Self) -> bool {
        self.canonical == other.canonical
    }
}

impl Eq for EnvironmentPattern {}

impl Hash for EnvironmentPattern {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.canonical.hash(state);
    }
}

impl PartialOrd for EnvironmentPattern {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for EnvironmentPattern {
    fn cmp(&self, other: &Self) -> Ordering {
        self.canonical.cmp(&other.canonical)
    }
}

impl EnvironmentPattern {
    /// Creates a validated environment-variable pattern.
    pub fn new(pattern: impl Into<String>) -> Result<Self, CommandError> {
        let pattern = pattern.into();
        if pattern.is_empty() {
            return Err(CommandError::EmptyEnvironmentPattern);
        }
        if contains_nul(OsStr::new(&pattern)) {
            return Err(CommandError::EnvironmentPatternContainsNul);
        }
        if pattern.contains('=') {
            return Err(CommandError::EnvironmentPatternContainsEquals);
        }
        Ok(Self {
            canonical: case_folded_text(&pattern),
            matcher: WildMatch::new_case_insensitive(&pattern),
            original: pattern,
        })
    }

    /// Returns the original pattern text.
    ///
    /// Trait identity is based on the same case-insensitive canonical form as
    /// [`Self::matches`], while this accessor preserves the caller's spelling
    /// for diagnostics and serialization.
    pub fn as_str(&self) -> &str {
        &self.original
    }

    /// Returns whether this pattern matches an environment variable name.
    pub fn matches(&self, name: &str) -> bool {
        self.matcher.matches(name)
    }
}

impl EnvironmentNameKey {
    /// Creates the policy identity for one native environment-variable name.
    pub fn new(name: &OsStr) -> Self {
        Self(environment_name_identity(name))
    }
}

impl CoreEnvironment {
    /// Creates a validated core snapshot from variables selected by the
    /// process adapter.
    pub fn from_selected<I>(variables: I) -> Result<Self, CommandError>
    where
        I: IntoIterator<Item = (OsString, OsString)>,
    {
        Ok(Self {
            variables: collect_environment(variables)?,
        })
    }

    /// Returns the selected core variables.
    pub fn variables(&self) -> &BTreeMap<OsString, OsString> {
        &self.variables
    }
}

impl EnvironmentInput {
    /// Creates a validated input containing all inherited variables.
    pub fn all<I>(variables: I) -> Result<Self, CommandError>
    where
        I: IntoIterator<Item = (OsString, OsString)>,
    {
        Ok(Self {
            base: EnvironmentBase::All,
            variables: collect_environment(variables)?,
        })
    }

    /// Creates an input containing a process adapter's selected core set.
    pub fn core(environment: CoreEnvironment) -> Self {
        Self {
            base: EnvironmentBase::Core,
            variables: environment.variables,
        }
    }

    /// Creates an input with no inherited variables.
    pub fn empty() -> Self {
        Self {
            base: EnvironmentBase::None,
            variables: BTreeMap::new(),
        }
    }

    /// Returns the declared base represented by this input.
    pub const fn base(&self) -> EnvironmentBase {
        self.base
    }

    /// Returns the variables represented by this input.
    pub fn variables(&self) -> &BTreeMap<OsString, OsString> {
        &self.variables
    }

    /// Consumes the input and returns its selected variables.
    pub fn into_variables(self) -> BTreeMap<OsString, OsString> {
        self.variables
    }
}

impl PartialEq for EnvironmentSpec {
    fn eq(&self, other: &Self) -> bool {
        self.base == other.base
            && self.filters == other.filters
            && self.override_names.len() == other.override_names.len()
            && self.override_names.iter().all(|(key, name)| {
                let Some(other_name) = other.override_names.get(key) else {
                    return false;
                };
                self.overrides.get(name) == other.overrides.get(other_name)
            })
    }
}

impl Eq for EnvironmentSpec {}

impl EnvironmentSpec {
    /// Creates an environment that inherits all parent variables.
    pub fn inherit_all() -> Self {
        Self {
            base: EnvironmentBase::All,
            overrides: BTreeMap::new(),
            override_names: HashMap::new(),
            filters: BTreeMap::new(),
        }
    }

    /// Creates an environment that starts empty.
    pub fn empty() -> Self {
        Self {
            base: EnvironmentBase::None,
            overrides: BTreeMap::new(),
            override_names: HashMap::new(),
            filters: BTreeMap::new(),
        }
    }

    /// Creates an environment that inherits the platform's core variables.
    pub fn inherit_core() -> Self {
        Self {
            base: EnvironmentBase::Core,
            overrides: BTreeMap::new(),
            override_names: HashMap::new(),
            filters: BTreeMap::new(),
        }
    }

    /// Returns the selected base environment behavior.
    pub fn base(&self) -> EnvironmentBase {
        self.base
    }

    /// Returns all explicit variable overrides in deterministic key order.
    ///
    /// The spelling of a name is retained for backend diagnostics, but names
    /// are one case-insensitive logical namespace for lookup and equality.
    pub fn overrides(&self) -> &BTreeMap<OsString, EnvironmentOverride> {
        &self.overrides
    }

    /// Returns canonical environment filters in deterministic pattern order.
    pub fn filters(&self) -> &BTreeMap<EnvironmentPattern, EnvironmentFilterAction> {
        &self.filters
    }

    /// Returns the override for one variable, if present.
    pub fn override_for(&self, name: &OsStr) -> Option<&EnvironmentOverride> {
        self.override_names
            .get(&EnvironmentNameKey::new(name))
            .and_then(|name| self.overrides.get(name))
    }

    /// Returns the filter action for a variable name, if a filter matches.
    ///
    /// Exclude always wins when both actions match. A backend can use the
    /// presence of any include filter together with this result to implement
    /// the complete inherited-environment decision without reimplementing
    /// wildcard precedence.
    pub fn filter_action_for(&self, name: &str) -> Option<EnvironmentFilterAction> {
        let mut include_matches = false;
        for (pattern, action) in &self.filters {
            if pattern.matches(name) {
                match action {
                    EnvironmentFilterAction::Include => include_matches = true,
                    EnvironmentFilterAction::Exclude => {
                        return Some(EnvironmentFilterAction::Exclude);
                    }
                }
            }
        }
        include_matches.then_some(EnvironmentFilterAction::Include)
    }

    /// Applies filters and explicit overrides to an already selected base
    /// environment.
    ///
    /// The caller selects the `All`, `Core`, or `None` base at the backend
    /// boundary. A broader input is rejected before transformation. This
    /// method then applies the portable sequence `exclude -> set/remove ->
    /// include` and keeps the validated base tag on the returned snapshot. A
    /// variable removed by an exclude is not restored by an include; an
    /// explicit set is applied after exclusion and can intentionally
    /// reintroduce that named variable.
    pub fn apply_to(&self, input: EnvironmentInput) -> Result<EnvironmentInput, CommandError> {
        if !base_is_at_most(input.base, self.base) {
            return Err(CommandError::EnvironmentBaseTooPermissive {
                required: self.base,
                supplied: input.base,
            });
        }
        let base = input.base;
        let variables = input.variables;
        let mut environment = BTreeMap::new();
        let mut environment_names = HashMap::new();
        for (name, value) in variables {
            remove_environment_name(&mut environment, &mut environment_names, &name);
            environment_names.insert(EnvironmentNameKey::new(&name), name.clone());
            environment.insert(name, value);
        }
        let has_include_filter = self
            .filters
            .values()
            .any(|action| *action == EnvironmentFilterAction::Include);

        environment.retain(|name, _| {
            self.filters.is_empty()
                || name.to_str().is_some_and(|name| {
                    !self.filters.iter().any(|(pattern, action)| {
                        *action == EnvironmentFilterAction::Exclude && pattern.matches(name)
                    })
                })
        });

        for (name, value) in &self.overrides {
            match value {
                EnvironmentOverride::Set(value) => {
                    remove_environment_name(&mut environment, &mut environment_names, name);
                    environment_names.insert(EnvironmentNameKey::new(name), name.clone());
                    environment.insert(name.clone(), value.clone());
                }
                EnvironmentOverride::Remove => {
                    remove_environment_name(&mut environment, &mut environment_names, name);
                }
            }
        }

        if has_include_filter {
            environment.retain(|name, _| {
                name.to_str().is_some_and(|name| {
                    self.filters.iter().any(|(pattern, action)| {
                        *action == EnvironmentFilterAction::Include && pattern.matches(name)
                    })
                })
            });
        } else if !self.filters.is_empty() {
            environment.retain(|name, _| name.to_str().is_some());
        }

        Ok(EnvironmentInput {
            base,
            variables: environment,
        })
    }

    /// Adds a variable assignment and returns the updated environment.
    pub fn with_var(
        mut self,
        name: impl Into<OsString>,
        value: impl Into<OsString>,
    ) -> Result<Self, CommandError> {
        let name = name.into();
        let value = value.into();
        validate_name(&name)?;
        if contains_nul(&value) {
            return Err(CommandError::EnvironmentValueContainsNul);
        }
        remove_environment_name(&mut self.overrides, &mut self.override_names, &name);
        self.override_names
            .insert(EnvironmentNameKey::new(&name), name.clone());
        self.overrides.insert(name, EnvironmentOverride::Set(value));
        Ok(self)
    }

    /// Adds a variable removal and returns the updated environment.
    pub fn without_var(mut self, name: impl Into<OsString>) -> Result<Self, CommandError> {
        let name = name.into();
        validate_name(&name)?;
        remove_environment_name(&mut self.overrides, &mut self.override_names, &name);
        self.override_names
            .insert(EnvironmentNameKey::new(&name), name.clone());
        self.overrides.insert(name, EnvironmentOverride::Remove);
        Ok(self)
    }

    /// Adds or replaces a canonical environment filter.
    pub fn with_filter(
        mut self,
        pattern: impl Into<String>,
        action: EnvironmentFilterAction,
    ) -> Result<Self, CommandError> {
        let pattern = EnvironmentPattern::new(pattern)?;
        self.filters.remove(&pattern);
        self.filters.insert(pattern, action);
        Ok(self)
    }

    /// Adds an include filter.
    pub fn with_include_pattern(self, pattern: impl Into<String>) -> Result<Self, CommandError> {
        self.with_filter(pattern, EnvironmentFilterAction::Include)
    }

    /// Adds an exclude filter.
    pub fn with_exclude_pattern(self, pattern: impl Into<String>) -> Result<Self, CommandError> {
        self.with_filter(pattern, EnvironmentFilterAction::Exclude)
    }
}

impl Default for EnvironmentSpec {
    fn default() -> Self {
        Self::inherit_core()
    }
}

fn validate_name(name: &OsStr) -> Result<(), CommandError> {
    if name.is_empty() {
        return Err(CommandError::EmptyEnvironmentName);
    }
    if contains_nul(name) {
        return Err(CommandError::EnvironmentNameContainsNul);
    }
    if name.to_string_lossy().contains('=') {
        return Err(CommandError::EnvironmentNameContainsEquals);
    }
    Ok(())
}

fn collect_environment<I>(variables: I) -> Result<BTreeMap<OsString, OsString>, CommandError>
where
    I: IntoIterator<Item = (OsString, OsString)>,
{
    let mut collected = BTreeMap::new();
    let mut names = HashMap::new();
    for (name, value) in variables {
        validate_name(&name)?;
        if contains_nul(&value) {
            return Err(CommandError::EnvironmentValueContainsNul);
        }
        remove_environment_name(&mut collected, &mut names, &name);
        names.insert(EnvironmentNameKey::new(&name), name.clone());
        collected.insert(name, value);
    }
    Ok(collected)
}

fn remove_environment_name<V>(
    values: &mut BTreeMap<OsString, V>,
    names: &mut HashMap<EnvironmentNameKey, OsString>,
    name: &OsStr,
) {
    if let Some(existing) = names.remove(&EnvironmentNameKey::new(name)) {
        values.remove(&existing);
    }
}

fn environment_name_identity(name: &OsStr) -> EnvironmentNameIdentity {
    if let Some(name) = name.to_str() {
        return EnvironmentNameIdentity::Folded(case_folded_text(name));
    }
    #[cfg(unix)]
    {
        EnvironmentNameIdentity::NativeBytes(name.as_bytes().to_vec())
    }
    #[cfg(windows)]
    {
        EnvironmentNameIdentity::NativeWide(name.encode_wide().collect())
    }
}

fn case_folded_text(value: &str) -> CaseFoldedText {
    CaseFoldedText(
        value
            .chars()
            .map(|character| character.to_lowercase().collect())
            .collect(),
    )
}

fn base_is_at_most(supplied: EnvironmentBase, required: EnvironmentBase) -> bool {
    match required {
        EnvironmentBase::None => supplied == EnvironmentBase::None,
        EnvironmentBase::Core => supplied != EnvironmentBase::All,
        EnvironmentBase::All => true,
    }
}