merry-process 0.1.3

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
use super::*;
use merry_core::{PendingToolCall, ToolCallArguments, ToolCallId, ToolName};
use merry_runtime::{PathAccess, PathAccessRule, PathAccessRuleSource, parse_permission_request};

fn path_request(path: &std::path::Path, access: &str) -> PermissionRequest {
    let call = PendingToolCall::new(
        ToolCallId::new("call-unrestricted-protected").expect("call id"),
        ToolName::new("request_permissions").expect("tool name"),
        ToolCallArguments::try_from(serde_json::json!({
            "requested": {
                "paths": [{ "path": path.display().to_string(), "access": access }]
            },
            "for_action": { "command": "cat file", "cwd": null }
        }))
        .expect("args"),
    );
    parse_permission_request(&call).expect("parse request")
}

#[test]
fn unrestricted_backend_keeps_product_private_paths_protected_while_leaving_config_open() {
    let temp = tempfile::tempdir().expect("tempdir");
    let workspace = temp.path().join("workspace");
    let data_merry = temp.path().join("data/merry");
    let providers = data_merry.join("providers");
    let config_dir = temp.path().join("config/merry");
    let external = temp.path().join("external");
    std::fs::create_dir_all(&workspace).expect("workspace");
    std::fs::create_dir_all(&providers).expect("providers");
    std::fs::create_dir_all(&config_dir).expect("config");
    std::fs::create_dir_all(&external).expect("external");

    let options = ProcessBackendOptions::new().extend_path_rules([
        PathAccessRule::new(
            &providers,
            PathAccess::Deny,
            PathAccessRuleSource::ProductPrivate,
        ),
        PathAccessRule::new(
            &config_dir,
            PathAccess::ReadOnly,
            PathAccessRuleSource::ProductReadOnly,
        ),
    ]);
    let backend =
        LocalProcessBackend::unrestricted(&workspace, options).expect("unrestricted backend");
    let factory = backend.new_session().permissioned_factory();

    assert!(
        factory.targets_protected_metadata(&path_request(&providers.join("providers.toml"), "ro")),
        "providers/ must stay protected under --sandbox off"
    );
    assert!(
        factory.targets_protected_metadata(&path_request(&data_merry, "ro")),
        "ancestor covering providers/ must stay protected under --sandbox off"
    );
    assert!(
        !factory.targets_protected_metadata(&path_request(&config_dir.join("config.toml"), "rw")),
        "config.toml writes stay unlocked under --sandbox off"
    );
    assert!(
        !factory.targets_protected_metadata(&path_request(&external.join("notes.txt"), "rw")),
        "ordinary external paths are not protected metadata"
    );
}

