Skip to content

Commit 01053b2

Browse files
committed
fix(mxc): bound forwarding and isolate sandbox trust staging
Signed-off-by: Prekshi Vyas <[email protected]>
1 parent 394e0dc commit 01053b2

10 files changed

Lines changed: 497 additions & 107 deletions

File tree

‎.agents/skills/implement-openshell-policy-mapper/SKILL.md‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ the splitter.
3939
consumption with no OpenShell proxy in the loop.
4040
- `split_policy` — *lossless / Pattern C*: MXC gets filesystem + containment +
4141
`127.0.0.1/32`-only egress with direct Internet set to `deny`; the **full**
42-
`network_policies` is preserved verbatim in
42+
`network_policies` and `network_middlewares` are preserved verbatim in
4343
a trimmed `SandboxPolicy` for the host CONNECT proxy. Network items that are
4444
`error` losses in the coarse map are **delegated, not lost** here.
4545
4. **Two consumers of one policy.** The host proxy evaluates the *trimmed original
@@ -256,14 +256,16 @@ pub fn split_policy(policy: &SandboxPolicy, opts: &MxcMappingOptions) -> Option<
256256
unsupported on `isolation_session`. Never emit a config
257257
MXC will reject silently.
258258
- `proxy_policy` = `SandboxPolicy { version: source.version.clone(),
259-
network_policies: source.network_policies.clone(), ..Default::default() }` — drop
259+
network_policies: source.network_policies.clone(),
260+
network_middlewares: source.network_middlewares.clone(), ..Default::default() }` — drop
260261
`filesystem`/`landlock`/`process`/`ui` (MXC's job), keep network **verbatim**. A
261262
network-only policy is valid (`validate_sandbox_policy` checks the other sections
262263
only if present).
263264
- **No network loss items** — delegation isn't loss. Emit one `info` item
264265
("N network rule(s) delegated to the OpenShell host CONNECT proxy") so the report
265266
accounts for every section. Filesystem mapping + its advisories same as Step 4.
266267
- Invariants (test all): `proxy_policy.network_policies == source.network_policies`;
268+
`proxy_policy.network_middlewares == source.network_middlewares`;
267269
`proxy_policy.version == source.version`; `validate_sandbox_policy(&proxy_policy)`
268270
Ok; round-trip `parse(serialize(proxy_policy)) == proxy_policy`; zero `error`
269271
items on `processcontainer`; deterministic.

‎architecture/mxc-compute-driver.md‎

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -314,7 +314,10 @@ placeholders and non-secret values into `process.env`, base64-encodes the config
314314
then runs the phases. The persisted public sandbox retains its base policy and
315315
contains no credential resolver state. For governed egress, `egress_proxy_addr` is a loopback seed: the driver
316316
keeps the IP (`127.0.0.1`) and binds port `0` to reserve a fresh ephemeral port per sandbox before writing
317-
the proxy URL into MXC config.
317+
the proxy URL into the agent environment, outside MXC JSON. Public CA files are
318+
staged under `share_dir/.openshell-proxy/<sandbox-id>/` so sandboxes sharing a
319+
directory do not overwrite each other's trust material. CA staging rejects an
320+
empty `share_dir`.
318321

319322
```mermaid
320323
sequenceDiagram
@@ -499,10 +502,11 @@ complexity), and Windows Sandbox/Hyper-V (heavy, admin). MXC is OS-native, no VM
499502
`processcontainer` as the default backend; `isolation_session` opt-in** for state-aware multi-exec. Requires
500503
a hard runtime check for Windows 11 build ≥ 26100, and a dependency on `wxc-exec.exe` being present.
501504

502-
**D2 — Do not port the supervisor; use Pattern C (host-side proxy).** Of the three patterns —
503-
**A** host-side surrogate, **B** in-sandbox binary via folder share, **C** host-side proxy + MXC
504-
native MXC 0.8 redirect — the design implements **A and C** and **no in-sandbox OpenShell binary at any
505-
phase**. The host CONNECT proxy lives inside `openshell-driver-mxc`, reusing the existing
505+
**D2 — Do not port the supervisor; use Pattern C (host-side proxy).** The three patterns are
506+
**A** host-side surrogate, **B** in-sandbox binary via folder share, and **C** host-side proxy
507+
with MXC loopback-only network rules. The driver uses Pattern C and injects `HTTP_PROXY`/`HTTPS_PROXY` and trust
508+
paths outside MXC JSON. The lightweight supervisor relay runs inside the sandbox;
509+
the Linux supervisor is not ported. The host CONNECT proxy lives inside `openshell-driver-mxc`, reusing the existing
506510
proxy/OPA/L7/router code unchanged. `isolation_session` remains unsupported for governed egress because it cannot enforce the same loopback-only path; until that changes, default to `processcontainer`.
507511

