Skip to content

Commit 96d6afa

Browse files
committed
feat(driver-mxc): implement lossless split_policy for proxy-delegated egress
Signed-off-by: Giedrius Burachas <[email protected]>
1 parent f22f9c7 commit 96d6afa

5 files changed

Lines changed: 283 additions & 8 deletions

File tree

‎crates/openshell-driver-mxc/examples/policy-to-mxc.rs‎

Lines changed: 95 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ mod imp {
2929
use clap::Parser;
3030
use openshell_driver_mxc::{
3131
DEFAULT_COMMAND, DEFAULT_CONTAINMENT, DEFAULT_MXC_VERSION, LossItem, MxcMappingOptions,
32-
build_loss_report, map_to_mxc, render_readme,
32+
build_loss_report, map_to_mxc, render_readme, split_policy,
3333
};
3434
use serde_json::Value;
3535

@@ -81,11 +81,41 @@ mod imp {
8181
/// Emit `OpenShell` wildcard hosts into `allowedHosts` despite lossiness.
8282
#[arg(long)]
8383
allow_wildcards: bool,
84+
85+
/// Run the lossless split instead of the coarse map.
86+
///
87+
/// Requires `--proxy-port`. Prints the MXC config (with proxy redirect
88+
/// and empty `allowedHosts`) and the trimmed proxy policy side-by-side.
89+
#[arg(long)]
90+
split: bool,
91+
92+
/// Localhost port the `OpenShell` CONNECT proxy listens on (required with `--split`).
93+
#[arg(long)]
94+
proxy_port: Option<u16>,
8495
}
8596

8697
pub fn run() -> Result<()> {
8798
let args = Args::parse();
8899

100+
if args.split {
101+
let port = args
102+
.proxy_port
103+
.ok_or_else(|| anyhow!("--proxy-port is required with --split"))?;
104+
let policy_path = args
105+
.policy
106+
.as_ref()
107+
.ok_or_else(|| anyhow!("--policy is required with --split"))?;
108+
let stem = policy_path
109+
.file_stem()
110+
.unwrap_or_default()
111+
.to_string_lossy()
112+
.into_owned();
113+
let slug = args.container_id.clone().unwrap_or(stem);
114+
let mut opts = build_options(&args, &slug);
115+
opts.proxy_localhost_port = Some(port);
116+
return show_split(policy_path, &opts);
117+
}
118+
89119
if let Some(examples_root) = &args.examples_root {
90120
let mut examples = discover_example_policies(examples_root)?;
91121
if examples.is_empty() {
@@ -211,6 +241,70 @@ mod imp {
211241
Ok(())
212242
}
213243

244+
// -----------------------------------------------------------------------
245+
// Lossless-split display
246+
// -----------------------------------------------------------------------
247+
248+
fn show_split(policy_path: &Path, opts: &MxcMappingOptions) -> Result<()> {
249+
let content = std::fs::read_to_string(policy_path)
250+
.with_context(|| format!("reading {}", policy_path.display()))?;
251+
let policy = openshell_policy::parse_sandbox_policy(&content)
252+
.map_err(|e| anyhow!("parsing {}: {e}", policy_path.display()))?;
253+
254+
let result = split_policy(&policy, opts)
255+
.ok_or_else(|| anyhow!("split_policy returned None — is --proxy-port set?"))?;
256+
257+
println!("=== MXC ContainerConfig (filesystem + proxy redirect) ===");
258+
println!("{}", serde_json::to_string_pretty(&result.mxc_config)?);
259+
260+
println!();
261+
println!("=== Proxy policy (preserved for OpenShell fine-grained enforcement) ===");
262+
if result.proxy_policy.network_policies.is_empty() {
263+
println!(" (no network_policies — nothing for the proxy to enforce)");
264+
} else {
265+
let mut rules: Vec<_> = result.proxy_policy.network_policies.iter().collect();
266+
rules.sort_by_key(|(k, _)| k.as_str());
267+
for (name, rule) in rules {
268+
println!(" rule: {name}");
269+
for ep in &rule.endpoints {
270+
let ports = if ep.ports.is_empty() {
271+
String::new()
272+
} else {
273+
format!(":{}", ep.ports.iter().map(|p| p.to_string()).collect::<Vec<_>>().join(","))
274+
};
275+
println!(
276+
" endpoint: {}{} protocol={} tls={} access={} enforcement={}",
277+
ep.host, ports,
278+
if ep.protocol.is_empty() { "-" } else { &ep.protocol },
279+
if ep.tls.is_empty() { "-" } else { &ep.tls },
280+
if ep.access.is_empty() { "-" } else { &ep.access },
281+
if ep.enforcement.is_empty() { "-" } else { &ep.enforcement },
282+
);
283+
if !ep.rules.is_empty() {
284+
println!(" allow rules: {}", ep.rules.len());
285+
}
286+
if !ep.deny_rules.is_empty() {
287+
println!(" deny rules: {}", ep.deny_rules.len());
288+
}
289+
}
290+
let binaries: Vec<_> = rule.binaries.iter().map(|b| b.path.as_str()).collect();
291+
if !binaries.is_empty() {
292+
println!(" binaries: {}", binaries.join(", "));
293+
}
294+
}
295+
}
296+
297+
if !result.loss.is_empty() {
298+
println!();
299+
println!("=== Filesystem loss items ({} item(s)) ===", result.loss.len());
300+
for item in &result.loss {
301+
println!(" [{}] {}: {}", item.severity, item.path, item.message);
302+
}
303+
}
304+
305+
Ok(())
306+
}
307+
214308
// -----------------------------------------------------------------------
215309
// File discovery & slug helpers
216310
// -----------------------------------------------------------------------

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,5 +37,6 @@ pub use grpc::ComputeDriverService;
3737
#[cfg(target_os = "windows")]
3838
pub use policy_map::{
3939
DEFAULT_COMMAND, DEFAULT_CONTAINMENT, DEFAULT_MXC_VERSION, LossItem, MxcMappingOptions,
40-
MxcMappingResult, OPEN_SHELL_SUPERSET_GAPS, build_loss_report, map_to_mxc, render_readme,
40+
MxcMappingResult, OPEN_SHELL_SUPERSET_GAPS, SplitPolicyResult, build_loss_report, map_to_mxc,
41+
render_readme, split_policy,
4142
};

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

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,116 @@ pub struct MxcMappingResult {
6767
pub loss: Vec<LossItem>,
6868
}
6969

70+
/// Result of the lossless split: the MXC config carries filesystem grants and a
71+
/// proxy redirect; the full network policy is returned unchanged for the
72+
/// `OpenShell` CONNECT proxy to enforce.
73+
#[derive(Clone, Debug)]
74+
pub struct SplitPolicyResult {
75+
/// MXC `ContainerConfig` with filesystem grants and `network.proxy` redirect.
76+
///
77+
/// `network.allowedHosts` is empty — direct egress is blocked at the MXC
78+
/// layer. All outbound connections flow through the proxy; the proxy enforces
79+
/// the full `OpenShell` network policy.
80+
pub mxc_config: Value,
81+
/// Full `OpenShell` network policy preserved verbatim for the host CONNECT
82+
/// proxy. Only `network_policies` is populated; the proxy does not enforce
83+
/// filesystem rules.
84+
pub proxy_policy: SandboxPolicy,
85+
/// Loss items from the filesystem side only. Network rules produce no losses
86+
/// here — they are delegated to the proxy rather than approximated.
87+
pub loss: Vec<LossItem>,
88+
}
89+
7090
/// Map an `OpenShell` policy to a coarse MXC `ContainerConfig`.
7191
pub fn map_to_mxc(policy: &SandboxPolicy, opts: &MxcMappingOptions) -> MxcMappingResult {
7292
let mut loss = Vec::new();
7393
let config = build_mxc_config(policy, opts, &mut loss);
7494
MxcMappingResult { config, loss }
7595
}
7696

97+
/// Lossless split: map filesystem + containment to MXC, delegate network to the
98+
/// `OpenShell` CONNECT proxy.
99+
///
100+
/// The returned [`SplitPolicyResult::mxc_config`] sets `network.proxy` to
101+
/// `127.0.0.1:{proxy_localhost_port}` and leaves `allowedHosts` empty — direct
102+
/// egress is blocked at the MXC layer and all outbound connections flow through
103+
/// the proxy. [`SplitPolicyResult::proxy_policy`] carries the original
104+
/// `network_policies` verbatim; no binary-scope, port, protocol, or wildcard
105+
/// loss items are generated for the network side.
106+
///
107+
/// Returns `None` if `opts.proxy_localhost_port` is not set. Use [`map_to_mxc`]
108+
/// for the standalone coarse path when no proxy is in the loop.
109+
pub fn split_policy(policy: &SandboxPolicy, opts: &MxcMappingOptions) -> Option<SplitPolicyResult> {
110+
let port = opts.proxy_localhost_port?;
111+
let mut loss = Vec::new();
112+
let mxc_config = build_split_mxc_config(policy, opts, port, &mut loss);
113+
let proxy_policy = SandboxPolicy {
114+
network_policies: policy.network_policies.clone(),
115+
..Default::default()
116+
};
117+
Some(SplitPolicyResult {
118+
mxc_config,
119+
proxy_policy,
120+
loss,
121+
})
122+
}
123+
124+
fn build_split_mxc_config(
125+
policy: &SandboxPolicy,
126+
opts: &MxcMappingOptions,
127+
proxy_port: u16,
128+
items: &mut Vec<LossItem>,
129+
) -> Value {
130+
let mut process = json!({
131+
"commandLine": opts.command,
132+
"timeout": opts.timeout_ms,
133+
});
134+
if let Some(cwd) = &opts.cwd {
135+
process["cwd"] = json!(cwd);
136+
}
137+
if !opts.env.is_empty() {
138+
process["env"] = json!(opts.env);
139+
}
140+
141+
let filesystem = map_filesystem(policy, opts, items);
142+
143+
// Direct egress is blocked; all outbound flows through the OpenShell proxy.
144+
// allowedHosts is intentionally empty — the proxy enforces the full policy.
145+
let network = json!({
146+
"defaultPolicy": "block",
147+
"allowedHosts": [],
148+
"blockedHosts": [],
149+
"proxy": {
150+
"host": "127.0.0.1",
151+
"port": proxy_port,
152+
},
153+
});
154+
155+
let mut config = json!({
156+
"version": opts.mxc_version,
157+
"containerId": opts.container_id,
158+
"containment": opts.containment,
159+
"lifecycle": {
160+
"destroyOnExit": true,
161+
"preservePolicy": false,
162+
},
163+
"process": process,
164+
"filesystem": filesystem,
165+
"network": network,
166+
"ui": {
167+
"disable": true,
168+
"clipboard": "none",
169+
"injection": false,
170+
},
171+
});
172+
173+
// No network hosts, so backend-specific network blocks (processContainer
174+
// internetClient, etc.) are not added — correct for the proxy path.
175+
add_backend_specific_config(&mut config, &opts.containment, &[], items);
176+
add_static_policy_loss(policy, opts, items);
177+
config
178+
}
179+
77180
fn build_mxc_config(
78181
policy: &SandboxPolicy,
79182
opts: &MxcMappingOptions,

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

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@
1818
//! and anything MXC cannot express (ports, protocol, L7 rules, binary scope)
1919
//! is recorded in the loss report. Use this when MXC enforces network on its
2020
//! own, with no `OpenShell` proxy in the loop.
21-
//! - `split_policy` (added in a later sprint) — the *lossless* split for the
22-
//! Windows MXC compute driver: MXC handles filesystem + containment + a
23-
//! `network.proxy` redirect, while the full `OpenShell` network policy is
24-
//! preserved in a trimmed policy enforced by the host CONNECT proxy.
21+
//! - [`split_policy`] — the *lossless* split for the Windows MXC compute
22+
//! driver: MXC handles filesystem + containment + a `network.proxy` redirect,
23+
//! while the full `OpenShell` network policy is preserved in a trimmed policy
24+
//! enforced by the host CONNECT proxy.
2525
//!
2626
//! The report/loss-report helpers are only exercised by the example and the
2727
//! integration tests, so the Windows lib build would otherwise warn on them;
@@ -38,5 +38,5 @@ mod report;
3838

3939
pub use config::{DEFAULT_COMMAND, DEFAULT_CONTAINMENT, DEFAULT_MXC_VERSION};
4040
pub use loss::{LossItem, OPEN_SHELL_SUPERSET_GAPS};
41-
pub use map::{MxcMappingOptions, MxcMappingResult, map_to_mxc};
41+
pub use map::{MxcMappingOptions, MxcMappingResult, SplitPolicyResult, map_to_mxc, split_policy};
4242
pub use report::{build_loss_report, render_readme};

‎crates/openshell-driver-mxc/tests/policy_mapper_examples.rs‎

Lines changed: 78 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919
use std::path::{Path, PathBuf};
2020

21-
use openshell_driver_mxc::{MxcMappingOptions, map_to_mxc};
21+
use openshell_driver_mxc::{MxcMappingOptions, map_to_mxc, split_policy};
2222
use openshell_policy::parse_sandbox_policy;
2323
use serde_json::Value;
2424

@@ -177,6 +177,83 @@ fn quickstart_coarse_mapping() {
177177
);
178178
}
179179

180+
#[test]
181+
fn split_policy_routes_network_to_proxy() {
182+
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
183+
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
184+
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
185+
186+
let opts = MxcMappingOptions {
187+
proxy_localhost_port: Some(8080),
188+
..Default::default()
189+
};
190+
let result = split_policy(&policy, &opts).expect("split_policy returns Some when port is set");
191+
let cfg = &result.mxc_config;
192+
193+
// Proxy redirect is emitted.
194+
assert_eq!(cfg["network"]["proxy"]["host"], "127.0.0.1");
195+
assert_eq!(cfg["network"]["proxy"]["port"], 8080);
196+
197+
// Direct egress is blocked; allowedHosts is empty (proxy enforces the list).
198+
assert_eq!(cfg["network"]["defaultPolicy"], "block");
199+
assert!(
200+
str_list(&cfg["network"]["allowedHosts"]).is_empty(),
201+
"split path must not populate allowedHosts"
202+
);
203+
204+
// Filesystem grants are preserved unchanged.
205+
assert_eq!(
206+
str_list(&cfg["filesystem"]["readwritePaths"]),
207+
policy.filesystem.as_ref().unwrap().read_write
208+
);
209+
210+
// Network policy is returned verbatim for the proxy.
211+
assert_eq!(
212+
result.proxy_policy.network_policies.len(),
213+
policy.network_policies.len(),
214+
"proxy_policy must carry all network rules"
215+
);
216+
assert!(
217+
result.proxy_policy.filesystem.is_none(),
218+
"proxy_policy must not carry filesystem rules"
219+
);
220+
221+
// No binary-scope, port, or protocol losses — those are delegated to the proxy.
222+
let net_losses: Vec<_> = result
223+
.loss
224+
.iter()
225+
.filter(|i| i.path.starts_with("network_policies"))
226+
.collect();
227+
assert!(
228+
net_losses.is_empty(),
229+
"split path must not generate network losses: {net_losses:?}"
230+
);
231+
}
232+
233+
#[test]
234+
fn split_policy_returns_none_without_port() {
235+
let opts = MxcMappingOptions::default();
236+
let policy = parse_sandbox_policy("").unwrap_or_default();
237+
assert!(
238+
split_policy(&policy, &opts).is_none(),
239+
"split_policy must return None when proxy_localhost_port is not set"
240+
);
241+
}
242+
243+
#[test]
244+
fn split_policy_deterministic() {
245+
let path = examples_root().join("sandbox-policy-quickstart/policy.yaml");
246+
let yaml = std::fs::read_to_string(&path).expect("read quickstart");
247+
let policy = parse_sandbox_policy(&yaml).expect("parse quickstart");
248+
let opts = MxcMappingOptions {
249+
proxy_localhost_port: Some(9999),
250+
..Default::default()
251+
};
252+
let a = split_policy(&policy, &opts).unwrap();
253+
let b = split_policy(&policy, &opts).unwrap();
254+
assert_eq!(a.mxc_config, b.mxc_config, "split_policy must be deterministic");
255+
}
256+
180257
#[test]
181258
fn network_only_policy_has_empty_filesystem() {
182259
// policy-advisor is a network-only seed (no filesystem_policy).

0 commit comments

Comments
 (0)