Skip to main content

tapid_runner/
config.rs

1use serde::Deserialize;
2use std::collections::BTreeMap;
3use std::fmt;
4use std::path::{Component, Path};
5
6/// Maximum accepted size of a checked-in TOML configuration document.
7pub const MAX_CONFIG_BYTES: usize = 1024 * 1024;
8/// Maximum number of per-script profiles in one configuration.
9pub const MAX_PROFILE_COUNT: usize = 256;
10/// Maximum combined read and write grants in one profile.
11pub const MAX_GRANT_COUNT: usize = 256;
12/// Maximum environment variable names allowlisted by one profile.
13pub const MAX_ENVIRONMENT_COUNT: usize = 256;
14/// Maximum UTF-8 byte length of a profile name, grant, or environment name.
15pub const MAX_STRING_BYTES: usize = 255;
16
17/// Whether execution must use containment or was explicitly overridden by a caller.
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
19pub enum SandboxMode {
20    /// Fail closed unless the requested policy can be enforced.
21    Required,
22    /// Explicit programmatic override. Checked-in configuration cannot select this mode.
23    Disabled,
24}
25
26/// Strength of the portable execution guarantee requested from a backend.
27///
28/// Consumers must include a wildcard arm so future assurance levels remain additive:
29///
30/// ```compile_fail
31/// use tapid_runner::AssuranceLevel;
32///
33/// fn label(level: AssuranceLevel) -> &'static str {
34///     match level {
35///         AssuranceLevel::Restricted => "restricted",
36///         AssuranceLevel::ManagedTree => "managed-tree",
37///     }
38/// }
39/// ```
40#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq)]
41#[non_exhaustive]
42#[serde(rename_all = "kebab-case")]
43pub enum AssuranceLevel {
44    /// Restrict ambient authority for the launched process and its descendants.
45    Restricted,
46    /// Also own the complete process tree and its cleanup boundary.
47    ManagedTree,
48}
49
50/// Project-relative filesystem grants for a sandboxed process.
51#[derive(Clone, Debug, Eq, PartialEq)]
52pub struct FilesystemPolicy {
53    read: Vec<String>,
54    write: Vec<String>,
55}
56
57impl FilesystemPolicy {
58    pub fn new(read: Vec<String>, write: Vec<String>) -> Result<Self, ConfigError> {
59        if read.len().saturating_add(write.len()) > MAX_GRANT_COUNT {
60            return Err(ConfigError::new(
61                ConfigErrorCategory::CapacityExceeded,
62                format!("filesystem policy exceeds {MAX_GRANT_COUNT} grants"),
63            ));
64        }
65        for path in read.iter().chain(&write) {
66            validate_string_length("filesystem grant", path)?;
67            validate_project_path(path)?;
68        }
69        Ok(Self { read, write })
70    }
71
72    pub fn read(&self) -> &[String] {
73        &self.read
74    }
75
76    pub fn write(&self) -> &[String] {
77        &self.write
78    }
79}
80
81/// Optional, validated execution resource ceilings.
82#[derive(Clone, Debug, Default, Eq, PartialEq)]
83pub struct ExecutionLimits {
84    timeout_seconds: Option<u64>,
85    max_output_bytes: Option<u64>,
86    max_processes: Option<u32>,
87    max_memory_bytes: Option<u64>,
88}
89
90impl ExecutionLimits {
91    pub fn new(
92        timeout_seconds: Option<u64>,
93        max_output_bytes: Option<u64>,
94        max_processes: Option<u32>,
95        max_memory_bytes: Option<u64>,
96    ) -> Result<Self, ConfigError> {
97        Ok(Self {
98            timeout_seconds: nonzero("timeout_seconds", timeout_seconds)?,
99            max_output_bytes: nonzero("max_output_bytes", max_output_bytes)?,
100            max_processes: nonzero("max_processes", max_processes)?,
101            max_memory_bytes: nonzero("max_memory_bytes", max_memory_bytes)?,
102        })
103    }
104
105    pub fn timeout_seconds(&self) -> Option<u64> {
106        self.timeout_seconds
107    }
108    pub fn max_output_bytes(&self) -> Option<u64> {
109        self.max_output_bytes
110    }
111    pub fn max_processes(&self) -> Option<u32> {
112        self.max_processes
113    }
114    pub fn max_memory_bytes(&self) -> Option<u64> {
115        self.max_memory_bytes
116    }
117}
118
119/// Complete declarative sandbox policy. This type does not imply enforcement.
120#[derive(Clone, Debug, Eq, PartialEq)]
121pub struct SandboxPolicy {
122    mode: SandboxMode,
123    assurance: AssuranceLevel,
124    filesystem: FilesystemPolicy,
125    network: bool,
126    environment: Vec<String>,
127    subprocess: bool,
128    limits: ExecutionLimits,
129}
130
131impl SandboxPolicy {
132    pub fn new(
133        mode: SandboxMode,
134        filesystem: FilesystemPolicy,
135        network: bool,
136        environment: Vec<String>,
137        subprocess: bool,
138        limits: ExecutionLimits,
139    ) -> Result<Self, ConfigError> {
140        Self::new_with_assurance(
141            mode,
142            AssuranceLevel::ManagedTree,
143            filesystem,
144            network,
145            environment,
146            subprocess,
147            limits,
148        )
149    }
150
151    pub fn new_with_assurance(
152        mode: SandboxMode,
153        assurance: AssuranceLevel,
154        filesystem: FilesystemPolicy,
155        network: bool,
156        environment: Vec<String>,
157        subprocess: bool,
158        limits: ExecutionLimits,
159    ) -> Result<Self, ConfigError> {
160        if environment.len() > MAX_ENVIRONMENT_COUNT {
161            return Err(ConfigError::new(
162                ConfigErrorCategory::CapacityExceeded,
163                format!("sandbox policy exceeds {MAX_ENVIRONMENT_COUNT} environment names"),
164            ));
165        }
166        for name in &environment {
167            validate_string_length("environment variable name", name)?;
168            validate_environment_name(name)?;
169        }
170        Ok(Self {
171            mode,
172            assurance,
173            filesystem,
174            network,
175            environment,
176            subprocess,
177            limits,
178        })
179    }
180
181    pub fn mode(&self) -> SandboxMode {
182        self.mode
183    }
184    pub fn assurance(&self) -> AssuranceLevel {
185        self.assurance
186    }
187    pub fn filesystem(&self) -> &FilesystemPolicy {
188        &self.filesystem
189    }
190    pub fn network(&self) -> bool {
191        self.network
192    }
193    pub fn environment(&self) -> &[String] {
194        &self.environment
195    }
196    pub fn subprocess(&self) -> bool {
197        self.subprocess
198    }
199    pub fn limits(&self) -> &ExecutionLimits {
200        &self.limits
201    }
202}
203
204impl Default for SandboxPolicy {
205    fn default() -> Self {
206        Self {
207            mode: SandboxMode::Required,
208            assurance: AssuranceLevel::ManagedTree,
209            filesystem: FilesystemPolicy {
210                read: vec![".".to_owned()],
211                write: Vec::new(),
212            },
213            network: false,
214            environment: Vec::new(),
215            // Node package scripts currently require a shell child.
216            subprocess: true,
217            limits: ExecutionLimits::default(),
218        }
219    }
220}
221
222/// Stable category for checked-in run configuration failures.
223#[derive(Clone, Copy, Debug, Eq, PartialEq)]
224pub enum ConfigErrorCategory {
225    Malformed,
226    UnknownKey,
227    InvalidPath,
228    InvalidEnvironment,
229    InvalidLimit,
230    CapacityExceeded,
231}
232
233/// A validation or syntax error in checked-in run configuration.
234#[derive(Clone, Debug, Eq, PartialEq)]
235pub struct ConfigError {
236    category: ConfigErrorCategory,
237    message: String,
238}
239
240impl ConfigError {
241    fn new(category: ConfigErrorCategory, message: impl Into<String>) -> Self {
242        Self {
243            category,
244            message: message.into(),
245        }
246    }
247
248    pub fn category(&self) -> ConfigErrorCategory {
249        self.category
250    }
251}
252
253impl fmt::Display for ConfigError {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.write_str(&self.message)
256    }
257}
258impl std::error::Error for ConfigError {}
259
260/// Parsed checked-in run policy with deterministic per-script overrides.
261#[derive(Clone, Debug, Eq, PartialEq)]
262pub struct RunConfig {
263    defaults: SandboxPolicy,
264    scripts: BTreeMap<String, SandboxPolicy>,
265}
266
267impl RunConfig {
268    pub fn parse_toml(input: &str) -> Result<Self, ConfigError> {
269        Self::parse_toml_bytes(input.as_bytes())
270    }
271
272    /// Parses UTF-8 TOML after enforcing the input byte ceiling before deserialization.
273    pub fn parse_toml_bytes(input: &[u8]) -> Result<Self, ConfigError> {
274        if input.len() > MAX_CONFIG_BYTES {
275            return Err(ConfigError::new(
276                ConfigErrorCategory::CapacityExceeded,
277                format!("run configuration exceeds {MAX_CONFIG_BYTES} bytes"),
278            ));
279        }
280        let input = std::str::from_utf8(input).map_err(|error| {
281            ConfigError::new(
282                ConfigErrorCategory::Malformed,
283                format!("run configuration is not valid UTF-8: {error}"),
284            )
285        })?;
286        let root: ConfigDocument = toml::from_str(input).map_err(deserialize_error)?;
287        if root.run.scripts.len() > MAX_PROFILE_COUNT {
288            return Err(ConfigError::new(
289                ConfigErrorCategory::CapacityExceeded,
290                format!("run configuration exceeds {MAX_PROFILE_COUNT} script profiles"),
291            ));
292        }
293        for name in root.run.scripts.keys() {
294            validate_string_length("script profile name", name)?;
295        }
296        let defaults = apply_profile(SandboxPolicy::default(), root.run.defaults)?;
297        let scripts = root
298            .run
299            .scripts
300            .into_iter()
301            .map(|(name, profile)| {
302                apply_profile(defaults.clone(), profile).map(|policy| (name, policy))
303            })
304            .collect::<Result<_, _>>()?;
305        Ok(Self { defaults, scripts })
306    }
307
308    pub fn defaults(&self) -> &SandboxPolicy {
309        &self.defaults
310    }
311
312    /// Returns the exact per-script profile without falling back to defaults.
313    pub fn exact_profile(&self, script: &str) -> Option<&SandboxPolicy> {
314        self.scripts.get(script)
315    }
316
317    /// Returns the exact script profile, or a clone of defaults when no override exists.
318    pub fn profile_for(&self, script: &str) -> SandboxPolicy {
319        self.scripts
320            .get(script)
321            .cloned()
322            .unwrap_or_else(|| self.defaults.clone())
323    }
324}
325
326#[derive(Debug, Default, Deserialize)]
327#[serde(default, deny_unknown_fields)]
328struct ConfigDocument {
329    run: RunSection,
330    #[serde(default, rename = "registries")]
331    _registries: Option<toml::Value>,
332}
333
334#[derive(Debug, Default, Deserialize)]
335#[serde(default, deny_unknown_fields)]
336struct RunSection {
337    defaults: RawProfile,
338    scripts: BTreeMap<String, RawProfile>,
339}
340
341#[derive(Debug, Default, Deserialize)]
342#[serde(default, deny_unknown_fields)]
343struct RawProfile {
344    assurance: Option<AssuranceLevel>,
345    read: Option<Vec<String>>,
346    write: Option<Vec<String>>,
347    network: Option<bool>,
348    environment: Option<Vec<String>>,
349    subprocess: Option<bool>,
350    timeout_seconds: Option<u64>,
351    max_output_bytes: Option<u64>,
352    max_processes: Option<u64>,
353    max_memory_bytes: Option<u64>,
354}
355
356fn deserialize_error(error: toml::de::Error) -> ConfigError {
357    let message = error.to_string();
358    let category = if message.contains("unknown field") {
359        ConfigErrorCategory::UnknownKey
360    } else if [
361        "timeout_seconds",
362        "max_output_bytes",
363        "max_processes",
364        "max_memory_bytes",
365    ]
366    .iter()
367    .any(|field| message.contains(field))
368        && (message.contains("too large")
369            || message.contains("out of range")
370            || message.contains("expected u64"))
371    {
372        ConfigErrorCategory::InvalidLimit
373    } else {
374        ConfigErrorCategory::Malformed
375    };
376    ConfigError::new(category, message)
377}
378
379fn apply_profile(mut policy: SandboxPolicy, raw: RawProfile) -> Result<SandboxPolicy, ConfigError> {
380    policy.assurance = raw.assurance.unwrap_or(policy.assurance);
381    policy.filesystem = FilesystemPolicy::new(
382        raw.read.unwrap_or(policy.filesystem.read),
383        raw.write.unwrap_or(policy.filesystem.write),
384    )?;
385    policy.network = raw.network.unwrap_or(policy.network);
386    if let Some(environment) = raw.environment {
387        if environment.len() > MAX_ENVIRONMENT_COUNT {
388            return Err(ConfigError::new(
389                ConfigErrorCategory::CapacityExceeded,
390                format!("sandbox policy exceeds {MAX_ENVIRONMENT_COUNT} environment names"),
391            ));
392        }
393        for name in &environment {
394            validate_string_length("environment variable name", name)?;
395            validate_environment_name(name)?;
396        }
397        policy.environment = environment;
398    }
399    policy.subprocess = raw.subprocess.unwrap_or(policy.subprocess);
400    policy.limits = ExecutionLimits::new(
401        raw.timeout_seconds.or(policy.limits.timeout_seconds),
402        raw.max_output_bytes.or(policy.limits.max_output_bytes),
403        match raw.max_processes {
404            Some(value) => Some(u32::try_from(value).map_err(|_| {
405                invalid_limit("max_processes", "must fit in an unsigned 32-bit integer")
406            })?),
407            None => policy.limits.max_processes,
408        },
409        raw.max_memory_bytes.or(policy.limits.max_memory_bytes),
410    )?;
411    Ok(policy)
412}
413
414fn nonzero<T>(name: &str, value: Option<T>) -> Result<Option<T>, ConfigError>
415where
416    T: Copy + Default + PartialEq,
417{
418    if value == Some(T::default()) {
419        Err(invalid_limit(name, "must be greater than zero"))
420    } else {
421        Ok(value)
422    }
423}
424
425fn invalid_limit(name: &str, reason: &str) -> ConfigError {
426    ConfigError::new(
427        ConfigErrorCategory::InvalidLimit,
428        format!("{name} {reason}"),
429    )
430}
431
432fn validate_string_length(kind: &str, value: &str) -> Result<(), ConfigError> {
433    if value.len() > MAX_STRING_BYTES {
434        return Err(ConfigError::new(
435            ConfigErrorCategory::CapacityExceeded,
436            format!("{kind} exceeds {MAX_STRING_BYTES} UTF-8 bytes"),
437        ));
438    }
439    Ok(())
440}
441
442fn validate_project_path(value: &str) -> Result<(), ConfigError> {
443    let path = Path::new(value);
444    let windows_absolute = value.starts_with(['\\', '/'])
445        || value.as_bytes().get(1) == Some(&b':')
446            && value
447                .as_bytes()
448                .first()
449                .is_some_and(u8::is_ascii_alphabetic);
450    let components: Vec<_> = value.split('/').collect();
451    let invalid_component = components.iter().any(|component| {
452        component.is_empty()
453            || (*component == "." && value != ".")
454            || *component == ".."
455            || (*component != "." && component.ends_with(['.', ' ']))
456            || component.chars().any(|character| {
457                character.is_control()
458                    || matches!(character, '<' | '>' | ':' | '"' | '|' | '?' | '*' | '\\')
459            })
460            || is_windows_reserved_component(component)
461    });
462    if value.is_empty()
463        || path.is_absolute()
464        || windows_absolute
465        || invalid_component
466        || path.components().any(|component| {
467            matches!(
468                component,
469                Component::ParentDir | Component::RootDir | Component::Prefix(_)
470            )
471        })
472    {
473        return Err(ConfigError::new(
474            ConfigErrorCategory::InvalidPath,
475            format!("filesystem grant is not a portable project-relative path: {value:?}"),
476        ));
477    }
478    Ok(())
479}
480
481fn is_windows_reserved_component(component: &str) -> bool {
482    let stem = component.split('.').next().unwrap_or(component);
483    let upper = stem.to_ascii_uppercase();
484    matches!(
485        upper.as_str(),
486        "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
487    ) || upper
488        .strip_prefix("COM")
489        .is_some_and(is_windows_reserved_port)
490        || upper
491            .strip_prefix("LPT")
492            .is_some_and(is_windows_reserved_port)
493}
494
495fn is_windows_reserved_port(suffix: &str) -> bool {
496    matches!(
497        suffix,
498        "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
499    )
500}
501
502pub(crate) fn validate_environment_name(name: &str) -> Result<(), ConfigError> {
503    let mut chars = name.chars();
504    let valid_start = chars
505        .next()
506        .is_some_and(|c| c == '_' || c.is_ascii_alphabetic());
507    if !valid_start || !chars.all(|c| c == '_' || c.is_ascii_alphanumeric()) {
508        return Err(ConfigError::new(
509            ConfigErrorCategory::InvalidEnvironment,
510            format!("invalid environment variable name: {name:?}"),
511        ));
512    }
513    Ok(())
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519
520    #[test]
521    fn assurance_defaults_to_managed_tree_and_can_be_restricted_explicitly() {
522        let legacy = RunConfig::parse_toml("").unwrap();
523        assert_eq!(legacy.defaults().assurance(), AssuranceLevel::ManagedTree);
524
525        let restricted = RunConfig::parse_toml(
526            "[run.defaults]\nassurance = \"restricted\"\n[run.scripts.strict]\nassurance = \"managed-tree\"",
527        )
528        .unwrap();
529        assert_eq!(
530            restricted.defaults().assurance(),
531            AssuranceLevel::Restricted
532        );
533        assert_eq!(
534            restricted.profile_for("strict").assurance(),
535            AssuranceLevel::ManagedTree
536        );
537    }
538
539    #[test]
540    fn defaults_are_fail_closed_and_profiles_override_individual_fields() {
541        let config = RunConfig::parse_toml(
542            r#"
543            [run.defaults]
544            read = [".", "fixtures"]
545            timeout_seconds = 30
546
547            [run.scripts.build]
548            write = ["dist"]
549            network = true
550            environment = ["NODE_ENV"]
551            max_output_bytes = 4096
552            max_processes = 4
553            max_memory_bytes = 1048576
554            "#,
555        )
556        .unwrap();
557
558        let defaults = config.defaults();
559        assert_eq!(defaults.mode(), SandboxMode::Required);
560        assert_eq!(defaults.filesystem().read(), &[".", "fixtures"]);
561        assert!(defaults.filesystem().write().is_empty());
562        assert!(!defaults.network());
563        assert!(defaults.environment().is_empty());
564        assert!(defaults.subprocess());
565        assert_eq!(defaults.limits().timeout_seconds(), Some(30));
566
567        let build = config.profile_for("build");
568        assert_eq!(build.mode(), SandboxMode::Required);
569        assert_eq!(build.filesystem().read(), &[".", "fixtures"]);
570        assert_eq!(build.filesystem().write(), &["dist"]);
571        assert!(build.network());
572        assert_eq!(build.environment(), &["NODE_ENV"]);
573        assert!(build.subprocess());
574        assert_eq!(build.limits().timeout_seconds(), Some(30));
575        assert_eq!(build.limits().max_output_bytes(), Some(4096));
576        assert_eq!(build.limits().max_processes(), Some(4));
577        assert_eq!(build.limits().max_memory_bytes(), Some(1048576));
578    }
579
580    #[test]
581    fn empty_config_uses_required_project_only_defaults() {
582        let config = RunConfig::parse_toml("").unwrap();
583        let defaults = config.defaults();
584        assert_eq!(defaults.mode(), SandboxMode::Required);
585        assert_eq!(defaults.filesystem().read(), &["."]);
586        assert!(defaults.filesystem().write().is_empty());
587        assert!(!defaults.network());
588        assert!(defaults.environment().is_empty());
589        assert!(defaults.subprocess());
590        assert_eq!(defaults.limits(), &ExecutionLimits::default());
591    }
592
593    #[test]
594    fn public_policy_constructors_validate_untrusted_values() {
595        assert_eq!(
596            FilesystemPolicy::new(vec!["../outside".into()], vec![])
597                .unwrap_err()
598                .category(),
599            ConfigErrorCategory::InvalidPath
600        );
601        assert_eq!(
602            ExecutionLimits::new(Some(0), None, None, None)
603                .unwrap_err()
604                .category(),
605            ConfigErrorCategory::InvalidLimit
606        );
607        assert_eq!(
608            SandboxPolicy::new(
609                SandboxMode::Disabled,
610                FilesystemPolicy::new(vec![".".into()], vec![]).unwrap(),
611                false,
612                vec!["BAD-NAME".into()],
613                true,
614                ExecutionLimits::default(),
615            )
616            .unwrap_err()
617            .category(),
618            ConfigErrorCategory::InvalidEnvironment
619        );
620    }
621
622    #[test]
623    fn rejects_unknown_keys_and_malformed_field_types() {
624        let unknown = RunConfig::parse_toml("[run.defaults]\nsandbox = \"disabled\"").unwrap_err();
625        assert_eq!(unknown.category(), ConfigErrorCategory::UnknownKey);
626
627        for source in [
628            "unexpected = true",
629            "[run]\nunexpected = true",
630            "[run.scripts.build]\nunexpected = true",
631        ] {
632            let error = RunConfig::parse_toml(source).unwrap_err();
633            assert_eq!(
634                error.category(),
635                ConfigErrorCategory::UnknownKey,
636                "{source}"
637            );
638        }
639
640        let malformed = RunConfig::parse_toml("[run.defaults]\nnetwork = \"yes\"").unwrap_err();
641        assert_eq!(malformed.category(), ConfigErrorCategory::Malformed);
642    }
643
644    #[test]
645    fn accepts_registry_configuration_alongside_strict_run_policy() {
646        let config = RunConfig::parse_toml(
647            "[registries.default]\nurl='https://mirror.example'\n[run.scripts.dev]\nnetwork=false\n",
648        )
649        .unwrap();
650        assert!(!config.exact_profile("dev").unwrap().network());
651
652        let error = RunConfig::parse_toml(
653            "[registries.default]\nurl='https://mirror.example'\n[run.defaults]\nunknown=true\n",
654        )
655        .unwrap_err();
656        assert_eq!(error.category(), ConfigErrorCategory::UnknownKey);
657    }
658
659    #[test]
660    fn accepts_standard_toml_strings_comments_and_multiline_arrays() {
661        let config = RunConfig::parse_toml(
662            r#"
663            [run.defaults] # standard TOML comments are supported
664            read = [
665                '.',
666                "fixtures\u002fdata",
667            ]
668            environment = ["NODE_ENV"]
669
670            [run.scripts."build:web"]
671            write = ['dist']
672            "#,
673        )
674        .unwrap();
675
676        assert_eq!(
677            config.defaults().filesystem().read(),
678            &[".", "fixtures/data"]
679        );
680        assert_eq!(
681            config.profile_for("build:web").filesystem().write(),
682            &["dist"]
683        );
684    }
685
686    #[test]
687    fn rejects_absolute_traversing_and_backslash_grants_on_every_platform() {
688        for path in [
689            "/etc",
690            "../secrets",
691            "safe/../../secrets",
692            r"C:\Windows",
693            r"dir\file",
694            r"plain\name",
695        ] {
696            let source = format!("[run.defaults]\nread = [{path:?}]");
697            let error = RunConfig::parse_toml(&source).unwrap_err();
698            assert_eq!(error.category(), ConfigErrorCategory::InvalidPath, "{path}");
699        }
700    }
701
702    #[test]
703    fn rejects_nonportable_and_ambiguous_grant_components_on_every_platform() {
704        for path in [
705            "has\0nul",
706            "file:stream",
707            "dir/file:stream",
708            "CON",
709            "con.txt",
710            "NUL.json",
711            "aux.data/more",
712            "COM1.log",
713            "com¹.log",
714            "LPT².txt",
715            "CONIN$",
716            "conout$.txt",
717            "lpt9",
718            "name.",
719            "name ",
720            "dir//file",
721            "dir/./file",
722            "dir/<file>",
723            "dir/file?",
724            "dir/file*",
725            "dir/file|name",
726            "dir/file\u{1f}",
727        ] {
728            let error = FilesystemPolicy::new(vec![path.to_owned()], vec![]).unwrap_err();
729            assert_eq!(
730                error.category(),
731                ConfigErrorCategory::InvalidPath,
732                "{path:?}"
733            );
734        }
735    }
736
737    #[test]
738    fn accepts_portable_names_that_only_contain_reserved_name_substrings() {
739        let policy = FilesystemPolicy::new(
740            vec![
741                "console".into(),
742                "connection.txt".into(),
743                "com10.log".into(),
744            ],
745            vec!["auxiliary/output".into()],
746        )
747        .unwrap();
748        assert_eq!(policy.read().len(), 3);
749        assert_eq!(policy.write().len(), 1);
750    }
751
752    #[test]
753    fn parsing_rejects_config_bytes_above_the_published_limit() {
754        let at_limit = vec![b' '; MAX_CONFIG_BYTES];
755        assert!(RunConfig::parse_toml_bytes(&at_limit).is_ok());
756
757        let above_limit = vec![b' '; MAX_CONFIG_BYTES + 1];
758        let error = RunConfig::parse_toml_bytes(&above_limit).unwrap_err();
759        assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
760    }
761
762    #[test]
763    fn parsing_bounds_script_profile_count_at_the_published_limit() {
764        let source = (0..MAX_PROFILE_COUNT)
765            .map(|index| format!("[run.scripts.p{index}]\nnetwork = false\n"))
766            .collect::<String>();
767        assert!(RunConfig::parse_toml(&source).is_ok());
768
769        let above_limit = format!("{source}[run.scripts.overflow]\nnetwork = false\n");
770        let error = RunConfig::parse_toml(&above_limit).unwrap_err();
771        assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
772    }
773
774    #[test]
775    fn filesystem_policy_bounds_total_grant_count_at_the_published_limit() {
776        let at_limit = vec!["portable".to_owned(); MAX_GRANT_COUNT];
777        assert!(FilesystemPolicy::new(at_limit, vec![]).is_ok());
778
779        let above_limit = vec!["portable".to_owned(); MAX_GRANT_COUNT + 1];
780        let error = FilesystemPolicy::new(above_limit, vec![]).unwrap_err();
781        assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
782    }
783
784    #[test]
785    fn sandbox_policy_bounds_environment_count_at_the_published_limit() {
786        let filesystem = FilesystemPolicy::new(vec![".".into()], vec![]).unwrap();
787        let at_limit = vec!["VALID_NAME".to_owned(); MAX_ENVIRONMENT_COUNT];
788        assert!(
789            SandboxPolicy::new(
790                SandboxMode::Required,
791                filesystem.clone(),
792                false,
793                at_limit,
794                true,
795                ExecutionLimits::default(),
796            )
797            .is_ok()
798        );
799
800        let above_limit = vec!["VALID_NAME".to_owned(); MAX_ENVIRONMENT_COUNT + 1];
801        let error = SandboxPolicy::new(
802            SandboxMode::Required,
803            filesystem,
804            false,
805            above_limit,
806            true,
807            ExecutionLimits::default(),
808        )
809        .unwrap_err();
810        assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
811    }
812
813    #[test]
814    fn filesystem_policy_bounds_grant_string_bytes_at_the_published_limit() {
815        let at_limit = "a".repeat(MAX_STRING_BYTES);
816        assert!(FilesystemPolicy::new(vec![at_limit], vec![]).is_ok());
817
818        let above_limit = "a".repeat(MAX_STRING_BYTES + 1);
819        let error = FilesystemPolicy::new(vec![above_limit], vec![]).unwrap_err();
820        assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
821    }
822
823    #[test]
824    fn sandbox_policy_bounds_environment_name_bytes_at_the_published_limit() {
825        let filesystem = FilesystemPolicy::new(vec![".".into()], vec![]).unwrap();
826        let at_limit = format!("E{}", "A".repeat(MAX_STRING_BYTES - 1));
827        assert!(
828            SandboxPolicy::new(
829                SandboxMode::Required,
830                filesystem.clone(),
831                false,
832                vec![at_limit],
833                true,
834                ExecutionLimits::default(),
835            )
836            .is_ok()
837        );
838
839        let above_limit = format!("E{}", "A".repeat(MAX_STRING_BYTES));
840        let error = SandboxPolicy::new(
841            SandboxMode::Required,
842            filesystem,
843            false,
844            vec![above_limit],
845            true,
846            ExecutionLimits::default(),
847        )
848        .unwrap_err();
849        assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
850    }
851
852    #[test]
853    fn parsing_bounds_profile_name_bytes_at_the_published_limit() {
854        let at_limit = "a".repeat(MAX_STRING_BYTES);
855        let source = format!("[run.scripts.{at_limit:?}]\nnetwork = false\n");
856        assert!(RunConfig::parse_toml(&source).is_ok());
857
858        let above_limit = "a".repeat(MAX_STRING_BYTES + 1);
859        let source = format!("[run.scripts.{above_limit:?}]\nnetwork = false\n");
860        let error = RunConfig::parse_toml(&source).unwrap_err();
861        assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
862    }
863
864    #[test]
865    fn parsing_applies_environment_count_limit_to_every_profile() {
866        let names = (0..=MAX_ENVIRONMENT_COUNT)
867            .map(|index| format!("\"E{index}\""))
868            .collect::<Vec<_>>()
869            .join(",");
870        for table in ["run.defaults", "run.scripts.build"] {
871            let source = format!("[{table}]\nenvironment = [{names}]\n");
872            let error = RunConfig::parse_toml(&source).unwrap_err();
873            assert_eq!(error.category(), ConfigErrorCategory::CapacityExceeded);
874        }
875    }
876
877    #[test]
878    fn rejects_invalid_environment_names() {
879        for name in ["", "1TOKEN", "BAD-NAME", "UNICODÉ"] {
880            let source = format!("[run.defaults]\nenvironment = [{name:?}]");
881            let error = RunConfig::parse_toml(&source).unwrap_err();
882            assert_eq!(
883                error.category(),
884                ConfigErrorCategory::InvalidEnvironment,
885                "{name}"
886            );
887        }
888    }
889
890    #[test]
891    fn rejects_zero_and_overflowing_limits() {
892        for field in [
893            "timeout_seconds",
894            "max_output_bytes",
895            "max_processes",
896            "max_memory_bytes",
897        ] {
898            let error = RunConfig::parse_toml(&format!("[run.defaults]\n{field} = 0")).unwrap_err();
899            assert_eq!(
900                error.category(),
901                ConfigErrorCategory::InvalidLimit,
902                "{field}"
903            );
904        }
905
906        let process_overflow =
907            RunConfig::parse_toml("[run.defaults]\nmax_processes = 4294967296").unwrap_err();
908        assert_eq!(
909            process_overflow.category(),
910            ConfigErrorCategory::InvalidLimit
911        );
912
913        let integer_overflow =
914            RunConfig::parse_toml("[run.defaults]\nmax_memory_bytes = 18446744073709551616")
915                .unwrap_err();
916        assert_eq!(
917            integer_overflow.category(),
918            ConfigErrorCategory::InvalidLimit,
919            "{integer_overflow}"
920        );
921    }
922
923    #[test]
924    fn profile_lookup_is_exact_and_deterministic() {
925        let config = RunConfig::parse_toml(
926            "[run.scripts.z]\nnetwork = true\n[run.scripts.a]\nsubprocess = false",
927        )
928        .unwrap();
929        assert!(config.profile_for("z").network());
930        assert!(!config.profile_for("a").subprocess());
931        assert_eq!(config.profile_for("missing"), config.defaults().clone());
932        assert_eq!(config.profile_for("A"), config.defaults().clone());
933    }
934
935    #[test]
936    fn exact_profile_lookup_never_falls_back_to_defaults() {
937        let config = RunConfig::parse_toml("[run.scripts.dev]\nnetwork = true").unwrap();
938
939        assert!(config.exact_profile("dev").unwrap().network());
940        assert!(config.exact_profile("missing").is_none());
941        assert!(config.exact_profile("Dev").is_none());
942    }
943}