//! Translate canonical permissions into MXC path grants. //! Denies and read-only carveouts remain separate kernel policy lists. //! Missing deny parents are created and marked before deny globs and volume grants are expanded. //! Alias limitations are documented in the crate README. use std::collections::HashMap; use std::collections::HashSet; use std::path::Path; use std::path::PathBuf; use akode_protocol::permissions::FileSystemPolicyProjection; use akode_protocol::protocol::FileSystemAccessMode; use akode_protocol::protocol::FileSystemPath; use akode_protocol::protocol::FileSystemSandboxPolicy; use akode_protocol::protocol::FileSystemSpecialPath; use akode_utils_absolute_path::AbsolutePathBuf; use akode_utils_path_uri::PathUri; use akode_windows_sandbox::expand_windows_deny_read_paths; use akode_windows_sandbox::resolve_windows_deny_read_paths; use mxc_sdk::mxc_common::cmdline::CommandLineContext; use mxc_sdk::mxc_common::cmdline::CommandLineError; use mxc_sdk::mxc_common::cmdline::cmdline_from_argv_for_context; use mxc_sdk::mxc_common::models::BaseProcessUiConfig; use mxc_sdk::mxc_common::models::ContainerPolicy; use mxc_sdk::mxc_common::models::ExecutionRequest; use mxc_sdk::mxc_common::models::FallbackPolicy; use mxc_sdk::mxc_common::models::NetworkAction; use mxc_sdk::mxc_common::models::NetworkCidr; use mxc_sdk::mxc_common::models::NetworkEgressPolicy; use mxc_sdk::mxc_common::models::NetworkIngressPolicy; use mxc_sdk::mxc_common::models::NetworkPeer; use mxc_sdk::mxc_common::models::NetworkRule; use mxc_sdk::mxc_common::models::UiPolicy; use thiserror::Error; use crate::MxcCommand; // Use the same Windows case/URI identity as the canonical permission model, // while retaining native spellings for the OS API. type NativePaths = HashMap; /// Invalid inputs or unsupported permissions encountered during policy translation. #[derive(Debug, Error)] pub enum PolicyError { #[error("MXC command must not be empty")] EmptyCommand, #[error("MXC requires an absolute policy working directory")] RelativePolicyCwd, #[error("MXC requires an absolute command working directory")] RelativeCommandCwd, #[error("MXC policy contains an unresolved symbolic filesystem path")] UnsupportedSymbolicPath, #[error("MXC requires a Unicode command working directory")] NonUnicodeCommandCwd, #[error("MXC requires Unicode filesystem policy paths")] NonUnicodePolicyPath, #[error("{0}")] PolicyResolution(String), #[error("enumerate MXC volume {path}: {source}")] EnumerateVolume { path: PathBuf, #[source] source: std::io::Error, }, #[error(transparent)] Path(#[from] std::io::Error), #[error(transparent)] CommandLine(#[from] CommandLineError), } /// Bind MXC's temporary-directory symbols using the filtered command environment. pub(super) fn materialize_temporary_paths( mut policy: FileSystemSandboxPolicy, env: &[String], ) -> std::io::Result { // Resolve Windows temporary directories from the filtered command // environment, including case-insensitive names. let mut temp_values = HashMap::new(); for (key, value) in env.iter().filter_map(|entry| entry.split_once('=')) { if key.eq_ignore_ascii_case("TEMP") || key.eq_ignore_ascii_case("TMP") { temp_values.insert(key.to_ascii_uppercase(), value); } } let temp_paths = ["TEMP", "TMP"] .into_iter() .filter_map(|key| temp_values.get(key).copied()) .filter(|path| Path::new(path).is_absolute()) .map(AbsolutePathBuf::from_absolute_path) .collect::>>()?; policy.entries = policy .entries .into_iter() .flat_map(|entry| { match &entry.path { FileSystemPath::Special { value: FileSystemSpecialPath::Tmpdir, } => temp_paths .iter() .map(|path| { let mut entry = entry.clone(); entry.path = path.clone().into(); entry }) .collect(), // /tmp has no special meaning on the Windows executor. FileSystemPath::Special { value: FileSystemSpecialPath::SlashTmp, } => Vec::new(), _ => vec![entry], } }) .collect(); Ok(policy) } pub(super) fn build_request( command: &MxcCommand, command_cwd: &Path, env: Vec, volume_roots: &[PathBuf], platform_read_roots: &[PathBuf], ) -> Result { if command.command.is_empty() { return Err(PolicyError::EmptyCommand); } let permissions = &command.permissions; let cwd = &command.sandbox_policy_cwd; if !cwd.is_absolute() { return Err(PolicyError::RelativePolicyCwd); } if !command_cwd.is_absolute() { return Err(PolicyError::RelativeCommandCwd); } let policy = materialize_temporary_paths(permissions.file_system_sandbox_policy(), &env)?; #[cfg(windows)] for denied in policy.get_unreadable_roots_with_cwd(cwd) { let Some(parent) = denied.as_path().parent() else { continue; }; if parent.components().any(|component| { component .as_os_str() .to_string_lossy() .trim_end_matches(['.', ' ']) .eq_ignore_ascii_case(".chatgptcreated") }) { return Err(PolicyError::PolicyResolution(format!( "MXC deny path {} uses the reserved directory name .chatgptcreated", denied.display() ))); } let mut missing = parent .ancestors() .take_while(|path| matches!(path.try_exists(), Ok(false))) .collect::>(); missing.reverse(); for directory in missing { // Only mark directories this launcher actually created. match std::fs::create_dir(directory) { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists && directory.is_dir() => { continue; } Err(error) => { return Err(PolicyError::PolicyResolution(format!( "MXC currently requires deny paths to have existing parent directories. Could not create {}: {error}. Create this directory manually or correct the path/permissions, then retry.", directory.display() ))); } } let sentinel = directory.join(".chatgptcreated"); std::fs::File::create_new(&sentinel).map_err(|error| { // Leave a failed preparation retryable when the directory is still empty. let _ = std::fs::remove_dir(directory); PolicyError::PolicyResolution(format!( "cannot create MXC directory sentinel {}: {error}", sentinel.display() )) })?; } } let full_disk_write = policy.has_full_disk_write_access(); let volumes = volume_roots .iter() .map(PathUri::from_host_native_path) .collect::>>()?; #[cfg(windows)] let read_volumes = crate::windows::implicit_read_roots(volume_roots, cwd, command_cwd)?; #[cfg(not(windows))] let read_volumes = volumes.clone(); let fs = materialize_volume_roots(policy.clone(), &volumes, &read_volumes)?; let absolute_cwd = AbsolutePathBuf::from_absolute_path(cwd) .map_err(|error| PolicyError::PolicyResolution(error.to_string()))?; let (roots, readable_roots, denied_paths) = if fs == policy { let resolved = fs.resolve_for_enforcement(cwd, FileSystemPolicyProjection::PreserveMutableRoots)?; let denies = expand_windows_deny_read_paths(&resolved, &absolute_cwd); (resolved.writable_roots, resolved.readable_roots, denies) } else { // A symbolic root deny sets the default on every volume. Expanding it into ACL // targets would mask narrower grants and probe disconnected drives. let roots = if full_disk_write { Vec::new() } else { fs.get_writable_roots_with_cwd_preserving_mutable_paths(cwd) }; ( roots, fs.get_readable_roots_with_cwd(cwd), resolve_windows_deny_read_paths(&policy, &absolute_cwd), ) }; let mut write = collect_paths(roots.iter().map(|root| root.root.to_path_buf()))?; if full_disk_write { write.extend(collect_paths(volume_roots.iter().cloned())?); // Explicit grants may name unmapped shares outside the enumerated volumes. for entry in &policy.entries { if entry.access.can_write() && let FileSystemPath::Path { path } = &entry.path { write.insert(path.clone(), path.to_abs_path()?.into_path_buf()); } } } let mut read = collect_paths( readable_roots .into_iter() .filter(|path| !fs.can_write_local_path_with_cwd(path.as_path(), cwd)) .map(|path| path.to_path_buf()), )?; let deny = collect_paths( denied_paths .map_err(PolicyError::PolicyResolution)? .into_iter() .map(AbsolutePathBuf::into_path_buf), )?; let carveouts = collect_paths(roots.into_iter().flat_map(|root| { let protected = root .protected_metadata_names .into_iter() .map(|name| root.root.join(name).to_path_buf()); root.read_only_subpaths .into_iter() .map(|path| path.to_path_buf()) .chain(protected) .collect::>() }))?; // Write restrictions must not grant otherwise forbidden reads. read.extend( carveouts .iter() .filter(|(_, path)| fs.can_read_local_path_with_cwd(path.as_path(), cwd)) .map(|(key, path)| (key.clone(), path.clone())), ); if policy.include_platform_defaults() { read.extend(collect_paths(platform_read_roots.iter().cloned())?); } write.retain(|key, _| !carveouts.contains_key(key) && !deny.contains_key(key)); read.retain(|key, _| !write.contains_key(key) && !deny.contains_key(key)); let volume_roots = volume_roots .iter() .map(PathUri::from_host_native_path) .collect::>>()?; prune_unavailable_volume_roots(&mut write, &volume_roots); prune_unavailable_volume_roots(&mut read, &volume_roots); // BaseContainer owns alias precedence for the emitted paths. Do not call // MXC's object normalizer: its metadata preflight rejects usable SMB grants // and inaccessible deny paths before the native API can evaluate them. // The hard-link and volume-root alias tradeoffs are intentional; see README. // Read-only roots already grant recursive access; only expand writable roots. let mut write = expand_volume_roots(write, &volume_roots)?; write.retain(|key, _| !carveouts.contains_key(key) && !deny.contains_key(key)); // Resolve equal-path write overrides before reaching MXC so the native // API receives one effective access mode for each path identity. read.retain(|key, _| !write.contains_key(key) && !deny.contains_key(key)); let network_enabled = permissions.network_sandbox_policy().is_enabled(); let proxied = command.managed_network.is_some(); if let Some(network) = &command.managed_network { crate::validate_managed_network(network) .map_err(|error| PolicyError::PolicyResolution(error.to_string()))?; } let egress_default = if network_enabled && !proxied { NetworkAction::Allow } else { NetworkAction::Deny }; let ingress_default = if network_enabled && !proxied { NetworkAction::Allow } else { NetworkAction::Deny }; let mut egress = NetworkEgressPolicy { default: egress_default, ..Default::default() }; if proxied { // PSEC host loopback can be bidirectional. This shape is supported only // when the caller already allows local clients and servers. Keep // private-network ingress denied and allow no direct DNS bypass. egress.allow.push(NetworkRule { to: vec![ NetworkPeer { cidr: NetworkCidr { address: std::net::Ipv4Addr::new(127, 0, 0, 0).into(), prefix_length: 8, }, except: Vec::new(), }, NetworkPeer { cidr: NetworkCidr { address: std::net::Ipv6Addr::LOCALHOST.into(), prefix_length: 128, }, except: Vec::new(), }, ], ports: Vec::new(), }); } Ok(ExecutionRequest { script_code: cmdline_from_argv_for_context( &command.command, CommandLineContext::WindowsCreateProcess, )?, working_directory: command_cwd .to_str() .ok_or(PolicyError::NonUnicodeCommandCwd)? .to_owned(), env: (!env.is_empty()).then_some(env), policy: ContainerPolicy { capabilities: vec!["registryRead".to_owned()], readwrite_paths: unicode_paths(write)?, readonly_paths: unicode_paths(read)?, denied_paths: unicode_paths(deny)?, fallback: FallbackPolicy { allow_dacl_mutation: false, }, network_egress: Some(egress), network_ingress: Some(NetworkIngressPolicy { default: ingress_default, host_loopback: if network_enabled || proxied { NetworkAction::Allow } else { NetworkAction::Deny }, }), network_specified: true, network_mode_specified: true, // PowerShell needs Win32k and desktop handles during DLL startup. // Keep clipboard, input injection, and system-control restrictions. ui: UiPolicy { disable: false, ..Default::default() }, base_process_ui: BaseProcessUiConfig { isolation: "desktop".to_owned(), ..Default::default() }, ..Default::default() }, ..Default::default() }) } fn prune_unavailable_volume_roots(paths: &mut NativePaths, volume_roots: &HashSet) { paths.retain(|key, path| { if !volume_roots.contains(key) && path.parent().is_some() { return true; } match std::fs::read_dir(path) { Ok(_) => true, Err(error) => !inaccessible_volume(&error), } }); } // Bind :root before canonical precedence and carveout resolution. Only implicit // reads use the filtered volumes; writes and denies retain every executor volume. pub(super) fn materialize_volume_roots( mut fs: FileSystemSandboxPolicy, volume_roots: &[PathUri], implicit_read_roots: &[PathUri], ) -> Result { let mut entries = Vec::new(); for entry in fs.entries { match &entry.path { FileSystemPath::Special { value: FileSystemSpecialPath::Root, } => { let roots = if entry.access == FileSystemAccessMode::Read { implicit_read_roots } else { volume_roots }; entries.extend(roots.iter().map(|path| { let mut entry = entry.clone(); entry.path = path.clone().into(); entry })); } FileSystemPath::Special { value: FileSystemSpecialPath::ProjectRoots { .. } | FileSystemSpecialPath::Tmpdir | FileSystemSpecialPath::SlashTmp, } => return Err(PolicyError::UnsupportedSymbolicPath), FileSystemPath::Path { .. } | FileSystemPath::GlobPattern { .. } | FileSystemPath::Special { value: FileSystemSpecialPath::Minimal | FileSystemSpecialPath::Unknown { .. }, } => entries.push(entry), } } fs.entries = entries; Ok(fs) } // MXC writable volume-root grants are nonrecursive, so snapshot each root's current // immediate children as recursive grants. A child created directly under the // root after policy construction is not granted. MXC/PSEC still enforces // restrictions on junction-resolved targets at access time. fn expand_volume_roots( paths: NativePaths, volume_roots: &HashSet, ) -> Result { let mut expanded = NativePaths::new(); for (key, path) in paths { if volume_roots.contains(&key) || path.parent().is_none() { match std::fs::read_dir(&path).and_then(Iterator::collect::>>) { Ok(entries) => { for entry in entries { let child = entry.path(); if child.to_str().is_none() { continue; } // Windows supplies the file type with directory entries. // Only resolve links: broken targets prevent PSEC startup. if entry.file_type().is_ok_and(|kind| kind.is_symlink()) && std::fs::metadata(&child).is_err() { continue; } expanded.insert(PathUri::from_host_native_path(&child)?, child); } } // GetLogicalDrives includes disconnected and empty removable // drives. They must not prevent commands on available volumes. Err(error) if inaccessible_volume(&error) => continue, Err(error) => { return Err(PolicyError::EnumerateVolume { path, source: error, }); } } } expanded.insert(key, path); } Ok(expanded) } fn collect_paths(paths: impl IntoIterator) -> Result { paths .into_iter() .map(|path| Ok((PathUri::from_host_native_path(&path)?, path))) .collect() } fn inaccessible_volume(error: &std::io::Error) -> bool { if matches!( error.kind(), std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::NotFound | std::io::ErrorKind::NetworkUnreachable | std::io::ErrorKind::HostUnreachable ) { return true; } #[cfg(windows)] { use windows_sys::Win32::Foundation::ERROR_BAD_NETPATH; use windows_sys::Win32::Foundation::ERROR_CONNECTION_UNAVAIL; use windows_sys::Win32::Foundation::ERROR_DEVICE_NOT_CONNECTED; use windows_sys::Win32::Foundation::ERROR_NOT_READY; matches!( error.raw_os_error().map(|code| code as u32), Some(ERROR_NOT_READY | ERROR_DEVICE_NOT_CONNECTED | ERROR_BAD_NETPATH) ) || error.raw_os_error() == Some(ERROR_CONNECTION_UNAVAIL as i32) } #[cfg(not(windows))] { false } } fn unicode_paths(paths: NativePaths) -> Result, PolicyError> { let mut paths = paths .into_values() .map(|path| { path.into_os_string() .into_string() .map_err(|_| PolicyError::NonUnicodePolicyPath) }) .collect::, _>>()?; paths.sort(); Ok(paths) }