#[test]
fn live_backend_tracks_read_only_workspace_isolates_host_children_and_supports_atomic_surgical_replace()
 {
    let temp = tempfile::tempdir().expect("tempdir");
    let workspace = temp.path().join("workspace");
    let external = temp.path().join("external");
    std::fs::create_dir_all(&workspace).expect("workspace");
    std::fs::create_dir_all(&external).expect("external");

    #[cfg(all(feature = "sandbox", any(target_os = "linux", target_os = "macos")))]
    if crate::probe_workspace_sandbox().is_ok() {
        let ro_sandbox = LiveProcessBackend::new(
            &workspace,
            ProcessBackendMode::Isolated,
            ProcessBackendOptions::new().read_only_workspace(),
        )
        .expect("live sandboxed ro backend");
        let ro_session = ro_sandbox.new_session();
        let ro_handle = ro_session.live_policy_handle(&workspace, true);
        assert!(
            !ro_handle.workspace_writable(),
            "read_only_workspace() must be reflected in Sandboxed LivePolicyHandle baseline"
        );
        {
            let _uncommitted = ro_sandbox
                .prepare_replace(
                    &workspace,
                    ProcessBackendMode::Isolated,
                    ProcessBackendOptions::new(),
                    SessionGrantClearPolicy::ClearAll,
                )
                .expect("prepare rw replace");
        }
        assert!(
            !ro_handle.workspace_writable(),
            "dropped PreparedLiveReplace must not mutate Sandboxed live policy"
        );
    }

    let backend = LiveProcessBackend::new(
        &workspace,
        ProcessBackendMode::Host,
        ProcessBackendOptions::new(),
    )
    .expect("live host backend");
    let parent_session = backend.new_session();
    let live_handle = parent_session.live_policy_handle(&workspace, true);
    let child_session = backend
        .new_session_with(ProcessSessionRequest::new().with_workspace_root(&workspace))
        .expect("child session");
    let parent_perms = parent_session
        .session_permissions()
        .expect("parent session permissions");
    let child_perms = child_session
        .session_permissions()
        .expect("child session permissions");
    parent_perms
        .retain_path_grants(vec![merry_runtime::ProcessPathGrant::new(
            PathAccessRule::new(
                &external,
                PathAccess::ReadOnly,
                PathAccessRuleSource::PermissionReview,
            ),
            merry_runtime::ProcessPathGrantConstraint::Ordinary,
        )])
        .expect("retain parent path grant");
    let ssh_req = parse_permission_request(&PendingToolCall::new(
        ToolCallId::new("call-ssh-session").expect("call id"),
        ToolName::new("request_permissions").expect("tool name"),
        ToolCallArguments::try_from(serde_json::json!({
            "requested": { "host_integrations": ["ssh-agent"] },
            "for_action": { "command": "ssh-add -l", "cwd": null }
        }))
        .expect("args"),
    ))
    .expect("ssh request");
    struct AcceptAllFactory(Arc<dyn merry_runtime::ProcessRunner>);
    impl PermissionedProcessRunnerFactory for AcceptAllFactory {
        fn runner_for(
            &self,
            _request: &PermissionRequest,
        ) -> Arc<dyn merry_runtime::ProcessRunner> {
            Arc::clone(&self.0)
        }
    }
    let _ = parent_perms
        .clone()
        .with_factory(AcceptAllFactory(parent_session.runner()))
        .runner_for_decision(&ssh_req, merry_runtime::ApprovalScope::Session);
    parent_perms
        .retain_domain_grants(["docs.rs".to_owned()])
        .expect("retain parent domain grant");
    let child_snap = child_perms.view().snapshot().expect("child snapshot");
    assert!(
        child_snap.path_rules().is_empty()
            && child_snap.allowed_domains().is_empty()
            && child_snap.host_integrations().is_empty(),
        "Host mode non-worktree child must not share parent's ProcessSessionPermissions"
    );

    {
        let _uncommitted = backend
            .prepare_replace(
                &workspace,
                ProcessBackendMode::Host,
                ProcessBackendOptions::new()
                    .with_network_policy(merry_runtime::CapabilityPolicy::Deny),
                SessionGrantClearPolicy::ClearAll,
            )
            .expect("prepare replace");
    }
    assert_ne!(
        live_handle.evaluate_network_host("example.com", &[]),
        merry_runtime::NetworkAccessDecision::Deny,
        "dropped PreparedLiveReplace must not mutate live network policy"
    );
    assert_eq!(
        parent_perms.grants().expect("parent grants").len(),
        3,
        "dropped PreparedLiveReplace must not clear session grants"
    );

    let prepared = backend
        .prepare_replace(
            &workspace,
            ProcessBackendMode::Host,
            ProcessBackendOptions::new()
                .with_denied_host_integrations([merry_runtime::HostIntegration::SshAgent]),
            SessionGrantClearPolicy::RevokeDenied {
                network_denied: false,
                denied_host_integrations: vec![merry_runtime::HostIntegration::SshAgent],
            },
        )
        .expect("prepare surgical replace");
    prepared.commit().expect("commit surgical replace");
    let remaining = parent_perms.view().snapshot().expect("remaining snapshot");
    assert!(
        remaining.host_integrations().is_empty(),
        "newly denied ssh_agent grant must be revoked"
    );
    assert_eq!(
        remaining.path_rules().len(),
        1,
        "unrelated external path grant must survive capability toggle"
    );
    assert_eq!(
        remaining.allowed_domains(),
        ["docs.rs"],
        "unrelated domain grant must survive ssh_agent toggle"
    );
}