subc-daemon 0.49.2

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
//! Resolve once for both program approval and execution. Arguments are never code inputs.

use super::{
    capture::{capture_program, capture_program_classified},
    CapturedInput, GateError, InputKey, Result,
};
use crate::supervise::{ModuleSpec, SpawnProgramBinding};
use std::{collections::BTreeMap, fs::File, path::Path};

pub(crate) fn approved_base(snapshot: &super::GateSnapshot, module: &str) -> subc_config::Digest {
    subc_config::raw_digest(
        &serde_json::to_vec(
            &snapshot
                .inputs
                .iter()
                .filter(|(key, _)| key.is_program() && key.module() == Some(module))
                .collect::<Vec<_>>(),
        )
        .expect("program inputs are serializable"),
    )
}

pub(crate) struct ProgramLaunch {
    pub(crate) spec: ModuleSpec,
    pub(crate) inputs: BTreeMap<InputKey, CapturedInput>,
    pub(crate) files: Vec<File>,
    pub(crate) image: subc_os::RetainedFileIdentity,
    pub(crate) script: Option<crate::supervise::script::ScriptBytes>,
    bindings: Vec<(std::path::PathBuf, subc_os::RetainedFileIdentity)>,
    #[cfg(windows)]
    _windows_files: Vec<File>,
}

impl ProgramLaunch {
    pub(crate) fn validate_for_spawn(&self) -> Result<()> {
        self.check_files(false)?;
        #[cfg(target_os = "macos")]
        if self
            .executable_value()?
            .get("cdhashes")
            .and_then(|value| value.as_array())
            .is_none_or(|hashes| hashes.is_empty())
        {
            return Err(GateError::new(
                "program_refused",
                "approved executable has no validated code directory",
            ));
        }
        #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))]
        return Err(GateError::new(
            "program_refused",
            "content binding is unsupported on this platform",
        ));
        #[cfg(any(target_os = "linux", target_os = "macos", windows))]
        Ok(())
    }
    pub(crate) fn check_files(&self, auxiliary_only: bool) -> Result<()> {
        for (path, _) in &self.bindings {
            if auxiliary_only && *path == self.spec.program {
                continue;
            }
            let key = InputKey::Program {
                module: self.spec.module_id.clone(),
                path: path.to_string_lossy().into_owned(),
            };
            let (_, actual) = capture_program(path).map_err(|error| {
                let code = if definite_capture_error(&error) {
                    "program_refused"
                } else {
                    "config_delivery_deferred"
                };
                GateError::new(code, error.detail)
            })?;
            if self
                .inputs
                .get(&key)
                .is_none_or(|expected| expected.state != actual.state)
            {
                return Err(GateError::new(
                    "program_refused",
                    "covered file content differs from its approved witness",
                ));
            }
        }
        Ok(())
    }
    pub(crate) fn executable_value(&self) -> Result<&serde_json::Value> {
        self.inputs
            .get(&InputKey::Program {
                module: self.spec.module_id.clone(),
                path: self.spec.program.to_string_lossy().into_owned(),
            })
            .and_then(|input| match &input.value {
                subc_config::RecordedValue::Value { value } => Some(value),
                _ => None,
            })
            .ok_or_else(|| {
                GateError::new(
                    "program_refused",
                    "approved executable witness is unavailable",
                )
            })
    }
    #[cfg(windows)]
    pub(crate) fn release_hello_handles(&mut self) {
        self._windows_files.clear();
    }
}

pub(crate) fn program_files(entry: &serde_json::Value) -> Result<Vec<String>> {
    let Some(files) = entry.get("program_files") else {
        return Ok(Vec::new());
    };
    files
        .as_array()
        .ok_or_else(|| GateError::new("program_refused", "program_files must be an array"))?
        .iter()
        .map(|file| {
            let path = file
                .as_str()
                .filter(|path| Path::new(path).is_absolute())
                .ok_or_else(|| {
                    GateError::new(
                        "program_refused",
                        "program_files entries must be absolute paths",
                    )
                })?;
            Ok(path.to_owned())
        })
        .collect()
}

