subc-os 0.1.59

Operating-system primitives for the subc daemon that need unsafe code, behind a safe API: per-process identity, signalling, memory and CPU usage, and the launch-nonce descriptor handoff.
Documentation
use super::*;
use crate::local_peer::fixture::SignedAppFixture;
use crate::local_peer::CodeRequirementOutcome;
use cortexkit_test_support::ScratchDir;
use std::{fs, os::unix::fs::symlink, process::Command};

const ID: &str = "dev.cortexkit.alfonso";
const REQUIREMENT: &str = "identifier \"dev.cortexkit.alfonso\"";
const RESOURCE: &str = "Contents/Resources/index.html";

#[test]
fn bundle_static_validation_binds_resources_to_the_running_process() {
    let root = ScratchDir::new("sealed-app");
    let fixture = SignedAppFixture::new(&root, ID, Some("1.2.3"), true, None);
    let sealed = check_dev_app_bundle(fixture.bundle(), ID).unwrap();
    assert_eq!(sealed.short_version.as_deref(), Some("1.2.3"));
    assert_eq!(sealed.build_time.as_deref(), Some("2026-11-29T12:00:00Z"));
    assert_eq!(
        check_dev_app_bundle(fixture.bundle(), "other.id"),
        Err(WrongIdentifier)
    );
    let mut process = fixture.launch();
    let (_socket, peer) = process.connect();
    assert_eq!(peer.check_dev_app(ID), Some(Ok(sealed.clone())));
    assert_eq!(peer.check_sealed_app(REQUIREMENT), Ok(sealed));
    fs::write(fixture.bundle().join(RESOURCE), "changed resource").unwrap();
    assert!(
        matches!(
            peer.check_code_requirement(REQUIREMENT),
            CodeRequirementOutcome::Satisfied(_)
        ),
        "SecCodeCheckValidity alone does not verify bundle resources"
    );
    assert_eq!(
        check_dev_app_bundle(fixture.bundle(), ID),
        Err(InvalidBundleSeal)
    );
    assert_eq!(peer.check_dev_app(ID), Some(Err(InvalidBundleSeal)));
    assert_eq!(peer.check_sealed_app(REQUIREMENT), Err(InvalidBundleSeal));
    drop(process);
    assert!(peer.check_sealed_app(REQUIREMENT).is_err());
}

