mirror of
https://github.com/NVIDIA/OpenShell.git
synced 2026-10-25 06:42:52 +08:00
* Implement Windows host proxy integration and update dependencies for OpenShell
* Update README and gateway config to clarify egress proxy address handling and allocation
* Refactor ProxyIdentityMode to return Result for static_binary and add tests for binary path and SHA256 hash
* Enhance platform_hosts_path for Windows to use SystemRoot and improve error handling for hosts file reading
* Refactor FileFingerprint to use Option for mtime and ctime, simplifying metadata handling
* Add conditional compilation for Windows host module
* add unit tests for OPA policy evaluation and identity handling
* remove openshell-supervisor-network from unsupported driver package test exclusion list
* feat(mxc): enable host proxy TLS state generation
Generate per-sandbox TLS state for the MXC host proxy so HTTPS L7 enforcement can use the same MITM path as Linux. Grant generated CA material to the MXC process and inject standard trust env vars, while matching Linux behavior by disabling TLS termination on CA setup failure and relying on proxy fail-closed handling.
* fix(docs): remove outdated notes on governed egress from docs
* fix(tests): update TLS environment variable paths to use temporary directory
* fix(examples): make run-mxc-e2e harness correct and orphan-free
The MXC e2e harness never actually exercised the fs scenarios: it started
the gateway once and patched agent_command per scenario AFTERWARDS, so the
running gateway kept launching the default demo agent (not shipped in the
kit) and every fs scenario failed with CreateProcessW error:2. It also
scored on the `sandbox create` exit code (non-zero due to the harmless
interactive attach), wrote sandbox records to the persistent gateway DB
(leaving orphans that collided on later runs), and its deny scenarios never
proved denial.
Changes:
- Start a FRESH gateway per scenario so each scenario's agent_command is
actually loaded (root cause of CreateProcessW error:2).
- Score by on-disk artifact / expected outcome, not `sandbox create` exit.
- Real deny assertions: a control write to a granted path must succeed
(proves the agent ran) while the denied write must be absent. fs-empty
probes an ungranted out-of-share path (share_dir is mapped rw by design).
- Run the gateway on an ephemeral in-memory DB (sqlite::memory:) so the
harness never writes to the persistent store and cannot leave orphan
sandbox records; also use unique per-run sandbox names + pre-delete.
- Fix the process_container probe: use a real cwd + absolute cmd.exe
(canonical wxc-exec does not expand %TEMP% -> 0x8007010B).
- Fix summary counts (@() so a single FAIL is counted and exit is non-zero).
Verified PASS=4 FAIL=0 on 7F203-MXC-003 (no BaseContainer velocity keys)
using a canonical wxc-exec build (AppContainer fallback).
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(e2e): probe timeout is milliseconds (10ms->30000ms)
MXC process.timeout is wall-clock ms (wire.rs). The 10 value meant 10ms,
which the base-container tier (7F203-MXC-001/.181) enforced strictly and
timed the probe out. AppContainer path (.18/-003) happened to slip under
it. Bump to 30000ms so the process_container preflight probe is reliable
across both tiers.
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(mxc): use native paths in real runtime probes
Signed-off-by: Shailendra Singh <shailendras@nvidia.com>
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(mxc): make processcontainer work with mxc-latest-released wxc-exec
Three fixes to support the release wxc-exec binary (BaseContainer dispatcher)
in addition to mxc-fixes-env-vars:
1. Seed process env from host (driver.rs)
ProcessContainer starts with a completely blank environment -- no PATH,
SystemRoot, or anything. Seed the process env from the gateway host
environment so the agent binary can locate DLLs and run. Skip internal
Windows drive-letter variables (keys starting with '=') which cause
CreateProcessW to return ERROR_ENVVAR_NOT_FOUND. User agent_env entries
and TLS CA vars are applied as overrides on top of the host env.
2. Remove TLS readonly_paths grant (driver.rs)
The release wxc-exec (BaseContainer dispatcher) requires write-DAC
permission on every path in readonly_paths to set up AppContainer ACLs.
Adding the proxy's temp TLS directory caused a DACL error and exit -1.
The CA cert paths remain available to the agent via TLS env vars.
3. Remove allowedHosts from network JSON (mxc.rs)
The release wxc-exec rejects network.allowedHosts / network.blockedHosts
on Windows with "not yet supported". Removed the loopback exemption
attempt (127.0.0.1, ::1, localhost) from the network section.
Intra-container loopback works natively in the release binary without
it -- the spawner can connect to the server at 127.0.0.1:22000 directly.
Additional changes:
- mxc-ws-agent.rs: add relay-debug.txt error capture and relay-ready.txt
marker for reliable timing of host client connections.
- mxc-ws-gateway.toml: debug = true for JSON config dump during diagnosis.
- run-ws-agent-test.ps1: default port changed to 17670 (gateway default);
relay-ready.txt polling before ws-echo to avoid connecting before the
spawner has established the proxy bridge.
Signed-off-by: Prashant Khodade <pkhodade@nvidia.com>
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(e2e): address CodeRabbit review on run-mxc-e2e.ps1 (MR !46)
Four robustness/correctness fixes from CodeRabbit:
1. Start-Gw: kill the spawned gateway before the "did not start within 30s"
throw. If the process is alive but never binds the port, $gw is not yet
assigned in the caller, so the finally block cannot reap it -> orphan
gateway holding the port for the next run.
2. create-fail scoring: a non-zero `sandbox create` exit alone is not proof
of a policy rejection (gateway-registration/transport/fixture errors also
exit non-zero and would false-pass). PASS now requires a genuine
rejection signal (network / invalid_argument / network_policies) AND that
it is not an infrastructure failure; other non-zero exits go to FAIL with
output captured.
3. deny scenarios (ControlTarget path): snapshot the deny target AFTER
Wait-File lands the control artifact, so a late denied write (enforcement
regression racing the control write) can no longer be recorded as PASS.
4. -KeepRunning: break out of the scenario loop after the first scenario so
a later scenario does not start a second gateway on the same port
(previously a reliable port collision instead of a usable debug mode).
Re-verified PASS=4 FAIL=0 on both boxes (7F203-MXC-001 base-container and
7F203-MXC-003 AppContainer fallback); network-policy-rejected correctly
scores as "policy rejection".
Signed-off-by: Akber Raza <akberr@nvidia.com>
* feat(mxc-e2e): collect run-mxc-e2e output into a results bundle
Mirror the sibling run-*.ps1 scripts by collecting every run's logs into a
timestamped results-e2e-<stamp>\ folder and zipping it. The bundle contains the
console transcript, per-scenario gateway stdout/stderr, the exact TOML rendered
for each scenario, the policy fixture used, and a summary.txt with the verdict
table.
Per-scenario gateway logs now land in gateway.<scenario>.log/.err.log inside the
bundle instead of a single fixed gateway.e2e.log in the script directory.
Wrap pre-flight, mode setup, scenario definitions, and the scenario loop in a
single try/catch/finally so the finally always writes the summary, stops the
transcript, and zips the bundle -- even on a pre-flight failure. The existing
per-scenario gateway-cleanup try/finally stays nested inside. All scenario
logic, scoring rules, and comments are preserved.
Signed-off-by: Prashant S Khodade <pkhodade@nvidia.com>
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(mxc-e2e): address CodeRabbit review on run-mxc-e2e.ps1
- Require -Scenario when -KeepRunning: the loop breaks after the first
scenario, so a full-suite run would execute only one scenario yet still
report the suite as PASS. Fail fast so a partial run can't be mislabeled
complete.
- Start-Transcript now runs inside the guarded try block with a
$transcriptStarted flag; Stop-Transcript is only called when it actually
started, so a Start-Transcript failure still yields the results bundle.
- Wrap the -Scenario filter in @() so a single exact match stays an array
(reliable .Count and a proper array for the scenario loop on PS 5.1).
Signed-off-by: Prashant S Khodade <pkhodade@nvidia.com>
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(examples): pass gateway config via OPENSHELL_GATEWAY_CONFIG for spaced paths
Start-Process -ArgumentList does not quote array elements, so launching the
gateway with a bare --config <path> token split on any space in the install
path (e.g. C:\Users\First Last\...), and clap rejected the fragment with
'unrecognized subcommand'. Every MXC example launcher that started the gateway
hit this when the kit was unzipped under a path containing a space.
Pass the config path through the OPENSHELL_GATEWAY_CONFIG env var (which the
gateway already reads via clap) and drop the --config token. Env vars carry
spaces safely.
Affected: run-ocsf-audit, run-mxc-e2e, run-demo, run-inference-test,
run-ollama-test. run-mtls-test was not affected (its launch passes no config
path). Root-caused and fix-verified on 7F203-MXC-003 from a spaced path.
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(run-mxc-e2e): improve scoring logic and enhance command execution handling
* fix(mxc): reconcile proxy support after rebase
Restore the proxy-enabled OCSF audit example removed by 13185f6e now that the host CONNECT proxy is present. Adapt the proxy lifecycle test to the target branch's DriverSandboxSpec policy delivery contract.
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(mxc): grant sandbox access to proxy CA
- Share the per-sandbox public CA bundle with the AppContainer
- Add real wxc-exec HTTPS proxy coverage and document trust isolation
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(mxc): reject unsupported network middleware
- Reject middleware-bearing MXC policies before sandbox lifecycle begins
- Guard host proxy startup and document the unsupported registry path
- Add mapper, lifecycle, and host proxy regression coverage
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(mxc): reconcile host proxy with main
- remove obsolete inference routing from the host proxy adapter
- use the workspace AWS-LC provider in host-proxy tests
- adapt the forward-proxy test to ProxyIdentityMode
Signed-off-by: Akber Raza <akberr@nvidia.com>
* fix(build): switch to bundled Z3 for Windows MSVC builds
* fix(mxc): reconcile host proxy after rebase
Signed-off-by: Drew Newberry <anewberry@nvidia.com>
---------
Signed-off-by: Akber Raza <akberr@nvidia.com>
Signed-off-by: Shailendra Singh <shailendras@nvidia.com>
Signed-off-by: Prashant Khodade <pkhodade@nvidia.com>
Signed-off-by: Prashant S Khodade <pkhodade@nvidia.com>
Signed-off-by: Drew Newberry <anewberry@nvidia.com>
Co-authored-by: Jamie King <jamiek@nvidia.com>
Co-authored-by: Shailendra Singh <shailendras@nvidia.com>
Co-authored-by: Prashant Khodade <pkhodade@nvidia.com>
Co-authored-by: Drew Newberry <anewberry@nvidia.com>
508 lines
18 KiB
Rust
508 lines
18 KiB
Rust
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
//! Parity/invariant tests for the embedded coarse map over the repository's
|
|
//! example policies.
|
|
//!
|
|
//! Windows-only: the embedded mapper API is gated on `target_os = "windows"`,
|
|
//! so this whole file compiles to nothing elsewhere and runs in full on a
|
|
//! Windows test lane.
|
|
//!
|
|
//! Byte-for-byte parity with the previous raw-YAML mapper is intentionally
|
|
//! *not* asserted: routing through the canonical typed `SandboxPolicy`
|
|
//! normalizes ports and uses an unordered proto map (we sort keys). Instead we
|
|
//! assert the substantive invariants — filesystem fidelity, the host allowlist,
|
|
//! deny-by-default, and that broadening features are flagged as losses.
|
|
|
|
#![cfg(target_os = "windows")]
|
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use openshell_driver_mxc::{MxcMappingOptions, map_to_mxc, split_policy};
|
|
use openshell_policy::{parse_sandbox_policy, serialize_sandbox_policy, validate_sandbox_policy};
|
|
use serde_json::Value;
|
|
|
|
fn examples_root() -> PathBuf {
|
|
Path::new(env!("CARGO_MANIFEST_DIR")).join("../../examples")
|
|
}
|
|
|
|
fn discover(dir: &Path, out: &mut Vec<PathBuf>) {
|
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
|
return;
|
|
};
|
|
for entry in entries.flatten() {
|
|
let path = entry.path();
|
|
if path.is_dir() {
|
|
discover(&path, out);
|
|
} else if let Some(name) = path.file_name().and_then(|n| n.to_str())
|
|
&& name.contains("policy")
|
|
&& path
|
|
.extension()
|
|
.is_some_and(|e| e.eq_ignore_ascii_case("yaml"))
|
|
{
|
|
out.push(path);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn str_list(value: &Value) -> Vec<String> {
|
|
value
|
|
.as_array()
|
|
.map(|a| {
|
|
a.iter()
|
|
.filter_map(|v| v.as_str().map(str::to_owned))
|
|
.collect()
|
|
})
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn proxy_addr() -> std::net::SocketAddr {
|
|
"127.0.0.1:18080".parse().unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn all_example_policies_map_with_invariants() {
|
|
let root = examples_root();
|
|
let mut policies = Vec::new();
|
|
discover(&root, &mut policies);
|
|
policies.sort();
|
|
assert!(
|
|
!policies.is_empty(),
|
|
"no example policies found under {}",
|
|
root.display()
|
|
);
|
|
|
|
for path in &policies {
|
|
let yaml = std::fs::read_to_string(path).expect("read policy");
|
|
let policy = parse_sandbox_policy(&yaml)
|
|
.unwrap_or_else(|e| panic!("parse {} failed: {e}", path.display()));
|
|
|
|
let result = map_to_mxc(&policy, &MxcMappingOptions::default());
|
|
let cfg = &result.config;
|
|
|
|
// Deny-by-default network posture is always emitted.
|
|
assert_eq!(
|
|
cfg["network"]["defaultPolicy"],
|
|
"block",
|
|
"{} must emit defaultPolicy=block",
|
|
path.display()
|
|
);
|
|
|
|
// Filesystem fidelity: read_write / read_only copied exactly.
|
|
if let Some(fs) = &policy.filesystem {
|
|
assert_eq!(
|
|
str_list(&cfg["filesystem"]["readwritePaths"]),
|
|
fs.read_write,
|
|
"readwrite mismatch for {}",
|
|
path.display()
|
|
);
|
|
assert_eq!(
|
|
str_list(&cfg["filesystem"]["readonlyPaths"]),
|
|
fs.read_only,
|
|
"readonly mismatch for {}",
|
|
path.display()
|
|
);
|
|
}
|
|
|
|
// Every non-wildcard endpoint host appears in allowedHosts.
|
|
let allowed = str_list(&cfg["network"]["allowedHosts"]);
|
|
for rule in policy.network_policies.values() {
|
|
for ep in &rule.endpoints {
|
|
if !ep.host.is_empty() && !ep.host.contains('*') {
|
|
assert!(
|
|
allowed.contains(&ep.host),
|
|
"{} missing host {} in allowedHosts",
|
|
path.display(),
|
|
ep.host
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
// allowedHosts is deduplicated.
|
|
let mut sorted = allowed.clone();
|
|
sorted.sort();
|
|
sorted.dedup();
|
|
assert_eq!(
|
|
sorted.len(),
|
|
allowed.len(),
|
|
"duplicate hosts for {}",
|
|
path.display()
|
|
);
|
|
|
|
// Deterministic: mapping twice yields identical config.
|
|
let again = map_to_mxc(&policy, &MxcMappingOptions::default());
|
|
assert_eq!(
|
|
result.config,
|
|
again.config,
|
|
"non-deterministic for {}",
|
|
path.display()
|
|
);
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn all_example_policies_split_with_expected_invariants() {
|
|
let root = examples_root();
|
|
let mut policies = Vec::new();
|
|
discover(&root, &mut policies);
|
|
policies.sort();
|
|
assert!(
|
|
!policies.is_empty(),
|
|
"no example policies found under {}",
|
|
root.display()
|
|
);
|
|
|
|
for path in &policies {
|
|
let yaml = std::fs::read_to_string(path).expect("read policy");
|
|
let policy = parse_sandbox_policy(&yaml)
|
|
.unwrap_or_else(|e| panic!("parse {} failed: {e}", path.display()));
|
|
let opts = MxcMappingOptions {
|
|
containment: "processcontainer".to_owned(),
|
|
proxy_redirect: Some(proxy_addr()),
|
|
..Default::default()
|
|
};
|
|
let result = split_policy(&policy, &opts)
|
|
.unwrap_or_else(|| panic!("split returned None for {}", path.display()));
|
|
let cfg = &result.mxc_config;
|
|
|
|
assert_eq!(
|
|
result.proxy_policy.network_policies,
|
|
policy.network_policies,
|
|
"proxy_policy must carry network rules verbatim for {}",
|
|
path.display()
|
|
);
|
|
assert_eq!(
|
|
result.proxy_policy.version,
|
|
policy.version,
|
|
"proxy_policy must preserve version for {}",
|
|
path.display()
|
|
);
|
|
validate_sandbox_policy(&result.proxy_policy).unwrap_or_else(|e| {
|
|
panic!("trimmed policy must validate for {}: {e:?}", path.display())
|
|
});
|
|
let serialized = serialize_sandbox_policy(&result.proxy_policy)
|
|
.unwrap_or_else(|e| panic!("serialize trimmed policy for {}: {e}", path.display()));
|
|
let round_trip = parse_sandbox_policy(&serialized)
|
|
.unwrap_or_else(|e| panic!("parse trimmed round-trip for {}: {e}", path.display()));
|
|
assert_eq!(
|
|
round_trip,
|
|
result.proxy_policy,
|
|
"trimmed policy must round-trip for {}",
|
|
path.display()
|
|
);
|
|
|
|
if let Some(fs) = &policy.filesystem {
|
|
assert_eq!(
|
|
str_list(&cfg["filesystem"]["readwritePaths"]),
|
|
fs.read_write,
|
|
"split readwrite mismatch for {}",
|
|
path.display()
|
|
);
|
|
assert_eq!(
|
|
str_list(&cfg["filesystem"]["readonlyPaths"]),
|
|
fs.read_only,
|
|
"split readonly mismatch for {}",
|
|
path.display()
|
|
);
|
|
} else {
|
|
assert!(str_list(&cfg["filesystem"]["readwritePaths"]).is_empty());
|
|
assert!(str_list(&cfg["filesystem"]["readonlyPaths"]).is_empty());
|
|
}
|
|
|
|
assert_eq!(cfg["network"]["defaultPolicy"], "block");
|
|
assert!(str_list(&cfg["network"]["allowedHosts"]).is_empty());
|
|
// MXC 0.6.0-alpha accepts only {"proxy": {"localhost": N}}.
|
|
assert_eq!(cfg["network"]["proxy"]["localhost"], 18080);
|
|
assert!(cfg["network"]["proxy"].get("host").is_none());
|
|
assert!(cfg["network"]["proxy"].get("port").is_none());
|
|
let errors: Vec<_> = result
|
|
.loss
|
|
.iter()
|
|
.filter(|item| item.severity == "error")
|
|
.collect();
|
|
if policy.network_middlewares.is_empty() {
|
|
assert!(
|
|
errors.is_empty(),
|
|
"processcontainer split must not emit error losses for {}: {:?}",
|
|
path.display(),
|
|
result.loss
|
|
);
|
|
} else {
|
|
assert_eq!(
|
|
errors.len(),
|
|
1,
|
|
"middleware policy must have one fail-closed loss for {}: {:?}",
|
|
path.display(),
|
|
result.loss
|
|
);
|
|
assert_eq!(errors[0].path, "network_middlewares");
|
|
}
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn quickstart_coarse_mapping() {
|
|
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
|
|
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
|
|
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
|
|
let result = map_to_mxc(&policy, &MxcMappingOptions::default());
|
|
let cfg = &result.config;
|
|
|
|
assert_eq!(
|
|
str_list(&cfg["network"]["allowedHosts"]),
|
|
vec!["api.github.com".to_owned()]
|
|
);
|
|
assert_eq!(
|
|
str_list(&cfg["filesystem"]["readwritePaths"]),
|
|
vec!["/sandbox", "/tmp", "/dev/null"]
|
|
);
|
|
assert_eq!(cfg["containment"], "bubblewrap");
|
|
|
|
// The github_api endpoint loses port, protocol, access, and binary scope.
|
|
let has = |severity: &str, needle: &str| {
|
|
result
|
|
.loss
|
|
.iter()
|
|
.any(|i| i.severity == severity && i.path.contains(needle))
|
|
};
|
|
assert!(has("error", "endpoints[0].port"), "expected port loss");
|
|
assert!(
|
|
has("error", "endpoints[0].protocol"),
|
|
"expected protocol loss"
|
|
);
|
|
assert!(
|
|
has("error", "endpoints[0].access"),
|
|
"expected access preset loss"
|
|
);
|
|
assert!(
|
|
has("error", "binaries[0].path"),
|
|
"expected binary-scope loss"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn split_policy_routes_network_to_proxy() {
|
|
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
|
|
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
|
|
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
|
|
|
|
let opts = MxcMappingOptions {
|
|
containment: "processcontainer".to_owned(),
|
|
proxy_redirect: Some("127.0.0.2:8080".parse().unwrap()),
|
|
..Default::default()
|
|
};
|
|
let result = split_policy(&policy, &opts).expect("split_policy returns Some when addr is set");
|
|
let cfg = &result.mxc_config;
|
|
|
|
// Proxy redirect is emitted. 127.0.0.2 is not the loopback 127.0.0.1 so
|
|
// the mapper records an error loss and omits the proxy block entirely.
|
|
// (MXC 0.6.0-alpha can only encode {"localhost": N}; non-127.0.0.1 is
|
|
// not representable.)
|
|
assert!(
|
|
cfg["network"].get("proxy").is_none() || cfg["network"]["proxy"].is_null(),
|
|
"non-127.0.0.1 redirect must NOT produce a proxy block: {:?}",
|
|
cfg["network"].get("proxy")
|
|
);
|
|
let has_proxy_loss = result
|
|
.loss
|
|
.iter()
|
|
.any(|i| i.path == "network.proxy" && i.severity == "error");
|
|
assert!(
|
|
has_proxy_loss,
|
|
"non-127.0.0.1 redirect must produce an error loss item"
|
|
);
|
|
|
|
// Direct egress is blocked; unsupported host-list fields are omitted and
|
|
// the proxy enforces the full list.
|
|
assert_eq!(cfg["network"]["defaultPolicy"], "block");
|
|
assert!(cfg["network"].get("allowedHosts").is_none());
|
|
assert!(cfg["network"].get("blockedHosts").is_none());
|
|
|
|
// Filesystem grants are preserved unchanged.
|
|
assert_eq!(
|
|
str_list(&cfg["filesystem"]["readwritePaths"]),
|
|
policy.filesystem.as_ref().unwrap().read_write
|
|
);
|
|
|
|
// Network policy is returned verbatim for the proxy.
|
|
assert_eq!(
|
|
result.proxy_policy.network_policies, policy.network_policies,
|
|
"proxy_policy must carry all network rules verbatim"
|
|
);
|
|
assert_eq!(result.proxy_policy.version, policy.version);
|
|
assert!(
|
|
result.proxy_policy.filesystem.is_none(),
|
|
"proxy_policy must not carry filesystem rules"
|
|
);
|
|
|
|
// No binary-scope, port, or protocol losses — those are delegated to the proxy.
|
|
let net_losses: Vec<_> = result
|
|
.loss
|
|
.iter()
|
|
.filter(|i| i.path.starts_with("network_policies") && i.severity != "info")
|
|
.collect();
|
|
assert!(
|
|
net_losses.is_empty(),
|
|
"split path must not generate lossy network items: {net_losses:?}"
|
|
);
|
|
assert!(result.loss.iter().any(|i| {
|
|
i.path == "network_policies" && i.severity == "info" && i.message.contains("delegated")
|
|
}));
|
|
}
|
|
|
|
#[test]
|
|
fn split_policy_returns_none_without_proxy_addr() {
|
|
let opts = MxcMappingOptions::default();
|
|
let policy = parse_sandbox_policy("").unwrap_or_default();
|
|
assert!(
|
|
split_policy(&policy, &opts).is_none(),
|
|
"split_policy must return None when proxy_redirect is not set"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn split_policy_deterministic() {
|
|
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
|
|
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
|
|
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
|
|
let opts = MxcMappingOptions {
|
|
containment: "processcontainer".to_owned(),
|
|
proxy_redirect: Some("127.0.0.1:9999".parse().unwrap()),
|
|
..Default::default()
|
|
};
|
|
let a = split_policy(&policy, &opts).unwrap();
|
|
let b = split_policy(&policy, &opts).unwrap();
|
|
assert_eq!(
|
|
a.mxc_config, b.mxc_config,
|
|
"split_policy must be deterministic"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn split_policy_rejects_proxy_redirect_on_isolation_session() {
|
|
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
|
|
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
|
|
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
|
|
let opts = MxcMappingOptions {
|
|
containment: "isolation_session".to_owned(),
|
|
proxy_redirect: Some(proxy_addr()),
|
|
..Default::default()
|
|
};
|
|
let result = split_policy(&policy, &opts).unwrap();
|
|
let errors: Vec<_> = result
|
|
.loss
|
|
.iter()
|
|
.filter(|i| i.severity == "error")
|
|
.collect();
|
|
assert_eq!(
|
|
errors.len(),
|
|
1,
|
|
"expected one containment error: {errors:?}"
|
|
);
|
|
assert_eq!(errors[0].path, "containment");
|
|
assert!(errors[0].message.contains("MXC M1"));
|
|
assert!(result.mxc_config["network"].get("proxy").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn network_only_policy_has_empty_filesystem() {
|
|
// policy-advisor is a network-only seed (no filesystem_policy).
|
|
let path = examples_root().join("policy-advisor/sandbox-policy.yaml");
|
|
let yaml = std::fs::read_to_string(&path).expect("read policy-advisor");
|
|
let policy = parse_sandbox_policy(&yaml).expect("parse policy-advisor");
|
|
let result = map_to_mxc(&policy, &MxcMappingOptions::default());
|
|
let cfg = &result.config;
|
|
|
|
assert!(str_list(&cfg["filesystem"]["readwritePaths"]).is_empty());
|
|
assert!(str_list(&cfg["filesystem"]["readonlyPaths"]).is_empty());
|
|
assert_eq!(
|
|
str_list(&cfg["network"]["allowedHosts"]),
|
|
vec!["api.anthropic.com".to_owned()]
|
|
);
|
|
}
|
|
|
|
// ── New tests: proxy JSON shape and non-127.0.0.1 guard ──────────────────────
|
|
|
|
#[test]
|
|
fn split_with_loopback_addr_emits_localhost_port_shape() {
|
|
// MXC 0.6.0-alpha accepts ONLY {"proxy": {"localhost": N}}.
|
|
// Verified against the real wxc-exec 0.6.0-alpha binary via --dry-run.
|
|
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
|
|
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
|
|
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
|
|
|
|
let opts = MxcMappingOptions {
|
|
containment: "processcontainer".to_owned(),
|
|
proxy_redirect: Some("127.0.0.1:18080".parse().unwrap()),
|
|
..Default::default()
|
|
};
|
|
let result = split_policy(&policy, &opts).expect("split returns Some");
|
|
let cfg = &result.mxc_config;
|
|
|
|
assert_eq!(
|
|
cfg["network"]["proxy"]["localhost"], 18080,
|
|
"proxy must use {{\"localhost\": N}} shape"
|
|
);
|
|
assert!(
|
|
cfg["network"]["proxy"].get("host").is_none(),
|
|
"proxy must not contain 'host' key"
|
|
);
|
|
assert!(
|
|
cfg["network"]["proxy"].get("port").is_none(),
|
|
"proxy must not contain 'port' key"
|
|
);
|
|
// No error losses — 127.0.0.1 is representable.
|
|
assert!(
|
|
result.loss.iter().all(|i| i.severity != "error"),
|
|
"127.0.0.1 proxy must not emit error losses: {:?}",
|
|
result
|
|
.loss
|
|
.iter()
|
|
.filter(|i| i.severity == "error")
|
|
.collect::<Vec<_>>()
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn split_with_non_loopback_addr_emits_error_loss_and_no_proxy_block() {
|
|
// Non-127.0.0.1 redirect addresses are not representable in MXC 0.6.0-alpha.
|
|
// The mapper must record an error loss and omit the proxy block.
|
|
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
|
|
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
|
|
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
|
|
|
|
let opts = MxcMappingOptions {
|
|
containment: "processcontainer".to_owned(),
|
|
proxy_redirect: Some("127.0.0.5:18080".parse().unwrap()),
|
|
..Default::default()
|
|
};
|
|
let result = split_policy(&policy, &opts).expect("split returns Some");
|
|
let cfg = &result.mxc_config;
|
|
|
|
// Proxy block must be absent.
|
|
assert!(
|
|
cfg["network"].get("proxy").is_none() || cfg["network"]["proxy"].is_null(),
|
|
"non-127.0.0.1 redirect must not produce a proxy block: {:?}",
|
|
cfg["network"].get("proxy")
|
|
);
|
|
|
|
// An error loss for "network.proxy" must be present.
|
|
let proxy_loss = result
|
|
.loss
|
|
.iter()
|
|
.find(|i| i.path == "network.proxy" && i.severity == "error");
|
|
assert!(
|
|
proxy_loss.is_some(),
|
|
"non-127.0.0.1 redirect must produce an error loss item on network.proxy: {:?}",
|
|
result.loss
|
|
);
|
|
let loss = proxy_loss.unwrap();
|
|
assert_eq!(loss.openshell_feature, "per-sandbox egress attribution");
|
|
assert!(
|
|
loss.message.contains("localhost"),
|
|
"loss message should mention 'localhost': {}",
|
|
loss.message
|
|
);
|
|
}
|