pub(crate) fn definite_program_change(approved: &BTreeMap<InputKey, CapturedInput>) -> bool {
    approved.iter().any(|(key, expected)| {
        let InputKey::Program { path, .. } = key else {
            return false;
        };
        if let subc_config::RecordedValue::Value { value } = &expected.value {
            if value.get("kind").and_then(|kind| kind.as_str()) == Some("script") {
                let runtime = match value.get("runtime").and_then(|runtime| runtime.as_str()) {
                    Some("bun") => crate::ScriptRuntime::Bun,
                    Some("python") => crate::ScriptRuntime::Python,
                    _ => return true,
                };
                let entry = crate::ScriptEntry::new(runtime, path.into());
                return crate::supervise::script::ScriptBytes::read(Path::new(path))
                    .map_or(true, |content| content.input(&entry) != *expected);
            }
        }
        if std::fs::metadata(path).is_ok_and(|metadata| !metadata.is_file()) {
            return true;
        }
        match capture_program(Path::new(path)) {
            Ok((_, actual)) => actual.state != expected.state,
            Err(error) => definite_capture_error(&error),
        }
    })
}

fn definite_capture_error(error: &GateError) -> bool {
    matches!(
        error.code.as_str(),
        "program_invalid" | "input_too_large" | "path_invalid"
    )
}

fn resolve(spec: &ModuleSpec) -> Result<SpawnProgramBinding> {
    #[cfg(windows)]
    let resolved = {
        let capture = crate::supervise::windows_spawn_capture(spec)
            .map_err(|error| GateError::new("program_refused", error))?;
        let mut resolved = spec.clone();
        resolved.program = capture.path().to_path_buf();
        resolved
    };
    #[cfg(not(windows))]
    let resolved = spec.clone();
    SpawnProgramBinding::capture(&resolved)
        .map_err(|error| GateError::new("program_refused", error))
}

fn known_interpreter(path: &Path) -> bool {
    let name = path
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or_default();
    let name = name.strip_suffix(".exe").unwrap_or(name);
    matches!(name, "node" | "bun" | "deno" | "python" | "sh" | "bash")
        || name.strip_prefix("python").is_some_and(|version| {
            let mut parts = version.split('.');
            let number =
                |part: &str| !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit());
            parts.next().is_some_and(number)
                && parts.next().is_none_or(number)
                && parts.next().is_none()
        })
}

#[cfg(all(test, unix))]
thread_local! {
    static BEFORE_CAPTURE: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
}

#[cfg(all(test, unix))]
pub(super) fn before_capture_for_test(hook: impl FnOnce() + 'static) {
    BEFORE_CAPTURE.with(|slot| *slot.borrow_mut() = Some(Box::new(hook)));
}

#[cfg(all(test, unix))]
pub(crate) fn native_fixture_for_test() -> std::path::PathBuf {
    // Resolved from the Cargo profile directory, not from this test binary's
    // location: newer Cargo places test binaries under `build/<pkg>/<hash>/out/`,
    // away from the profile directory where `cargo build --bins` puts the fixture.
    let fixture = cortexkit_test_support::cargo_profile_bin("config-gate-fixture");
    assert!(
        fixture.is_file(),
        "config-gate-fixture not built; build subc-daemon's bins with test-support first"
    );
    fixture
}