fn run(command: &mut Command) {
    let out = crate::child_spawn::output(command).unwrap();
    assert!(
        out.status.success(),
        "{command:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn framework_library(root: &Path, path: &Path, marker: u8, universal: bool) {
    let source = root.join("framework.c");
    fs::write(&source, format!("int fixture(void) {{ return {marker}; }}")).unwrap();
    let mut cc = Command::new("cc");
    if universal {
        cc.args(["-arch", "arm64", "-arch", "x86_64"]);
    }
    run(cc.arg("-dynamiclib").arg(source).arg("-o").arg(path));
}

fn framework_version(root: &Path, framework: &Path, version: &str, marker: u8, universal: bool) {
    let contents = framework.join("Versions").join(version);
    fs::create_dir_all(contents.join("Resources")).unwrap();
    framework_library(root, &contents.join("Sealed"), marker, universal);
    fs::write(contents.join("Resources/Info.plist"), "<?xml version=\"1.0\"?><plist version=\"1.0\"><dict><key>CFBundleIdentifier</key><string>net.example.sealed-framework</string><key>CFBundleExecutable</key><string>Sealed</string><key>CFBundlePackageType</key><string>FMWK</string></dict></plist>").unwrap();
}

fn sign_framework(framework: &Path, version: &str) {
    // The fixture has a stable designated requirement across its two builds,
    // just as a real signing certificate can identify more than one build.
    run(Command::new("/usr/bin/codesign")
        .args([
            "--force",
            "--sign",
            "-",
            "--timestamp=none",
            "--bundle-version",
            version,
            "-r",
            "=designated => identifier \"net.example.sealed-framework\"",
        ])
        .arg(framework));
}

fn framework_fixture(
    root: &Path,
    universal: bool,
    extra_version: bool,
) -> (SignedAppFixture, PathBuf) {
    let fixture = SignedAppFixture::new(root, ID, Some("1.0.0"), true, None);
    let framework = fixture
        .bundle()
        .join("Contents/Frameworks/Sealed.framework");
    framework_version(root, &framework, "A", 1, universal);
    symlink("A", framework.join("Versions/Current")).unwrap();
    symlink("Versions/Current/Sealed", framework.join("Sealed")).unwrap();
    symlink("Versions/Current/Resources", framework.join("Resources")).unwrap();
    sign_framework(&framework, "A");
    if extra_version {
        framework_version(root, &framework, "B", 2, false);
        sign_framework(&framework, "B");
    }
    run(Command::new("/usr/bin/codesign")
        .args([
            "--force",
            "--sign",
            "-",
            "--timestamp=none",
            "--options",
            "runtime",
            "--identifier",
            ID,
        ])
        .arg(fixture.bundle()));
    (fixture, framework)
}

#[test]
fn bundle_nested_code_is_pinned_beyond_designated_requirement() {
    let root = ScratchDir::new("pinned-framework");
    let (fixture, framework) = framework_fixture(&root, false, false);
    check_dev_app_bundle(fixture.bundle(), ID).unwrap();
    framework_library(&root, &framework.join("Versions/A/Sealed"), 2, false);
    sign_framework(&framework, "A");
    run(Command::new("/usr/bin/codesign")
        .args(["--verify", "--strict", "--deep"])
        .arg(fixture.bundle()));
    assert_eq!(
        check_dev_app_bundle(fixture.bundle(), ID),
        Err(InvalidNestedSeal)
    );
    let mut process = fixture.launch();
    let (_socket, peer) = process.connect();
    assert_eq!(peer.check_sealed_app(REQUIREMENT), Err(InvalidNestedSeal));
}

#[test]
fn bundle_refuses_unpinned_nested_architectures_and_framework_versions() {
    for (universal, multi_version, kind) in [
        (true, false, "architectures"),
        (false, true, "version directories"),
    ] {
        let root = ScratchDir::new("unpinned-framework");
        let (fixture, _) = framework_fixture(&root, universal, multi_version);
        let expected = Err(UnpinnedNestedLayout {
            item: "Frameworks/Sealed.framework".into(),
            count: 2,
            kind,
        });
        assert_eq!(check_dev_app_bundle(fixture.bundle(), ID), expected);
        let mut process = fixture.launch();
        let (_socket, peer) = process.connect();
        assert_eq!(peer.check_sealed_app(REQUIREMENT), expected);
    }
}

#[test]
#[ignore = "measurement fixture; run explicitly with --ignored --nocapture"]
fn measure_large_dev_app_validation() {
    let root = ScratchDir::new("large-sealed-app");
    let (fixture, _) = framework_fixture(&root, false, false);
    const FILES: usize = 4096;
    const BYTES: usize = 16 * 1024;
    let mut payload = [b'x'; BYTES];
    for index in 0..FILES {
        let directory = fixture
            .bundle()
            .join(format!("Contents/Resources/{:02}", index / 256));
        fs::create_dir_all(&directory).unwrap();
        payload[..usize::BITS as usize / 8].copy_from_slice(&index.to_le_bytes());
        fs::write(directory.join(format!("asset-{index}.bin")), payload).unwrap();
    }
    run(Command::new("/usr/bin/codesign")
        .args([
            "--force",
            "--sign",
            "-",
            "--timestamp=none",
            "--options",
            "runtime",
            "--identifier",
            ID,
        ])
        .arg(fixture.bundle()));
    let mut process = fixture.launch();
    let (_socket, peer) = process.connect();
    let measurements: Vec<_> = (0..5)
        .map(|_| {
            let start = std::time::Instant::now();
            assert!(matches!(peer.check_dev_app(ID), Some(Ok(_))));
            start.elapsed().as_millis()
        })
        .collect();
    println!("check_dev_app: {FILES} resources, {} MiB, one nested framework; milliseconds: {measurements:?}", FILES * BYTES / (1024 * 1024));
}