508512
**D3 — Keep the gateway as a long-lived Windows Service.** Ship `openshell-gateway.exe` as a Windows Service
@@ -627,7 +631,7 @@ lane is the prerequisite for all of it).
627631
| **Surrogate** | A host-side stand-in for the supervisor (Pattern A surrogate). **Not used** in this design. |
628632
| **CONNECT proxy** | OpenShell's forward proxy (OPA + L7 + inference router + privacy router). On Windows it runs on the host inside the driver process. |
629633
| **Proxy environment** | `HTTP_PROXY`/`HTTPS_PROXY` and staged public CA paths injected for proxy-aware clients; `NO_PROXY` is cleared. |
630-
| **Pattern A / B / C** | Host surrogate / in-sandbox binary / host proxy + redirect. This design uses **A + C**. |
634+
| **Pattern A / B / C** | Host surrogate / in-sandbox binary / host proxy with MXC loopback-only rules and proxy environment injection. Governed egress uses Pattern C. |
631635
| **Egress** | Outbound network traffic from the sandbox; the thing OpenShell governs. |
632636
| **MXC** | Microsoft eXecution Container — sandboxes code via Windows AppContainer (and LXC/Seatbelt elsewhere). |
633637
| **`wxc-exec`** | MXC's Windows CLI; one process per lifecycle phase. |

‎crates/openshell-driver-mxc/examples/run-openclaw-forward-test.ps1‎