pub(crate) fn capture(spec: &ModuleSpec, covered: &[String]) -> Result<ProgramLaunch> {
    let mut command = spec.clone();
    if let Some(script) = &spec.script {
        command.program = crate::supervise::script::runner_path(script.runtime)
            .map_err(|error| GateError::new("program_refused", error))?;
    }
    let spec = &command;
    let script = spec
        .script
        .as_ref()
        .map(|entry| crate::supervise::script::ScriptBytes::read(&entry.path))
        .transpose()?;
    let binding = resolve(spec)?;
    let mut launch = spec.clone();
    launch.program = std::path::absolute(&binding.path)
        .map_err(|error| GateError::new("program_refused", error))?;
    let mut paths = vec![launch.program.clone()];
    #[cfg(all(test, unix))]
    BEFORE_CAPTURE.with(|slot| {
        if let Some(hook) = slot.borrow_mut().take() {
            hook();
        }
    });
    let image = binding.identity;
    let launch_identity = image;
    paths.extend(covered.iter().map(Into::into));
    let mut inputs = BTreeMap::new();
    let mut files = Vec::new();
    let mut bindings = Vec::new();
    #[cfg(windows)]
    let mut windows_files = Vec::new();
    for path in paths {
        #[cfg(windows)]
        let no_delete = {
            use std::os::windows::fs::OpenOptionsExt;
            // FILE_SHARE_READ excludes both mutation and delete sharing on the
            // same file whose identity is compared with the hash descriptor.
            std::fs::OpenOptions::new()
                .read(true)
                .share_mode(1)
                .open(
                    std::fs::canonicalize(&path)
                        .map_err(|error| GateError::new("program_refused", error))?,
                )
                .map_err(|error| GateError::new("program_refused", error))?
        };
        let (file, captured, script) = capture_program_classified(&path)?;
        if path == launch.program && (script || known_interpreter(&path)) {
            return Err(GateError::new(
                "program_refused",
                "script modules are refused while the config gate is on because the interpreter re-reads the script by path after the check; ship the module as a compiled program",
            ));
        }
        let retained = subc_os::retained_file_identity(&file)
            .map_err(|error| GateError::new("program_refused", error))?;
        #[cfg(windows)]
        if retained
            != subc_os::retained_file_identity(&no_delete)
                .map_err(|error| GateError::new("program_refused", error))?
        {
            return Err(GateError::stale());
        }
        if path == launch.program
            && subc_os::retained_file_identity(&file).ok() != Some(launch_identity)
        {
            return Err(GateError::stale());
        }
        inputs.insert(
            InputKey::Program {
                module: spec.module_id.clone(),
                path: path.to_string_lossy().into_owned(),
            },
            captured,
        );
        bindings.push((path, retained));
        #[cfg(windows)]
        windows_files.push(no_delete);
        files.push(file);
    }
    if let (Some(entry), Some(script)) = (&spec.script, &script) {
        inputs.insert(
            InputKey::Program {
                module: spec.module_id.clone(),
                path: entry.path.to_string_lossy().into_owned(),
            },
            script.input(entry),
        );
    }
    Ok(ProgramLaunch {
        spec: launch,
        inputs,
        files,
        image,
        script,
        bindings,
        #[cfg(windows)]
        _windows_files: windows_files,
    })
}

#[cfg(all(test, windows))]
mod windows_tests {
    use super::*;

    #[test]
    fn config_admission_windows_retains_every_covered_file_without_delete_sharing() {
        let path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("../../target/scratch")
            .join(format!("admission-windows-files-{}", std::process::id()));
        std::fs::create_dir_all(&path).unwrap();
        let covered = path.join("module.cjs");
        std::fs::write(&covered, "approved code").unwrap();
        let spec = ModuleSpec {
            script: None,
            module_id: "native-binding".into(),
            program: std::path::PathBuf::from(std::env::var_os("SystemRoot").unwrap())
                .join("System32/cmd.exe"),
            args: vec!["/C".into(), "exit 0".into()],
            env: vec![],
            reserved: false,
            reserved_prefixes: vec![],
            protocol: subc_control::ModuleProtocol::None,
            overlap: Default::default(),
            carry_containment: false,
        };
        let launch = capture(&spec, &[covered.to_string_lossy().into_owned()]).unwrap();
        assert!(launch.check_files(false).is_ok());
        assert_eq!(
            std::fs::rename(&covered, path.join("replaced.cjs"))
                .unwrap_err()
                .raw_os_error(),
            Some(32)
        );
        drop(launch);
        std::fs::rename(covered, path.join("replaced.cjs")).unwrap();
        std::fs::remove_dir_all(path).unwrap();
    }
}