Base: codex-main originale (prima del fork aKode)
This commit is contained in:
6
codex-rs/mxc-sandbox/BUILD.bazel
Normal file
6
codex-rs/mxc-sandbox/BUILD.bazel
Normal file
@@ -0,0 +1,6 @@
|
||||
load("//:defs.bzl", "codex_rust_crate")
|
||||
|
||||
codex_rust_crate(
|
||||
name = "mxc-sandbox",
|
||||
crate_name = "codex_mxc_sandbox",
|
||||
)
|
||||
44
codex-rs/mxc-sandbox/Cargo.toml
Normal file
44
codex-rs/mxc-sandbox/Cargo.toml
Normal file
@@ -0,0 +1,44 @@
|
||||
[package]
|
||||
name = "codex-mxc-sandbox"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[lib]
|
||||
doctest = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
# This direct dependency pins MXC's transitive ETW dependency for Windows GNU linking.
|
||||
[package.metadata.cargo-shear]
|
||||
ignored = ["tracelogging"]
|
||||
|
||||
[dependencies]
|
||||
anyhow = { workspace = true }
|
||||
codex-network-proxy = { workspace = true }
|
||||
codex-protocol = { workspace = true }
|
||||
codex-utils-absolute-path = { workspace = true }
|
||||
codex-utils-path-uri = { workspace = true }
|
||||
codex-windows-sandbox = { workspace = true }
|
||||
mxc-sdk = { workspace = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
flatbuffers = { workspace = true }
|
||||
# 1.2.4 imports OneCore_apiset, which the GNU Windows toolchain does not ship.
|
||||
tracelogging = "=1.2.3"
|
||||
windows-sys = { workspace = true, features = [
|
||||
"Win32_Foundation",
|
||||
"Win32_Storage_FileSystem",
|
||||
"Win32_System_Com",
|
||||
"Win32_System_SystemInformation",
|
||||
"Win32_System_WindowsProgramming",
|
||||
"Win32_UI_Shell",
|
||||
] }
|
||||
|
||||
[dev-dependencies]
|
||||
pretty_assertions = { workspace = true }
|
||||
tempfile = { workspace = true }
|
||||
124
codex-rs/mxc-sandbox/README.md
Normal file
124
codex-rs/mxc-sandbox/README.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# Native Windows MXC sandbox
|
||||
|
||||
This crate routes a command through the current Codex executable and directly
|
||||
into Microsoft's MXC `BaseContainerRunner`. It requires a working Windows
|
||||
process security environment (PSEC). It never invokes MXC's AppContainer
|
||||
dispatcher, edits host ACLs, creates sandbox users, runs setup, or requests
|
||||
elevation. The existing Codex Windows sandboxes remain separate backends.
|
||||
|
||||
Windows executors record `codex.windows_mxc.available` once per process with an
|
||||
`available=true|false` tag. This measures runtime availability independently of
|
||||
selection. Unsupported Windows executors reject MXC requests before execution.
|
||||
|
||||
`is_available()` uses MXC's cached create/close probe, rather than an OS build
|
||||
number or the SDK's broad `platform_support()` result. The latter also reports
|
||||
older AppContainer backends as supported. A requested deny path additionally
|
||||
requires the native `PSE_SUPPORT_FS_DENY` capability; otherwise the command
|
||||
fails before launch.
|
||||
|
||||
The wrapper inherits the command's pipes or ConPTY console. MXC creates its
|
||||
child suspended, assigns a kill-on-close job before resuming it, and retains
|
||||
the native policy through workload completion. Filesystem permissions come
|
||||
from the canonical Codex permission profile, including protected metadata
|
||||
carveouts. Supported managed network access allows IPv4 and IPv6 loopback
|
||||
clients and servers, including the dedicated proxy listeners, while denying
|
||||
direct non-loopback egress and general inbound network access.
|
||||
Win32k calls and desktop handles remain available for PowerShell startup;
|
||||
clipboard, input-injection, and desktop/system-control restrictions remain.
|
||||
|
||||
Filesystem conflicts in the emitted policy are enforced by BaseContainer:
|
||||
equivalent path spellings and symlink/junction aliases use the strictest access
|
||||
(`deny` > read-only > read-write), while more-specific paths override ancestor
|
||||
grants. See the [BaseContainer path-precedence rules](https://github.com/microsoft/mxc/blob/main/docs/schema.md#overlapping-paths-for-windows-basecontainer).
|
||||
|
||||
Do not call MXC's shared `normalize_object_conflicts` before or after volume
|
||||
expansion. Its identity preflight is used by mount-based backends and can reject
|
||||
an otherwise usable Windows policy when a network share does not support
|
||||
`FileIdInfo`, or a protected deny path cannot be opened for metadata. Codex sends
|
||||
explicit path grants to BaseContainer without requiring that additional lookup.
|
||||
We intentionally accept two limitations:
|
||||
|
||||
- Hard-link names retain independent path permissions. An allowed name can read
|
||||
or modify the same file as a denied or read-only name; we do not tighten all
|
||||
names to an object-wide restriction.
|
||||
- Volume-root expansion uses each root's declared access without reconciling
|
||||
aliases first. For example, a writable `V:\` plus a read-only junction to
|
||||
`V:\` can produce a writable `V:\projects` grant. That generated, more-specific
|
||||
grant permits writes through either name despite the read-only root alias.
|
||||
|
||||
## Selection and rollout
|
||||
|
||||
`windows.sandbox = "mxc"` is strict. The default-off `features.prefer_mxc`
|
||||
selects MXC for local execution when available unless local binding is explicitly
|
||||
forbidden; otherwise legacy configuration and setup apply. Remote executors keep
|
||||
their configured backend. Command failures never trigger backend fallback.
|
||||
Desktop can supply `-c features.prefer_mxc=true` from its saved rollout decision
|
||||
on the next local Windows launch. Gate changes require a subsequent launch, and
|
||||
rollback may require legacy setup. `config/read` retains the configured sandbox;
|
||||
`windowsSandbox/readiness` reflects the effective local selection.
|
||||
|
||||
## Launch contract
|
||||
|
||||
`create_command_args()` wraps the command like the Seatbelt backend, using the
|
||||
executor's Codex executable as the native SDK helper. It carries one typed
|
||||
request: the canonical `PermissionProfile`, policy cwd, proxy context, and exact
|
||||
argv. The helper inherits command cwd, environment, and stdio from the shared
|
||||
process path; policy cwd can differ from command cwd.
|
||||
|
||||
Windows MXC reserves `SystemDrive` and `LOCALAPPDATA` for the host's validated,
|
||||
nonempty values in both wrapper and explicit child environments. Caller
|
||||
overrides are replaced case-insensitively; unavailable host values fail before
|
||||
launch with a diagnostic naming the variable.
|
||||
Windows may virtualize the child's `LOCALAPPDATA` into a sandbox directory
|
||||
beneath the host profile.
|
||||
|
||||
The request uses launcher-only environment chunks to leave Windows' command-line
|
||||
budget to the workload. Payloads are limited to 1,000,000 UTF-8 bytes and chunks
|
||||
to 4096 bytes; the helper removes them before native process creation. Use
|
||||
`codex sandbox windows` to debug through the same preparation path as execution.
|
||||
|
||||
## Limits and Windows validation
|
||||
|
||||
- Deny globs use the existing Windows sandbox resolver to expand matching files
|
||||
and directories into concrete paths before launch. This has the same snapshot
|
||||
semantics and scan limits as the existing Windows sandbox.
|
||||
- Native deny paths depend on the host's capability probe. An installed Windows
|
||||
update alone is not treated as evidence that every policy feature is enabled.
|
||||
- When MXC is the executor's selected backend, managed networking defaults
|
||||
`allow_local_binding` to `true`. An effective `false` after applying managed
|
||||
requirements is a configuration error: native host-loopback access
|
||||
is bidirectional, and MXC's proxy-peer identity mode is not integrated here.
|
||||
`true` permits local servers and direct host-loopback connections and removes
|
||||
the proxy's additional private-network destination checks. Proxy domain rules
|
||||
still apply to proxied traffic; direct DNS remains denied. This default also
|
||||
applies to remote Windows executors and does not enable disabled networking.
|
||||
- Read-only volume-root grants recurse without enumerating children. Writable
|
||||
volume-root grants do not recurse, so the adapter grants the root and its
|
||||
immediate children; new children added during a running command are not
|
||||
implicitly writable.
|
||||
- Default read access excludes network shares unrelated to the policy or command
|
||||
cwd. Explicit read/write grants remain supported. Unrelated shares are not
|
||||
probed for object identity or enumerated for implicit reads.
|
||||
- The native API represents paths and environment values as Unicode strings.
|
||||
Non-Unicode values fail instead of undergoing lossy conversion.
|
||||
- An empty child environment still uses the Windows user-profile defaults.
|
||||
Supplying only two keys would turn it into an incomplete explicit environment,
|
||||
so the wrapper's bootstrap values are removed before the SDK selects defaults.
|
||||
Nonempty environments remain explicit except for these two host-owned values.
|
||||
- The upstream runner terminates remaining descendants when the foreground
|
||||
process exits, as well as on cancellation. Both existing Windows backends
|
||||
preserve descendants after normal exit, so detached servers currently lose
|
||||
that behavior under MXC. Retaining descendants safely requires a longer-lived
|
||||
owner for the native policy and job.
|
||||
- The command itself remains subject to Windows' command-line length limit.
|
||||
- Portable tests validate policy translation and wrapper arguments. Actual
|
||||
enforcement, nested access overrides, alternate path encodings, junctions
|
||||
and hardlinks, protected metadata, ConPTY behavior, process-tree cancellation,
|
||||
proxy isolation, and
|
||||
comparison with the existing Windows and Unix sandboxes require the smoke
|
||||
suite on supported Windows and the corresponding platform hosts.
|
||||
Test the normal `powershell.exe` and `pwsh.exe` command paths, not only `cmd.exe`.
|
||||
|
||||
The MXC git revision is pinned with the workspace dependencies. Native launch
|
||||
errors are returned without dumping the SDK's diagnostic buffer, which may
|
||||
contain command or environment data.
|
||||
55
codex-rs/mxc-sandbox/src/availability.rs
Normal file
55
codex-rs/mxc-sandbox/src/availability.rs
Normal file
@@ -0,0 +1,55 @@
|
||||
//! Probe PSEC creation and startup attributes without launching a process.
|
||||
//! Cache the result so automatic MXC selection requires a usable native API.
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use flatbuffers::FlatBufferBuilder;
|
||||
use mxc_sdk::mxc_common::models::ContainerPolicy;
|
||||
use mxc_sdk::mxc_common::ui_policy::resolve_ui_restrictions;
|
||||
use mxc_sdk::process_container_common::PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE;
|
||||
use mxc_sdk::process_container_common::ProcessSecurityEnvironmentApi;
|
||||
use mxc_sdk::process_container_common::SecurityEnvironmentStartupInfo;
|
||||
use mxc_sdk::process_container_common::job_object::to_job_object_uilimit_mask;
|
||||
use mxc_sdk::process_security_environment_spec::process_security_environment_layout::EndpointPolicyT;
|
||||
use mxc_sdk::process_security_environment_spec::process_security_environment_layout::FilterAction;
|
||||
use mxc_sdk::process_security_environment_spec::process_security_environment_layout::NetworkPolicyT;
|
||||
use mxc_sdk::process_security_environment_spec::process_security_environment_layout::ProcessSecurityEnvironmentT;
|
||||
use mxc_sdk::process_security_environment_spec::process_security_environment_layout::SchemaVersionT;
|
||||
use mxc_sdk::process_security_environment_spec::process_security_environment_layout::finish_process_security_environment_buffer;
|
||||
|
||||
pub(super) fn is_available() -> bool {
|
||||
static USABLE: OnceLock<bool> = OnceLock::new();
|
||||
*USABLE.get_or_init(|| {
|
||||
// Preserve the previous SDK's probe: no filesystem, network, or UI
|
||||
// grants, and no process launch. API-set presence alone is insufficient.
|
||||
let policy = ContainerPolicy::default();
|
||||
let mut egress = EndpointPolicyT::default();
|
||||
egress.default_action = FilterAction::deny;
|
||||
let mut network = NetworkPolicyT::default();
|
||||
network.egress = Some(Box::new(egress));
|
||||
let mut specification = ProcessSecurityEnvironmentT::default();
|
||||
specification.version = SchemaVersionT { major: 1, minor: 0 };
|
||||
specification.disallow_win32k_system_calls = policy.ui.disable;
|
||||
specification.ui_restrictions = u64::from(to_job_object_uilimit_mask(
|
||||
&resolve_ui_restrictions(&policy.ui, &policy.base_process_ui),
|
||||
));
|
||||
specification.network_policy = Some(Box::new(network));
|
||||
let mut builder = FlatBufferBuilder::with_capacity(/* capacity */ 1024);
|
||||
let specification = specification.pack(&mut builder);
|
||||
finish_process_security_environment_buffer(&mut builder, specification);
|
||||
ProcessSecurityEnvironmentApi::load()
|
||||
.and_then(|api| {
|
||||
api.create(
|
||||
builder.finished_data(),
|
||||
PROCESS_SECURITY_ENVIRONMENT_FLAG_NONE,
|
||||
)
|
||||
})
|
||||
.and_then(|environment| {
|
||||
let startup_info =
|
||||
SecurityEnvironmentStartupInfo::new(Default::default(), environment.raw(), &[]);
|
||||
environment.close();
|
||||
startup_info.map(drop)
|
||||
})
|
||||
.is_ok()
|
||||
})
|
||||
}
|
||||
166
codex-rs/mxc-sandbox/src/lib.rs
Normal file
166
codex-rs/mxc-sandbox/src/lib.rs
Normal file
@@ -0,0 +1,166 @@
|
||||
//! Native Windows MXC helper. Policy conversion is portable; execution requires
|
||||
//! a usable process security environment and never enters MXC's ACL fallbacks.
|
||||
|
||||
#[cfg(windows)]
|
||||
mod availability;
|
||||
#[cfg(windows)]
|
||||
mod native;
|
||||
#[cfg(any(windows, test))]
|
||||
mod policy;
|
||||
mod transport;
|
||||
#[cfg(windows)]
|
||||
mod windows;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use codex_network_proxy::ManagedNetworkSandboxContext;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_windows_sandbox::environment_transport;
|
||||
use serde::Deserialize;
|
||||
use serde::Serialize;
|
||||
|
||||
pub const CODEX_WINDOWS_MXC_ARG1: &str = "--__codex-windows-mxc";
|
||||
const CLIENT_ONLY_LOOPBACK_UNSUPPORTED: &str = "MXC cannot enforce managed networking with allow_local_binding=false: native host-loopback access is bidirectional";
|
||||
|
||||
fn validate_managed_network(network: &ManagedNetworkSandboxContext) -> Result<()> {
|
||||
ensure!(
|
||||
!network.loopback_ports.is_empty(),
|
||||
"MXC managed networking requires dedicated proxy ports"
|
||||
);
|
||||
ensure!(
|
||||
!network.loopback_ports.contains(&0),
|
||||
"MXC proxy ports must be nonzero"
|
||||
);
|
||||
ensure!(
|
||||
network.allow_local_binding,
|
||||
CLIENT_ONLY_LOOPBACK_UNSUPPORTED
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct MxcCommand {
|
||||
permissions: PermissionProfile,
|
||||
sandbox_policy_cwd: PathBuf,
|
||||
managed_network: Option<ManagedNetworkSandboxContext>,
|
||||
command: Vec<String>,
|
||||
#[serde(default)]
|
||||
default_child_env: bool,
|
||||
}
|
||||
|
||||
/// Inputs used to build an MXC helper invocation.
|
||||
#[derive(Debug)]
|
||||
pub struct CreateMxcCommandArgsParams<'a> {
|
||||
pub command: Vec<String>,
|
||||
pub permission_profile: &'a PermissionProfile,
|
||||
pub sandbox_policy_cwd: &'a Path,
|
||||
pub managed_network: Option<&'a ManagedNetworkSandboxContext>,
|
||||
pub env: &'a mut HashMap<String, String>,
|
||||
}
|
||||
|
||||
/// Wrap exact argv and add bounded launcher-only environment variables. The
|
||||
/// helper removes these variables before starting the sandboxed command.
|
||||
pub fn create_command_args(args: CreateMxcCommandArgsParams<'_>) -> Result<Vec<String>> {
|
||||
let CreateMxcCommandArgsParams {
|
||||
command,
|
||||
permission_profile,
|
||||
sandbox_policy_cwd,
|
||||
managed_network,
|
||||
env,
|
||||
} = args;
|
||||
sandbox_policy_cwd
|
||||
.to_str()
|
||||
.context("MXC requires a Unicode policy working directory")?;
|
||||
if let Some(network) = managed_network {
|
||||
validate_managed_network(network)?;
|
||||
}
|
||||
transport::encode(
|
||||
&MxcCommand {
|
||||
permissions: permission_profile.clone(),
|
||||
sandbox_policy_cwd: sandbox_policy_cwd.to_owned(),
|
||||
managed_network: managed_network.cloned(),
|
||||
command,
|
||||
default_child_env: env
|
||||
.keys()
|
||||
.all(|key| environment_transport::is_key(key.as_ref())),
|
||||
},
|
||||
env,
|
||||
)?;
|
||||
Ok(vec![CODEX_WINDOWS_MXC_ARG1.to_owned()])
|
||||
}
|
||||
|
||||
/// Whether the executor can create a native MXC process security environment.
|
||||
/// This deliberately excludes MXC's older AppContainer fallback backends.
|
||||
pub fn is_available() -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
availability::is_available()
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve configured symbols and snapshot deny globs for policy inspection.
|
||||
/// Reuses MXC's resolution without adding native grants or protections.
|
||||
#[cfg(windows)]
|
||||
pub fn prepare_file_system_policy(
|
||||
policy: codex_protocol::permissions::FileSystemSandboxPolicy,
|
||||
env: &HashMap<String, String>,
|
||||
policy_cwd: &codex_utils_absolute_path::AbsolutePathBuf,
|
||||
command_cwd: &Path,
|
||||
) -> Result<codex_protocol::permissions::FileSystemSandboxPolicy> {
|
||||
use codex_utils_path_uri::PathUri;
|
||||
|
||||
let env_entries = env
|
||||
.iter()
|
||||
.map(|(key, value)| format!("{key}={value}"))
|
||||
.collect::<Vec<_>>();
|
||||
let mut policy = policy::materialize_temporary_paths(policy, &env_entries)?;
|
||||
let denied = codex_windows_sandbox::resolve_windows_deny_read_paths(&policy, policy_cwd)
|
||||
.map_err(anyhow::Error::msg)?;
|
||||
policy = policy.with_expanded_deny_globs(denied);
|
||||
if policy.has_full_disk_write_access() {
|
||||
return Ok(policy);
|
||||
}
|
||||
let volumes = windows::volume_roots(policy_cwd.as_path(), command_cwd)?;
|
||||
let read_volumes = windows::implicit_read_roots(&volumes, policy_cwd.as_path(), command_cwd)?;
|
||||
let volumes = volumes
|
||||
.into_iter()
|
||||
.map(PathUri::from_host_native_path)
|
||||
.collect::<std::io::Result<Vec<_>>>()?;
|
||||
Ok(policy::materialize_volume_roots(
|
||||
policy,
|
||||
&volumes,
|
||||
&read_volumes,
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Entry point dispatched before ordinary Codex CLI parsing.
|
||||
pub fn run_main() -> ! {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
match windows::run() {
|
||||
Ok(exit_code) => std::process::exit(exit_code),
|
||||
Err(error) => {
|
||||
eprintln!("MXC launcher: {error:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
eprintln!("MXC sandbox execution requires Windows");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "policy_tests.rs"]
|
||||
mod tests;
|
||||
40
codex-rs/mxc-sandbox/src/native.rs
Normal file
40
codex-rs/mxc-sandbox/src/native.rs
Normal file
@@ -0,0 +1,40 @@
|
||||
//! Run an already prepared MXC request with inherited stdio and job ownership.
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use mxc_sdk::mxc_common::logger::Logger;
|
||||
use mxc_sdk::mxc_common::logger::Mode;
|
||||
use mxc_sdk::mxc_common::models::ExecutionRequest;
|
||||
use mxc_sdk::mxc_common::sandbox_process::SandboxBackend;
|
||||
use mxc_sdk::mxc_common::sandbox_process::StdioMode;
|
||||
use mxc_sdk::process_container_common::base_container_runner::BaseContainerRunner;
|
||||
|
||||
// The ETW functions used by tracelogging are documented Advapi32 exports on
|
||||
// both Windows toolchains; 1.2.3 leaves their import library to the application.
|
||||
#[link(name = "advapi32")]
|
||||
unsafe extern "system" {}
|
||||
|
||||
pub(super) fn launch(request: &ExecutionRequest) -> Result<i32> {
|
||||
ensure!(
|
||||
!request
|
||||
.policy
|
||||
.capabilities
|
||||
.iter()
|
||||
.any(|capability| capability.eq_ignore_ascii_case("permissiveLearningMode")),
|
||||
"MXC native launch does not support permissiveLearningMode"
|
||||
);
|
||||
if !request.policy.denied_paths.is_empty() {
|
||||
ensure!(
|
||||
BaseContainerRunner::supports_native_denied_paths(),
|
||||
"this Windows build cannot enforce native MXC deny paths"
|
||||
);
|
||||
}
|
||||
let mut logger = Logger::new(Mode::Buffer);
|
||||
let mut child = BaseContainerRunner::new()
|
||||
.spawn(request, &mut logger, StdioMode::Inherit)
|
||||
.map_err(|error| anyhow::anyhow!("{}", error.error_message))?;
|
||||
// Do not publish the SDK diagnostic buffer: it may contain command or
|
||||
// environment data. This wrapper emits only the resulting launch error.
|
||||
child.wait().context("waiting for the MXC command")
|
||||
}
|
||||
509
codex-rs/mxc-sandbox/src/policy.rs
Normal file
509
codex-rs/mxc-sandbox/src/policy.rs
Normal file
@@ -0,0 +1,509 @@
|
||||
//! 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 codex_protocol::permissions::FileSystemPolicyProjection;
|
||||
use codex_protocol::protocol::FileSystemAccessMode;
|
||||
use codex_protocol::protocol::FileSystemPath;
|
||||
use codex_protocol::protocol::FileSystemSandboxPolicy;
|
||||
use codex_protocol::protocol::FileSystemSpecialPath;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use codex_windows_sandbox::expand_windows_deny_read_paths;
|
||||
use codex_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<PathUri, PathBuf>;
|
||||
|
||||
/// 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<FileSystemSandboxPolicy> {
|
||||
// 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::<std::io::Result<Vec<_>>>()?;
|
||||
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<String>,
|
||||
volume_roots: &[PathBuf],
|
||||
platform_read_roots: &[PathBuf],
|
||||
) -> Result<ExecutionRequest, PolicyError> {
|
||||
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::<Vec<_>>();
|
||||
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::<std::io::Result<Vec<_>>>()?;
|
||||
#[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::<Vec<_>>()
|
||||
}))?;
|
||||
// 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::<std::io::Result<HashSet<_>>>()?;
|
||||
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<PathUri>) {
|
||||
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<FileSystemSandboxPolicy, PolicyError> {
|
||||
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<PathUri>,
|
||||
) -> Result<NativePaths, PolicyError> {
|
||||
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::<std::io::Result<Vec<_>>>) {
|
||||
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<Item = PathBuf>) -> Result<NativePaths, PolicyError> {
|
||||
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<Vec<String>, PolicyError> {
|
||||
let mut paths = paths
|
||||
.into_values()
|
||||
.map(|path| {
|
||||
path.into_os_string()
|
||||
.into_string()
|
||||
.map_err(|_| PolicyError::NonUnicodePolicyPath)
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
paths.sort();
|
||||
Ok(paths)
|
||||
}
|
||||
999
codex-rs/mxc-sandbox/src/policy_tests.rs
Normal file
999
codex-rs/mxc-sandbox/src/policy_tests.rs
Normal file
@@ -0,0 +1,999 @@
|
||||
//! Portable policy and launcher regressions, with Windows identity coverage.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_network_proxy::ManagedNetworkSandboxContext;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_protocol::permissions::FileSystemSandboxPolicyContext;
|
||||
use codex_protocol::protocol::FileSystemAccessMode;
|
||||
use codex_protocol::protocol::FileSystemPath;
|
||||
use codex_protocol::protocol::FileSystemSandboxEntry;
|
||||
use codex_protocol::protocol::FileSystemSandboxPolicy;
|
||||
use codex_protocol::protocol::FileSystemSpecialPath;
|
||||
use codex_protocol::protocol::NetworkSandboxPolicy;
|
||||
use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
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 pretty_assertions::assert_eq;
|
||||
|
||||
use crate::CreateMxcCommandArgsParams;
|
||||
use crate::MxcCommand;
|
||||
use crate::create_command_args;
|
||||
use crate::policy::PolicyError;
|
||||
use crate::policy::build_request;
|
||||
use crate::policy::materialize_volume_roots;
|
||||
|
||||
#[test]
|
||||
fn symbolic_root_precedence_is_independent_of_drive_and_cwd() -> Result<()> {
|
||||
use FileSystemAccessMode::Deny;
|
||||
use FileSystemAccessMode::Read;
|
||||
use FileSystemAccessMode::Write;
|
||||
|
||||
let volumes = [
|
||||
PathUri::parse("file:///C:/")?,
|
||||
PathUri::parse("file:///D:/")?,
|
||||
PathUri::parse("file:///R:/")?,
|
||||
];
|
||||
let readonly = PathUri::parse("file:///R:/foobar")?;
|
||||
let writable = PathUri::parse("file:///R:/writable")?;
|
||||
let mut fs = FileSystemSandboxPolicy::read_only();
|
||||
fs.entries.extend([
|
||||
FileSystemSandboxEntry::new(volumes[1].clone().into(), Read),
|
||||
FileSystemSandboxEntry::new(readonly.clone().into(), Read),
|
||||
FileSystemSandboxEntry::new(writable.clone().into(), Read),
|
||||
FileSystemSandboxEntry::new(writable.clone().into(), Write),
|
||||
]);
|
||||
for access in [Read, Write, Deny] {
|
||||
fs.entries[0].access = access;
|
||||
let resolved = materialize_volume_roots(fs.clone(), &volumes, &volumes[..2])?;
|
||||
for volume in &volumes {
|
||||
let cwd = volume.join("work")?;
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
user_home_dir: None,
|
||||
temporary_directories: None,
|
||||
};
|
||||
assert_eq!(
|
||||
[&volumes[0], &volumes[1], &volumes[2], &readonly, &writable]
|
||||
.map(|path| resolved.resolve_access(path, &context)),
|
||||
[
|
||||
access,
|
||||
access,
|
||||
if access == Read { Deny } else { access },
|
||||
Read,
|
||||
Write
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
fs.entries[0].access = Write;
|
||||
fs.entries.push(FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Tmpdir,
|
||||
},
|
||||
Read,
|
||||
));
|
||||
assert!(matches!(
|
||||
materialize_volume_roots(fs, &volumes, &volumes),
|
||||
Err(PolicyError::UnsupportedSymbolicPath)
|
||||
));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn approved_command_expands_volume_roots_without_retaining_original_grants() -> Result<()> {
|
||||
use FileSystemAccessMode::Deny;
|
||||
use FileSystemAccessMode::Read;
|
||||
use FileSystemAccessMode::Write;
|
||||
|
||||
let volumes = [
|
||||
PathUri::parse("file:///C:/")?,
|
||||
PathUri::parse("file:///D:/")?,
|
||||
];
|
||||
let cwd = volumes[0].join("work")?;
|
||||
let secret = volumes[0].join("private")?;
|
||||
let formerly_readonly = volumes[1].join("scoped")?;
|
||||
let reopened = secret.join("reopened")?;
|
||||
let root_git = volumes[0].join(".git")?;
|
||||
let denied_root_metadata = volumes[0].join(".agents")?;
|
||||
let workspace_git = cwd.join(".git/FETCH_HEAD")?;
|
||||
let context = FileSystemSandboxPolicyContext {
|
||||
cwd: &cwd,
|
||||
workspace_roots: std::slice::from_ref(&cwd),
|
||||
user_home_dir: None,
|
||||
temporary_directories: Some(&[]),
|
||||
};
|
||||
let mut policy = FileSystemSandboxPolicy::read_only();
|
||||
policy.entries.extend([
|
||||
FileSystemSandboxEntry::new(secret.clone().into(), Deny),
|
||||
FileSystemSandboxEntry::new(denied_root_metadata.clone().into(), Deny),
|
||||
FileSystemSandboxEntry::new(reopened.clone().into(), Write),
|
||||
FileSystemSandboxEntry::new(formerly_readonly.clone().into(), Read),
|
||||
]);
|
||||
let approved = policy.for_approved_command(&context);
|
||||
assert_eq!(approved.resolve_access(&formerly_readonly, &context), Deny);
|
||||
let translated = materialize_volume_roots(approved, &volumes, &volumes[..1])?;
|
||||
assert_eq!(
|
||||
[
|
||||
&volumes[0],
|
||||
&volumes[1],
|
||||
&formerly_readonly,
|
||||
&secret,
|
||||
&reopened,
|
||||
]
|
||||
.map(|path| translated.resolve_access(path, &context)),
|
||||
[Write, Write, Write, Deny, Deny]
|
||||
);
|
||||
assert_eq!(
|
||||
[&root_git, &denied_root_metadata, &workspace_git]
|
||||
.map(|path| translated.can_write_path(path, &context)),
|
||||
[true, false, true]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn canonical_root(temp: &tempfile::TempDir) -> Result<PathBuf> {
|
||||
Ok(
|
||||
PathUri::from_host_native_path(std::fs::canonicalize(temp.path())?)?
|
||||
.to_abs_path()?
|
||||
.into_path_buf(),
|
||||
)
|
||||
}
|
||||
|
||||
fn entry(path: &Path, access: FileSystemAccessMode) -> Result<FileSystemSandboxEntry> {
|
||||
Ok(FileSystemSandboxEntry::new(
|
||||
AbsolutePathBuf::from_absolute_path(path)?.into(),
|
||||
access,
|
||||
))
|
||||
}
|
||||
|
||||
fn command(permissions: &PermissionProfile, cwd: &Path) -> MxcCommand {
|
||||
MxcCommand {
|
||||
permissions: permissions.clone(),
|
||||
sandbox_policy_cwd: cwd.to_owned(),
|
||||
managed_network: None,
|
||||
command: vec!["program.exe".to_owned(), "--arg".to_owned()],
|
||||
default_child_env: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrapper_preserves_exact_argv_and_separate_command_cwd() -> Result<()> {
|
||||
let root = tempfile::tempdir()?;
|
||||
let cwd = root.path().join("command-cwd");
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(Vec::new()),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
let argv = vec![
|
||||
r"C:\Program Files\tool.exe".to_owned(),
|
||||
"--permissions".to_owned(),
|
||||
String::new(),
|
||||
"quotes\" and slash\\".to_owned(),
|
||||
];
|
||||
let mut env = HashMap::new();
|
||||
codex_windows_sandbox::environment_transport::encode("stale", &mut env)?;
|
||||
let wrapped = create_command_args(CreateMxcCommandArgsParams {
|
||||
command: argv.clone(),
|
||||
permission_profile: &profile,
|
||||
sandbox_policy_cwd: root.path(),
|
||||
managed_network: None,
|
||||
env: &mut env,
|
||||
})?;
|
||||
assert_eq!(wrapped, vec![crate::CODEX_WINDOWS_MXC_ARG1]);
|
||||
let parsed = crate::transport::decode(&mut env)?;
|
||||
assert!(parsed.default_child_env);
|
||||
assert!(env.is_empty());
|
||||
assert_eq!(
|
||||
(
|
||||
&parsed.permissions,
|
||||
parsed.sandbox_policy_cwd.as_path(),
|
||||
&parsed.command
|
||||
),
|
||||
(&profile, root.path(), &argv)
|
||||
);
|
||||
let request = build_request(&parsed, &cwd, vec!["CUSTOM=value".to_owned()], &[], &[])?;
|
||||
assert_eq!(
|
||||
(request.script_code, request.working_directory, request.env),
|
||||
(
|
||||
r#""C:\Program Files\tool.exe" --permissions "" "quotes\" and slash\\""#.to_owned(),
|
||||
cwd.to_str().unwrap().to_owned(),
|
||||
Some(vec!["CUSTOM=value".to_owned()]),
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
build_request(&parsed, &cwd, Vec::new(), &[], &[])?.env,
|
||||
None
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_command_is_rejected_before_native_launch() -> Result<()> {
|
||||
let root = tempfile::tempdir()?;
|
||||
let mut parsed = command(&PermissionProfile::read_only(), root.path());
|
||||
parsed.command.clear();
|
||||
let error = build_request(&parsed, root.path(), Vec::new(), &[], &[]).unwrap_err();
|
||||
assert_eq!(error.to_string(), "MXC command must not be empty");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_grants_preserve_denies_and_read_only_carveouts() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let canonical = canonical_root(&temp)?;
|
||||
let root = canonical.as_path();
|
||||
let gitdir = tempfile::tempdir()?;
|
||||
std::fs::write(
|
||||
root.join(".git"),
|
||||
format!("gitdir: {}", gitdir.path().display()),
|
||||
)?;
|
||||
let readonly = root.join("readonly");
|
||||
let writable_child = readonly.join("writable");
|
||||
let denied = root.join("secret");
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(root, FileSystemAccessMode::Write)?,
|
||||
entry(&readonly, FileSystemAccessMode::Read)?,
|
||||
entry(&writable_child, FileSystemAccessMode::Write)?,
|
||||
entry(&denied, FileSystemAccessMode::Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(&command(&profile, root), root, Vec::new(), &[], &[])?;
|
||||
let mut expected_read = [
|
||||
root.join(".agents"),
|
||||
root.join(".aws"),
|
||||
root.join(".codex"),
|
||||
root.join(".git"),
|
||||
readonly,
|
||||
writable_child.join(".agents"),
|
||||
writable_child.join(".aws"),
|
||||
writable_child.join(".codex"),
|
||||
writable_child.join(".git"),
|
||||
];
|
||||
expected_read.sort();
|
||||
assert_eq!(
|
||||
(
|
||||
request.policy.readwrite_paths,
|
||||
request.policy.readonly_paths,
|
||||
request.policy.denied_paths
|
||||
),
|
||||
(
|
||||
vec![
|
||||
root.to_str().unwrap().to_owned(),
|
||||
writable_child.to_str().unwrap().to_owned()
|
||||
],
|
||||
expected_read
|
||||
.iter()
|
||||
.map(|path| path.to_str().unwrap().to_owned())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![denied.to_str().unwrap().to_owned()],
|
||||
)
|
||||
);
|
||||
assert!(!request.policy.fallback.allow_dacl_mutation);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn volume_expansion_does_not_turn_read_only_child_writable() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let canonical = canonical_root(&temp)?;
|
||||
let root = canonical.as_path();
|
||||
let readonly = root.join("protected");
|
||||
let writable = root.join("work");
|
||||
let missing = root.join("new");
|
||||
let denied = missing.join("parent").join("secret");
|
||||
std::fs::create_dir(&readonly)?;
|
||||
std::fs::create_dir(&writable)?;
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(root, FileSystemAccessMode::Write)?,
|
||||
entry(&readonly, FileSystemAccessMode::Read)?,
|
||||
entry(&denied, FileSystemAccessMode::Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, root),
|
||||
root,
|
||||
Vec::new(),
|
||||
&[root.to_owned()],
|
||||
&[],
|
||||
)?;
|
||||
let mut expected_write_paths = vec![root.to_str().unwrap(), writable.to_str().unwrap()];
|
||||
if cfg!(windows) {
|
||||
expected_write_paths.insert(1, missing.to_str().unwrap());
|
||||
assert!(denied.parent().unwrap().is_dir());
|
||||
assert!(!denied.exists());
|
||||
for directory in [&missing, &missing.join("parent")] {
|
||||
assert_eq!(std::fs::read(directory.join(".chatgptcreated"))?, b"");
|
||||
}
|
||||
for directory in [root, readonly.as_path(), writable.as_path()] {
|
||||
assert!(!directory.join(".chatgptcreated").exists());
|
||||
}
|
||||
}
|
||||
assert_eq!(request.policy.readwrite_paths, expected_write_paths);
|
||||
assert_eq!(request.policy.denied_paths, vec![denied.to_str().unwrap()]);
|
||||
assert_eq!(
|
||||
request.policy.readonly_paths,
|
||||
vec![
|
||||
root.join(".agents").to_str().unwrap(),
|
||||
root.join(".aws").to_str().unwrap(),
|
||||
root.join(".codex").to_str().unwrap(),
|
||||
root.join(".git").to_str().unwrap(),
|
||||
readonly.to_str().unwrap()
|
||||
]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn volume_expansion_skips_broken_links_and_preserves_other_grants() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = canonical_root(&temp)?;
|
||||
let uninspectable = root.join("loop");
|
||||
std::os::unix::fs::symlink(&uninspectable, &uninspectable)?;
|
||||
std::os::unix::fs::symlink(root.join("missing"), root.join("dangling"))?;
|
||||
let readable = root.join("readable");
|
||||
std::fs::write(&readable, "readable")?;
|
||||
let alias = root.join("alias");
|
||||
std::os::unix::fs::symlink(&readable, &alias)?;
|
||||
let denied = root.join("secret");
|
||||
std::fs::write(&denied, "secret")?;
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(&root, FileSystemAccessMode::Write)?,
|
||||
entry(&denied, FileSystemAccessMode::Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, &root),
|
||||
&root,
|
||||
Vec::new(),
|
||||
std::slice::from_ref(&root),
|
||||
&[],
|
||||
)?;
|
||||
assert_eq!(
|
||||
(request.policy.readwrite_paths, request.policy.denied_paths),
|
||||
(
|
||||
vec![
|
||||
root.to_str().unwrap().to_owned(),
|
||||
alias.to_str().unwrap().to_owned(),
|
||||
readable.to_str().unwrap().to_owned()
|
||||
],
|
||||
vec![denied.to_str().unwrap().to_owned()],
|
||||
)
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_write_access_expands_volume_children() -> Result<()> {
|
||||
let first = tempfile::tempdir()?;
|
||||
let second = tempfile::tempdir()?;
|
||||
let unmapped = tempfile::tempdir()?;
|
||||
let explicit = canonical_root(&unmapped)?;
|
||||
let volumes = [canonical_root(&first)?, canonical_root(&second)?];
|
||||
std::fs::create_dir(volumes[0].join("one"))?;
|
||||
std::fs::create_dir(volumes[1].join("two"))?;
|
||||
let mut fs = FileSystemSandboxPolicy::read_only();
|
||||
// Like an unmapped UNC share, this grant is outside the supplied volumes.
|
||||
fs.entries
|
||||
.push(entry(&explicit, FileSystemAccessMode::Read)?);
|
||||
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Write] {
|
||||
let mut expected = vec![volumes[0].clone(), volumes[1].clone(), explicit.clone()];
|
||||
if access == FileSystemAccessMode::Write {
|
||||
expected.extend([volumes[0].join("one"), volumes[1].join("two")]);
|
||||
}
|
||||
expected.sort();
|
||||
fs.entries[0].access = access;
|
||||
fs.entries[1].access = access;
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, &volumes[0]),
|
||||
&volumes[0],
|
||||
Vec::new(),
|
||||
&volumes,
|
||||
&[],
|
||||
)?;
|
||||
let native = request.policy;
|
||||
let (granted, other) = if access == FileSystemAccessMode::Write {
|
||||
(native.readwrite_paths, native.readonly_paths)
|
||||
} else {
|
||||
(native.readonly_paths, native.readwrite_paths)
|
||||
};
|
||||
assert_eq!(
|
||||
granted,
|
||||
expected
|
||||
.iter()
|
||||
.map(|path| path.to_str().unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(other, Vec::<String>::new());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_network_allows_authorized_loopback_without_lan_or_dns_access() -> Result<()> {
|
||||
let root = tempfile::tempdir()?;
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(Vec::new()),
|
||||
NetworkSandboxPolicy::Enabled,
|
||||
);
|
||||
let proxy = ManagedNetworkSandboxContext {
|
||||
loopback_ports: vec![43123, 43124],
|
||||
allow_local_binding: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut env = HashMap::new();
|
||||
create_command_args(CreateMxcCommandArgsParams {
|
||||
command: vec!["program.exe".to_owned()],
|
||||
permission_profile: &profile,
|
||||
sandbox_policy_cwd: root.path(),
|
||||
managed_network: Some(&proxy),
|
||||
env: &mut env,
|
||||
})?;
|
||||
let parsed = crate::transport::decode(&mut env)?;
|
||||
let request = build_request(&parsed, root.path(), Vec::new(), &[], &[])?;
|
||||
assert_eq!(
|
||||
request.policy.network_egress,
|
||||
Some(NetworkEgressPolicy {
|
||||
default: NetworkAction::Deny,
|
||||
allow: vec![NetworkRule {
|
||||
to: vec![
|
||||
NetworkPeer {
|
||||
cidr: "127.0.0.0/8".parse()?,
|
||||
except: Vec::new()
|
||||
},
|
||||
NetworkPeer {
|
||||
cidr: NetworkCidr {
|
||||
address: std::net::Ipv6Addr::LOCALHOST.into(),
|
||||
prefix_length: 128
|
||||
},
|
||||
except: Vec::new()
|
||||
},
|
||||
],
|
||||
ports: Vec::new(),
|
||||
}],
|
||||
deny: Vec::new(),
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
request.policy.network_ingress,
|
||||
Some(NetworkIngressPolicy {
|
||||
default: NetworkAction::Deny,
|
||||
host_loopback: NetworkAction::Allow,
|
||||
})
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_managed_network_is_rejected_at_both_boundaries() -> Result<()> {
|
||||
let root = tempfile::tempdir()?;
|
||||
let cwd = root.path();
|
||||
let profile = PermissionProfile::read_only();
|
||||
for (loopback_ports, allow_local_binding) in
|
||||
[(Vec::new(), true), (vec![0], true), (vec![43123], false)]
|
||||
{
|
||||
let proxy = ManagedNetworkSandboxContext {
|
||||
loopback_ports,
|
||||
allow_local_binding,
|
||||
..Default::default()
|
||||
};
|
||||
let mut env = HashMap::new();
|
||||
assert!(
|
||||
create_command_args(CreateMxcCommandArgsParams {
|
||||
command: Vec::new(),
|
||||
permission_profile: &profile,
|
||||
sandbox_policy_cwd: cwd,
|
||||
managed_network: Some(&proxy),
|
||||
env: &mut env,
|
||||
})
|
||||
.is_err()
|
||||
);
|
||||
let mut parsed = command(&profile, cwd);
|
||||
parsed.managed_network = Some(proxy);
|
||||
assert!(build_request(&parsed, cwd, Vec::new(), &[], &[]).is_err());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deny_globs_expand_files_and_directories_before_launch() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = canonical_root(&temp)?;
|
||||
let nested = root.join("nested");
|
||||
std::fs::create_dir(&nested)?;
|
||||
let file = nested.join("file.secret");
|
||||
let directory = nested.join("directory.secret");
|
||||
std::fs::write(&file, "secret")?;
|
||||
std::fs::create_dir(&directory)?;
|
||||
std::fs::write(nested.join("allowed.txt"), "allowed")?;
|
||||
let missing = root.join("missing").join("parent").join("explicit.secret");
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(&root, FileSystemAccessMode::Write)?,
|
||||
entry(&missing, FileSystemAccessMode::Deny)?,
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: "**/*.secret".to_owned(),
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
),
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(&command(&profile, &root), &nested, Vec::new(), &[], &[])?;
|
||||
#[cfg(windows)]
|
||||
{
|
||||
assert!(missing.parent().unwrap().is_dir());
|
||||
assert!(!missing.exists());
|
||||
}
|
||||
assert_eq!(request.policy.readwrite_paths, vec![root.to_str().unwrap()]);
|
||||
let mut expected = [file, directory, missing];
|
||||
expected.sort();
|
||||
assert_eq!(
|
||||
request.policy.denied_paths,
|
||||
expected.map(|path| path.to_str().unwrap().to_owned())
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn denied_parents_are_created_before_glob_expansion() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = canonical_root(&temp)?;
|
||||
let missing = root.join("missing");
|
||||
for parent_deny in [
|
||||
entry(&missing, FileSystemAccessMode::Deny)?,
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::GlobPattern {
|
||||
pattern: "**/missing".to_owned(),
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
),
|
||||
] {
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(&root, FileSystemAccessMode::Write)?,
|
||||
parent_deny,
|
||||
entry(&missing.join("child"), FileSystemAccessMode::Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(&command(&profile, &root), &root, Vec::new(), &[], &[])?;
|
||||
assert!(missing.is_dir());
|
||||
assert!(!missing.join("child").exists());
|
||||
assert_eq!(
|
||||
request.policy.denied_paths,
|
||||
vec![
|
||||
missing.to_str().unwrap(),
|
||||
missing.join("child").to_str().unwrap()
|
||||
]
|
||||
);
|
||||
let sentinel = missing.join(".chatgptcreated");
|
||||
assert_eq!(std::fs::read(&sentinel)?, b"");
|
||||
std::fs::write(&sentinel, "preserve existing contents")?;
|
||||
build_request(&command(&profile, &root), &root, Vec::new(), &[], &[])?;
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(&sentinel)?,
|
||||
"preserve existing contents"
|
||||
);
|
||||
std::fs::remove_file(sentinel)?;
|
||||
std::fs::remove_dir(&missing)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn deny_parent_cannot_use_sentinel_name() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = canonical_root(&temp)?;
|
||||
let missing = root.join("missing");
|
||||
for name in [".chatgptcreated", ".CHATGPTCREATED", ".chatgptcreated. "] {
|
||||
let denied = missing.join(name).join("secret");
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(&root, FileSystemAccessMode::Write)?,
|
||||
entry(&denied, FileSystemAccessMode::Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let error = build_request(&command(&profile, &root), &root, Vec::new(), &[], &[])
|
||||
.expect_err("sentinel directory names must be rejected before creating parents");
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("reserved directory name .chatgptcreated")
|
||||
);
|
||||
assert!(!missing.exists());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_deny_keeps_only_narrow_explicit_grants() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let canonical = canonical_root(&temp)?;
|
||||
let root = canonical.as_path();
|
||||
let child = root.join("allowed");
|
||||
for access in [FileSystemAccessMode::Read, FileSystemAccessMode::Write] {
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
access,
|
||||
),
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
FileSystemAccessMode::Deny,
|
||||
),
|
||||
entry(&child, access)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, root),
|
||||
root,
|
||||
Vec::new(),
|
||||
&[root.to_owned()],
|
||||
&[],
|
||||
)?;
|
||||
let allowed = vec![child.to_str().unwrap().to_owned()];
|
||||
let expected = match access {
|
||||
FileSystemAccessMode::Read => (Vec::new(), allowed),
|
||||
FileSystemAccessMode::Write => (
|
||||
allowed,
|
||||
[".agents", ".aws", ".codex", ".git"]
|
||||
.map(|name| child.join(name).to_str().unwrap().to_owned())
|
||||
.to_vec(),
|
||||
),
|
||||
FileSystemAccessMode::Deny => unreachable!(),
|
||||
};
|
||||
assert_eq!(
|
||||
(
|
||||
request.policy.readwrite_paths,
|
||||
request.policy.readonly_paths
|
||||
),
|
||||
expected
|
||||
);
|
||||
assert_eq!(request.policy.denied_paths, Vec::<String>::new());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windows_temp_roots_use_filtered_environment_and_keep_explicit_denies() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let canonical = canonical_root(&temp)?;
|
||||
let root = canonical.as_path();
|
||||
let first = root.join("temp").join("~");
|
||||
let second = root.join("tmp with spaces");
|
||||
let denied = first.join("secret");
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Tmpdir,
|
||||
},
|
||||
FileSystemAccessMode::Write,
|
||||
),
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::SlashTmp,
|
||||
},
|
||||
FileSystemAccessMode::Write,
|
||||
),
|
||||
entry(&denied, FileSystemAccessMode::Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, root),
|
||||
root,
|
||||
vec![
|
||||
format!("temp={}", first.display()),
|
||||
format!("Tmp={}", second.display()),
|
||||
],
|
||||
&[],
|
||||
&[],
|
||||
)?;
|
||||
assert_eq!(
|
||||
request.policy.readwrite_paths,
|
||||
vec![first.to_str().unwrap(), second.to_str().unwrap()]
|
||||
);
|
||||
assert_eq!(request.policy.denied_paths, vec![denied.to_str().unwrap()]);
|
||||
|
||||
for value in [
|
||||
None,
|
||||
Some(""),
|
||||
Some("relative"),
|
||||
Some("~/scratch"),
|
||||
Some("~\\scratch"),
|
||||
Some("C:temp"),
|
||||
Some("\\temp"),
|
||||
] {
|
||||
let request = build_request(
|
||||
&command(&profile, root),
|
||||
root,
|
||||
value
|
||||
.map(|value| vec![format!("TEMP={value}"), format!("TMP={value}")])
|
||||
.unwrap_or_default(),
|
||||
&[],
|
||||
&[],
|
||||
)?;
|
||||
assert_eq!(request.policy.readwrite_paths, Vec::<String>::new());
|
||||
assert_eq!(request.policy.denied_paths, vec![denied.to_str().unwrap()]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_platform_roots_preserve_explicit_denies() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = canonical_root(&temp)?;
|
||||
let allowed = root.join("platform");
|
||||
let denied = root.join("secret");
|
||||
for include_defaults in [false, true] {
|
||||
let mut entries = vec![entry(&denied, FileSystemAccessMode::Deny)?];
|
||||
if include_defaults {
|
||||
entries.push(FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Minimal,
|
||||
},
|
||||
FileSystemAccessMode::Read,
|
||||
));
|
||||
}
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(entries),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
let request = build_request(
|
||||
&command(&profile, &root),
|
||||
&root,
|
||||
Vec::new(),
|
||||
&[],
|
||||
&[allowed.clone(), denied.clone()],
|
||||
)?;
|
||||
let expected_read = if include_defaults {
|
||||
vec![allowed.to_str().unwrap().to_owned()]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
assert_eq!(
|
||||
(request.policy.readonly_paths, request.policy.denied_paths),
|
||||
(expected_read, vec![denied.to_str().unwrap().to_owned()])
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn symbolic_root_preserves_equal_path_precedence_and_denies() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let base = canonical_root(&temp)?;
|
||||
let volumes = [
|
||||
base.join("first"),
|
||||
base.join("readonly"),
|
||||
base.join("denied"),
|
||||
];
|
||||
for volume in &volumes {
|
||||
std::fs::create_dir_all(volume.join("child"))?;
|
||||
}
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
FileSystemAccessMode::Write,
|
||||
),
|
||||
entry(&volumes[1], FileSystemAccessMode::Read)?,
|
||||
entry(&volumes[2], FileSystemAccessMode::Deny)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, &volumes[0]),
|
||||
&volumes[0],
|
||||
Vec::new(),
|
||||
&volumes,
|
||||
&[],
|
||||
)?;
|
||||
assert_eq!(
|
||||
request.policy.readwrite_paths,
|
||||
vec![
|
||||
volumes[0].to_str().unwrap().to_owned(),
|
||||
volumes[0].join("child").to_str().unwrap().to_owned(),
|
||||
volumes[1].to_str().unwrap().to_owned(),
|
||||
volumes[1].join("child").to_str().unwrap().to_owned(),
|
||||
]
|
||||
);
|
||||
let reads_in_volumes: Vec<_> = request
|
||||
.policy
|
||||
.readonly_paths
|
||||
.into_iter()
|
||||
.filter(|path| Path::new(path).starts_with(&base))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
reads_in_volumes,
|
||||
volumes[..2]
|
||||
.iter()
|
||||
.flat_map(
|
||||
|volume| [".agents", ".aws", ".codex", ".git"].map(|name| volume
|
||||
.join(name)
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned())
|
||||
)
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
request.policy.denied_paths,
|
||||
vec![volumes[2].to_str().unwrap()]
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn narrowing_one_volume_keeps_the_other_volume_root_grant() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let base = canonical_root(&temp)?;
|
||||
let volumes = [base.join("first"), base.join("second")];
|
||||
for volume in &volumes {
|
||||
std::fs::create_dir_all(volume.join("child"))?;
|
||||
}
|
||||
for (root_access, narrowed) in [
|
||||
(FileSystemAccessMode::Read, FileSystemAccessMode::Deny),
|
||||
(FileSystemAccessMode::Write, FileSystemAccessMode::Read),
|
||||
] {
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
FileSystemSandboxEntry::new(
|
||||
FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
root_access,
|
||||
),
|
||||
entry(&volumes[0].join("child"), narrowed)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, &volumes[0]),
|
||||
&volumes[0],
|
||||
Vec::new(),
|
||||
&volumes,
|
||||
&[],
|
||||
)?;
|
||||
let granted = if root_access == FileSystemAccessMode::Write {
|
||||
request.policy.readwrite_paths
|
||||
} else {
|
||||
request.policy.readonly_paths
|
||||
};
|
||||
let second_grants: Vec<_> = granted
|
||||
.into_iter()
|
||||
.filter(|path| Path::new(path).starts_with(&volumes[1]))
|
||||
.collect();
|
||||
let mut expected = vec![volumes[1].to_str().unwrap().to_owned()];
|
||||
if root_access == FileSystemAccessMode::Write {
|
||||
expected.push(volumes[1].join("child").to_str().unwrap().to_owned());
|
||||
}
|
||||
assert_eq!(second_grants, expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn volume_enumeration_uses_windows_identity_for_read_write_overrides() -> Result<()> {
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = canonical_root(&temp)?;
|
||||
let child = root.join("MiXeD");
|
||||
std::fs::create_dir(&child)?;
|
||||
let alias = child.to_str().unwrap().to_ascii_lowercase();
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![
|
||||
entry(&root, FileSystemAccessMode::Read)?,
|
||||
entry(Path::new(&alias), FileSystemAccessMode::Write)?,
|
||||
]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let request = build_request(
|
||||
&command(&profile, &root),
|
||||
&root,
|
||||
Vec::new(),
|
||||
std::slice::from_ref(&root),
|
||||
&[],
|
||||
)?;
|
||||
assert_eq!(
|
||||
request.policy.readwrite_paths,
|
||||
vec![
|
||||
PathUri::from_host_native_path(&alias)?
|
||||
.to_abs_path()?
|
||||
.as_path()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_owned()
|
||||
]
|
||||
);
|
||||
let readonly_child: Vec<_> = request
|
||||
.policy
|
||||
.readonly_paths
|
||||
.into_iter()
|
||||
.filter(|path| path.eq_ignore_ascii_case(child.to_str().unwrap()))
|
||||
.collect();
|
||||
assert_eq!(readonly_child, Vec::<String>::new());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relative_working_directories_fail_before_launch() -> Result<()> {
|
||||
let root = tempfile::tempdir()?;
|
||||
let profile = PermissionProfile::from_runtime_permissions(
|
||||
&FileSystemSandboxPolicy::restricted(Vec::new()),
|
||||
NetworkSandboxPolicy::Restricted,
|
||||
);
|
||||
for (policy_cwd, command_cwd, kind) in [
|
||||
(Path::new("relative"), root.path(), "policy"),
|
||||
(root.path(), Path::new("relative"), "command"),
|
||||
] {
|
||||
let error = build_request(
|
||||
&command(&profile, policy_cwd),
|
||||
command_cwd,
|
||||
Vec::new(),
|
||||
&[],
|
||||
&[],
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
format!("MXC requires an absolute {kind} working directory")
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_unicode_paths_fail_before_launch() -> Result<()> {
|
||||
#[cfg(unix)]
|
||||
let name = <std::ffi::OsString as std::os::unix::ffi::OsStringExt>::from_vec(vec![0xff]);
|
||||
#[cfg(windows)]
|
||||
let name = <std::ffi::OsString as std::os::windows::ffi::OsStringExt>::from_wide(&[0xd800]);
|
||||
let temp = tempfile::tempdir()?;
|
||||
let root = canonical_root(&temp)?;
|
||||
let invalid = root.join(name);
|
||||
for (policy_path, command_cwd, expected) in [
|
||||
(
|
||||
root.as_path(),
|
||||
invalid.as_path(),
|
||||
"MXC requires a Unicode command working directory",
|
||||
),
|
||||
(
|
||||
invalid.as_path(),
|
||||
root.as_path(),
|
||||
"MXC requires Unicode filesystem policy paths",
|
||||
),
|
||||
] {
|
||||
let fs = FileSystemSandboxPolicy::restricted(vec![entry(
|
||||
policy_path,
|
||||
FileSystemAccessMode::Deny,
|
||||
)?]);
|
||||
let profile =
|
||||
PermissionProfile::from_runtime_permissions(&fs, NetworkSandboxPolicy::Restricted);
|
||||
let error = build_request(&command(&profile, &root), command_cwd, Vec::new(), &[], &[])
|
||||
.unwrap_err();
|
||||
assert_eq!(error.to_string(), expected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
44
codex-rs/mxc-sandbox/src/transport.rs
Normal file
44
codex-rs/mxc-sandbox/src/transport.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
//! Bounded launcher transport. Windows startup variables are host-owned;
|
||||
//! an original-empty marker preserves the SDK's user-profile defaults.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use codex_windows_sandbox::environment_transport;
|
||||
|
||||
use crate::MxcCommand;
|
||||
|
||||
pub(super) fn encode(command: &MxcCommand, env: &mut HashMap<String, String>) -> Result<()> {
|
||||
// SDK profile defaults depend on the launcher's SystemRoot.
|
||||
#[cfg(windows)]
|
||||
for key in ["SystemDrive", "LOCALAPPDATA"]
|
||||
.into_iter()
|
||||
.chain(command.default_child_env.then_some("SystemRoot"))
|
||||
{
|
||||
let value = std::env::var(key)
|
||||
.ok()
|
||||
.filter(|value| !value.is_empty())
|
||||
.with_context(|| format!("MXC requires nonempty Unicode host {key}"))?;
|
||||
env.retain(|name, _| !name.eq_ignore_ascii_case(key));
|
||||
env.insert(key.to_owned(), value);
|
||||
}
|
||||
let payload = serde_json::to_string(command)?;
|
||||
environment_transport::encode(&payload, env)
|
||||
}
|
||||
|
||||
#[cfg(any(windows, test))]
|
||||
pub(super) fn decode(env: &mut HashMap<String, String>) -> Result<MxcCommand> {
|
||||
let payload = environment_transport::decode_and_scrub(env)?;
|
||||
let command: MxcCommand =
|
||||
serde_json::from_str(&payload).context("invalid MXC launcher request")?;
|
||||
if command.default_child_env {
|
||||
env.clear();
|
||||
}
|
||||
Ok(command)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "transport_tests.rs"]
|
||||
mod tests;
|
||||
56
codex-rs/mxc-sandbox/src/transport_tests.rs
Normal file
56
codex-rs/mxc-sandbox/src/transport_tests.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
//! Verify bounded transport, Unicode roundtrips, and child-environment cleanup.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use codex_protocol::models::PermissionProfile;
|
||||
use codex_windows_sandbox::environment_transport;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use crate::MxcCommand;
|
||||
|
||||
use super::decode;
|
||||
use super::encode;
|
||||
|
||||
fn command(args: Vec<String>) -> MxcCommand {
|
||||
MxcCommand {
|
||||
permissions: PermissionProfile::read_only(),
|
||||
sandbox_policy_cwd: PathBuf::from("workspace"),
|
||||
managed_network: None,
|
||||
command: args,
|
||||
default_child_env: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_unicode_launch_roundtrips_and_never_reaches_child_environment() -> Result<()> {
|
||||
let args = vec![
|
||||
"codex-windows-mxc".to_owned(),
|
||||
"🧊".repeat(20_000),
|
||||
"a\"\\b".to_owned(),
|
||||
];
|
||||
let expected_env = HashMap::from([("CUSTOM".to_owned(), "value".to_owned())]);
|
||||
let mut env = expected_env.clone();
|
||||
#[cfg(windows)]
|
||||
env.extend(
|
||||
["systemdrive", "LocalAppData"].map(|key| (key.to_owned(), "caller-only".to_owned())),
|
||||
);
|
||||
environment_transport::encode("stale", &mut env)?;
|
||||
let request = command(args);
|
||||
encode(&request, &mut env)?;
|
||||
assert!(
|
||||
env.values()
|
||||
.all(|value| value.encode_utf16().count() < 32_767)
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::to_value(decode(&mut env)?)?,
|
||||
serde_json::to_value(request)?
|
||||
);
|
||||
#[cfg(windows)]
|
||||
for key in ["SystemDrive", "LOCALAPPDATA"] {
|
||||
assert_eq!(env.remove(key), Some(std::env::var(key)?));
|
||||
}
|
||||
assert_eq!(env, expected_env);
|
||||
Ok(())
|
||||
}
|
||||
165
codex-rs/mxc-sandbox/src/windows.rs
Normal file
165
codex-rs/mxc-sandbox/src/windows.rs
Normal file
@@ -0,0 +1,165 @@
|
||||
//! Resolve executor-local state and launch the decoded MXC helper request.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Result;
|
||||
use anyhow::ensure;
|
||||
use codex_utils_path_uri::PathUri;
|
||||
use windows_sys::Win32::Foundation::RPC_E_CHANGED_MODE;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetDriveTypeW;
|
||||
use windows_sys::Win32::Storage::FileSystem::GetLogicalDrives;
|
||||
use windows_sys::Win32::System::Com::COINIT_MULTITHREADED;
|
||||
use windows_sys::Win32::System::Com::CoInitializeEx;
|
||||
use windows_sys::Win32::System::Com::CoTaskMemFree;
|
||||
use windows_sys::Win32::System::Com::CoUninitialize;
|
||||
use windows_sys::Win32::System::SystemInformation::GetWindowsDirectoryW;
|
||||
use windows_sys::Win32::System::WindowsProgramming::DRIVE_REMOTE;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramData;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramFiles;
|
||||
use windows_sys::Win32::UI::Shell::FOLDERID_ProgramFilesX86;
|
||||
use windows_sys::Win32::UI::Shell::SHGetKnownFolderPath;
|
||||
|
||||
struct ComUninitializeGuard;
|
||||
|
||||
impl Drop for ComUninitializeGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe { CoUninitialize() };
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn run() -> Result<i32> {
|
||||
ensure!(
|
||||
crate::is_available(),
|
||||
"native MXC is unavailable on this Windows build"
|
||||
);
|
||||
// Read the already-filtered wrapper environment, rejecting lossy values
|
||||
// instead of inheriting a different environment inside the sandbox.
|
||||
let mut env = std::env::vars_os()
|
||||
.map(|(key, value)| {
|
||||
let key = key
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("MXC requires Unicode environment variable names"))?;
|
||||
let value = value
|
||||
.into_string()
|
||||
.map_err(|_| anyhow::anyhow!("MXC requires Unicode environment variable values"))?;
|
||||
Ok((key, value))
|
||||
})
|
||||
.collect::<Result<HashMap<_, _>>>()?;
|
||||
// Serde errors can quote arbitrary payload values; do not print them to stderr.
|
||||
let command = crate::transport::decode(&mut env)
|
||||
.map_err(|_| anyhow::anyhow!("invalid MXC launcher request"))?;
|
||||
// The transport itself proves this is an explicit child environment; it
|
||||
// may intentionally contain no variables once launcher state is removed.
|
||||
let command_cwd = std::env::current_dir()?;
|
||||
let volumes = volume_roots(&command.sandbox_policy_cwd, &command_cwd)?;
|
||||
let request = crate::policy::build_request(
|
||||
&command,
|
||||
&command_cwd,
|
||||
env.into_iter()
|
||||
.map(|(key, value)| format!("{key}={value}"))
|
||||
.collect(),
|
||||
&volumes,
|
||||
&platform_read_roots()?,
|
||||
)?;
|
||||
crate::native::launch(&request)
|
||||
}
|
||||
|
||||
pub(super) fn volume_roots(
|
||||
policy_cwd: &std::path::Path,
|
||||
command_cwd: &std::path::Path,
|
||||
) -> Result<Vec<PathBuf>> {
|
||||
let mask = unsafe { GetLogicalDrives() };
|
||||
ensure!(
|
||||
mask != 0,
|
||||
"cannot enumerate Windows volumes: {}",
|
||||
std::io::Error::last_os_error()
|
||||
);
|
||||
let mut volumes: Vec<PathBuf> = (0..26)
|
||||
.filter(|index| mask & (1 << index) != 0)
|
||||
.map(|index| PathBuf::from(format!("{}:\\", (b'A' + index as u8) as char)))
|
||||
.collect();
|
||||
// An explicit UNC cwd has no drive letter and is absent from GetLogicalDrives.
|
||||
for cwd in [policy_cwd, command_cwd] {
|
||||
if let Some(root) = cwd.ancestors().last() {
|
||||
volumes.push(root.to_path_buf());
|
||||
}
|
||||
}
|
||||
Ok(volumes)
|
||||
}
|
||||
|
||||
// Default reads cover local volumes and cwd shares, not unrelated network shares.
|
||||
// Explicit grants follow the normal policy path.
|
||||
pub(super) fn implicit_read_roots(
|
||||
volume_roots: &[PathBuf],
|
||||
policy_cwd: &Path,
|
||||
command_cwd: &Path,
|
||||
) -> std::io::Result<Vec<PathUri>> {
|
||||
volume_roots
|
||||
.iter()
|
||||
.filter(|root| {
|
||||
let wide = root
|
||||
.as_os_str()
|
||||
.encode_wide()
|
||||
.chain([0])
|
||||
.collect::<Vec<_>>();
|
||||
let drive_type = unsafe { GetDriveTypeW(wide.as_ptr()) };
|
||||
drive_type != DRIVE_REMOTE
|
||||
|| policy_cwd.starts_with(root)
|
||||
|| command_cwd.starts_with(root)
|
||||
})
|
||||
.map(PathUri::from_host_native_path)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn platform_read_roots() -> Result<Vec<PathBuf>> {
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
|
||||
let mut buffer = vec![0u16; 32768];
|
||||
let length = unsafe { GetWindowsDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) };
|
||||
ensure!(
|
||||
length > 0 && (length as usize) < buffer.len(),
|
||||
"cannot locate the Windows directory"
|
||||
);
|
||||
let com_status = unsafe { CoInitializeEx(std::ptr::null(), COINIT_MULTITHREADED as u32) };
|
||||
ensure!(
|
||||
com_status >= 0 || com_status == RPC_E_CHANGED_MODE,
|
||||
"cannot initialize COM: HRESULT {com_status:#010x}"
|
||||
);
|
||||
let _com = (com_status >= 0).then(|| ComUninitializeGuard);
|
||||
let mut roots = vec![PathBuf::from(std::ffi::OsString::from_wide(
|
||||
&buffer[..length as usize],
|
||||
))];
|
||||
for folder in [
|
||||
FOLDERID_ProgramFiles,
|
||||
FOLDERID_ProgramFilesX86,
|
||||
FOLDERID_ProgramData,
|
||||
] {
|
||||
let mut path = std::ptr::null_mut();
|
||||
let status = unsafe {
|
||||
SHGetKnownFolderPath(&folder, /*dwflags*/ 0, std::ptr::null_mut(), &mut path)
|
||||
};
|
||||
if status >= 0 && !path.is_null() {
|
||||
let mut length = 0;
|
||||
unsafe {
|
||||
while *path.add(length) != 0 {
|
||||
length += 1;
|
||||
}
|
||||
roots.push(PathBuf::from(std::ffi::OsString::from_wide(
|
||||
std::slice::from_raw_parts(path, length),
|
||||
)));
|
||||
CoTaskMemFree(path.cast());
|
||||
}
|
||||
} else {
|
||||
if !path.is_null() {
|
||||
unsafe { CoTaskMemFree(path.cast()) };
|
||||
}
|
||||
anyhow::bail!(
|
||||
"cannot locate required Windows platform directory: HRESULT {status:#010x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(roots)
|
||||
}
|
||||
Reference in New Issue
Block a user