Lines changed: 68 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -506,74 +506,77 @@ try {
506506
$savedOpenClawConfigPath = $env:OPENCLAW_CONFIG_PATH
507507
$savedOpenClawStateDir = $env:OPENCLAW_STATE_DIR
508508
$cleanOpenClawStateDir = Join-Path $ShareDir "home\.openclaw"
509-
$env:OPENCLAW_CONFIG_PATH = Join-Path $cleanOpenClawStateDir "openclaw.json"
510-
$env:OPENCLAW_STATE_DIR = $cleanOpenClawStateDir
511-
# Bumped from 6 -> 14 (2026-09-10): on this box OpenClaw's actual startup
512-
# (port bind -> SQLite agent-db open -> HTTP server listening -> "ready")
513-
# measured ~90s wall clock, longer than 6 attempts' ~60s budget covers --
514-
# the sandbox was torn down mid-startup before the health check could ever
515-
# succeed. 14 attempts at up to 10s each comfortably covers 90s+ without
516-
# a fixed sleep that would undershoot on a slower box.
517-
$healthAttempts = 14
518-
for ($attempt = 1; $attempt -le $healthAttempts; $attempt++) {
519-
$healthRaw = & $NodeExePath @healthArgs 2>&1
520-
$healthRaw | Out-File (Join-Path $resultDir "openclaw-health-raw.txt") -Encoding UTF8
521-
# --json output is PRETTY-PRINTED (multi-line), not compact -- extract from
522-
# the first '{' to the last '}' across the whole output rather than
523-
# assuming any single line is a complete JSON document.
524-
$rawJoined = ($healthRaw | ForEach-Object { [string]$_ }) -join "`n"
525-
$startIdx = $rawJoined.IndexOf('{')
526-
$endIdx = $rawJoined.LastIndexOf('}')
527-
$healthJson = $null
528-
if ($startIdx -ge 0 -and $endIdx -gt $startIdx) {
529-
$jsonText = $rawJoined.Substring($startIdx, $endIdx - $startIdx + 1)
530-
try { $healthJson = $jsonText | ConvertFrom-Json } catch { Info "could not parse health JSON: $($_.Exception.Message)" }
509+
try {
510+
$env:OPENCLAW_CONFIG_PATH = Join-Path $cleanOpenClawStateDir "openclaw.json"
511+
$env:OPENCLAW_STATE_DIR = $cleanOpenClawStateDir
512+
# Bumped from 6 -> 14 (2026-09-10): on this box OpenClaw's actual startup
513+
# (port bind -> SQLite agent-db open -> HTTP server listening -> "ready")
514+
# measured ~90s wall clock, longer than 6 attempts' ~60s budget covers --
515+
# the sandbox was torn down mid-startup before the health check could ever
516+
# succeed. 14 attempts at up to 10s each comfortably covers 90s+ without
517+
# a fixed sleep that would undershoot on a slower box.
518+
$healthAttempts = 14
519+
for ($attempt = 1; $attempt -le $healthAttempts; $attempt++) {
520+
$healthRaw = & $NodeExePath @healthArgs 2>&1
521+
$healthRaw | Out-File (Join-Path $resultDir "openclaw-health-raw.txt") -Encoding UTF8
522+
# --json output is PRETTY-PRINTED (multi-line), not compact -- extract from
523+
# the first '{' to the last '}' across the whole output rather than
524+
# assuming any single line is a complete JSON document.
525+
$rawJoined = ($healthRaw | ForEach-Object { [string]$_ }) -join "`n"
526+
$startIdx = $rawJoined.IndexOf('{')
527+
$endIdx = $rawJoined.LastIndexOf('}')
528+
$healthJson = $null
529+
if ($startIdx -ge 0 -and $endIdx -gt $startIdx) {
530+
$jsonText = $rawJoined.Substring($startIdx, $endIdx - $startIdx + 1)
531+
try { $healthJson = $jsonText | ConvertFrom-Json } catch { Info "could not parse health JSON: $($_.Exception.Message)" }
532+
}
533+
if ($healthJson -and $healthJson.ok -eq $true) {
534+
$passed = $true
535+
Ok "gateway health: ok=true (attempt $attempt/$healthAttempts)"
536+
break
537+
} else {
538+
Info "attempt $attempt/${healthAttempts}: no ok=true response yet$(if ($attempt -lt $healthAttempts) { ' -- retrying (still inside OpenClaws own startup-grace window)' })"
539+
}
531540
}
532-
if ($healthJson -and $healthJson.ok -eq $true) {
533-
$passed = $true
534-
Ok "gateway health: ok=true (attempt $attempt/$healthAttempts)"
535-
break
536-
} else {
537-
Info "attempt $attempt/${healthAttempts}: no ok=true response yet$(if ($attempt -lt $healthAttempts) { ' -- retrying (still inside OpenClaws own startup-grace window)' })"
541+
if (-not $passed) {
542+
Bad "gateway health did not report ok=true after $healthAttempts attempts"
543+
$healthRaw | ForEach-Object { Info "$_" }
538544
}
539-
}
540-
if (-not $passed) {
541-
Bad "gateway health did not report ok=true after $healthAttempts attempts"
542-
$healthRaw | ForEach-Object { Info "$_" }
543-
}
544545

545-
# Treat egress as a qualification gate, not just diagnostic output. The
546-
# capture script runs these probes before importing OpenClaw, so the record
547-
# is available by the time gateway health succeeds.
548-
Step "Verify governed egress evidence"
549-
$capturePath = Join-Path $ShareDir "openclaw-capture.log"
550-
$proofMatch = Select-String -Path $capturePath -Pattern '^\[egress-proof\] (?<json>\{.*\})$' -ErrorAction SilentlyContinue | Select-Object -Last 1
551-
$proof = $null
552-
if ($proofMatch) {
553-
try { $proof = $proofMatch.Matches[0].Groups['json'].Value | ConvertFrom-Json }
554-
catch { Info "could not parse egress proof JSON: $($_.Exception.Message)" }
555-
}
556-
$proofPassed = $proof -and
557-
$proof.proxyConfigured -eq $true -and
558-
$proof.allowedViaProxy.connected -eq $true -and
559-
$proof.deniedViaProxy.connected -eq $false -and
560-
$proof.directInternetBypass.connected -eq $false
561-
if ($proofPassed) {
562-
Ok "allowed host passed proxy; denied host and direct Internet bypass were blocked"
563-
Info "unrelated host loopback reachable: $($proof.unrelatedHostLoopback.connected) (known limitation)"
564-
} else {
565-
$passed = $false
566-
Bad "governed egress proof failed or was not recorded"
567-
}
568-
if ($null -eq $savedOpenClawConfigPath) {
569-
Remove-Item Env:OPENCLAW_CONFIG_PATH -ErrorAction SilentlyContinue
570-
} else {
571-
$env:OPENCLAW_CONFIG_PATH = $savedOpenClawConfigPath
572-
}
573-
if ($null -eq $savedOpenClawStateDir) {
574-
Remove-Item Env:OPENCLAW_STATE_DIR -ErrorAction SilentlyContinue
575-
} else {
576-
$env:OPENCLAW_STATE_DIR = $savedOpenClawStateDir
546+
# Treat egress as a qualification gate, not just diagnostic output. The
547+
# capture script runs these probes before importing OpenClaw, so the record
548+
# is available by the time gateway health succeeds.
549+
Step "Verify governed egress evidence"
550+
$capturePath = Join-Path $ShareDir "openclaw-capture.log"
551+
$proofMatch = Select-String -Path $capturePath -Pattern '^\[egress-proof\] (?<json>\{.*\})$' -ErrorAction SilentlyContinue | Select-Object -Last 1
552+
$proof = $null
553+
if ($proofMatch) {
554+
try { $proof = $proofMatch.Matches[0].Groups['json'].Value | ConvertFrom-Json }
555+
catch { Info "could not parse egress proof JSON: $($_.Exception.Message)" }
556+
}
557+
$proofPassed = $proof -and
558+
$proof.proxyConfigured -eq $true -and
559+
$proof.allowedViaProxy.connected -eq $true -and
560+
$proof.deniedViaProxy.connected -eq $false -and
561+
$proof.directInternetBypass.connected -eq $false
562+
if ($proofPassed) {
563+
Ok "allowed host passed proxy; denied host and direct Internet bypass were blocked"
564+
Info "unrelated host loopback reachable: $($proof.unrelatedHostLoopback.connected) (known limitation)"
565+
} else {
566+
$passed = $false
567+
Bad "governed egress proof failed or was not recorded"
568+
}
569+
} finally {
570+
if ($null -eq $savedOpenClawConfigPath) {
571+
Remove-Item Env:OPENCLAW_CONFIG_PATH -ErrorAction SilentlyContinue
572+
} else {
573+
$env:OPENCLAW_CONFIG_PATH = $savedOpenClawConfigPath
574+
}
575+
if ($null -eq $savedOpenClawStateDir) {
576+
Remove-Item Env:OPENCLAW_STATE_DIR -ErrorAction SilentlyContinue
577+
} else {
578+
$env:OPENCLAW_STATE_DIR = $savedOpenClawStateDir
579+
}
577580
}
578581
}
579582
catch {

‎crates/openshell-driver-mxc/src/driver.rs‎

Lines changed: 84 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -527,11 +527,30 @@ fn append_tls_env_vars(env: &mut Vec<String>, ca_paths: Option<&(PathBuf, PathBu
527527
fn stage_tls_ca_files(
528528
ca_paths: Option<&(PathBuf, PathBuf)>,
529529
share_dir: &str,
530+
sandbox_id: &str,
530531
) -> std::io::Result<Option<(PathBuf, PathBuf)>> {
531532
let Some((ca_cert_path, combined_bundle_path)) = ca_paths else {
532533
return Ok(None);
533534
};
534-
let target_dir = PathBuf::from(share_dir).join(".openshell-proxy");
535+
if share_dir.trim().is_empty() {
536+
return Err(std::io::Error::new(
537+
std::io::ErrorKind::InvalidInput,
538+
"share_dir must be set when staging proxy CA files",
539+
));
540+
}
541+
if sandbox_id.is_empty()
542+
|| !sandbox_id
543+
.bytes()
544+
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
545+
{
546+
return Err(std::io::Error::new(
547+
std::io::ErrorKind::InvalidInput,
548+
"sandbox_id must be a non-empty alphanumeric, hyphen or underscore component",
549+
));
550+
}
551+
let target_dir = PathBuf::from(share_dir)
552+
.join(".openshell-proxy")
553+
.join(sandbox_id);
535554
std::fs::create_dir_all(&target_dir)?;
536555
let staged_ca = target_dir.join("openshell-ca.pem");
537556
let staged_bundle = target_dir.join("ca-bundle.pem");
@@ -1409,7 +1428,7 @@ async fn run_lifecycle(
14091428
// DACL is already granted by the policy, so HTTPS clients can authenticate
14101429
// the OpenShell inspection proxy without broadening filesystem access.
14111430
let agent_proxy_ca_paths = if config.pc_minimal_env && host_proxy_ca_paths.is_some() {
1412-
match stage_tls_ca_files(host_proxy_ca_paths.as_ref(), &config.share_dir) {
1431+
match stage_tls_ca_files(host_proxy_ca_paths.as_ref(), &config.share_dir, &sandbox_id) {
14131432
Ok(paths) => paths,
14141433
Err(error) => {
14151434
set_failed(
@@ -2577,14 +2596,77 @@ mod lifecycle_tests {
25772596
let staged = stage_tls_ca_files(
25782597
Some(&(ca, bundle)),
25792598
share.path().to_str().expect("UTF-8 test path"),
2599+
"sandbox-a",
25802600
)
25812601
.unwrap()
25822602
.expect("staged paths");
25832603

2604+
assert_eq!(
2605+
staged.0.parent().unwrap(),
2606+
share.path().join(".openshell-proxy").join("sandbox-a")
2607+
);
25842608
assert_eq!(std::fs::read(staged.0).unwrap(), b"ca");
25852609
assert_eq!(std::fs::read(staged.1).unwrap(), b"bundle");
25862610
}
25872611

2612+
#[test]
2613+
fn tls_ca_staging_keeps_sandboxes_in_the_same_share_independent() {
2614+
let source = tempfile::tempdir().unwrap();
2615+
let share = tempfile::tempdir().unwrap();
2616+
let paths = (
2617+
source.path().join("ca.pem"),
2618+
source.path().join("bundle.pem"),
2619+
);
2620+
std::fs::write(&paths.0, b"first-ca").unwrap();
2621+
std::fs::write(&paths.1, b"first-bundle").unwrap();
2622+
let first = stage_tls_ca_files(Some(&paths), share.path().to_str().unwrap(), "sandbox-a")
2623+
.unwrap()
2624+
.unwrap();
2625+
std::fs::write(&paths.0, b"second-ca").unwrap();
2626+
std::fs::write(&paths.1, b"second-bundle").unwrap();
2627+
let second = stage_tls_ca_files(Some(&paths), share.path().to_str().unwrap(), "sandbox-b")
2628+
.unwrap()
2629+
.unwrap();
2630+
2631+
assert_ne!(first, second);
2632+
assert_eq!(std::fs::read(first.0).unwrap(), b"first-ca");
2633+
assert_eq!(std::fs::read(first.1).unwrap(), b"first-bundle");
2634+
assert_eq!(std::fs::read(second.0).unwrap(), b"second-ca");
2635+
assert_eq!(std::fs::read(second.1).unwrap(), b"second-bundle");
2636+
}
2637+
2638+
#[test]
2639+
fn tls_ca_staging_rejects_empty_shares_and_unsafe_sandbox_components() {
2640+
let share = tempfile::tempdir().unwrap();
2641+
let paths = (PathBuf::from("unused-ca"), PathBuf::from("unused-bundle"));
2642+
for empty in ["", " ", "\t"] {
2643+
assert_eq!(
2644+
stage_tls_ca_files(Some(&paths), empty, "sandbox-a")
2645+
.unwrap_err()
2646+
.kind(),
2647+
std::io::ErrorKind::InvalidInput
2648+
);
2649+
}
2650+
for id in [
2651+
"",
2652+
".",
2653+
"..",
2654+
"../outside",
2655+
"..\\outside",
2656+
"C:\\outside",
2657+
"file:stream",
2658+
] {
2659+
assert_eq!(
2660+
stage_tls_ca_files(Some(&paths), share.path().to_str().unwrap(), id)
2661+
.unwrap_err()
2662+
.kind(),
2663+
std::io::ErrorKind::InvalidInput
2664+
);
2665+
}
2666+
assert_eq!(std::fs::read_dir(share.path()).unwrap().count(), 0);
2667+
assert_eq!(stage_tls_ca_files(None, "", "").unwrap(), None);
2668+
}
2669+
25882670
#[test]
25892671
fn proxy_env_replaces_inherited_values_and_clears_bypass_rules() {
25902672
let mut env = vec![

0 commit comments

Comments
 (0)