Skip to content

Commit 62533e2

Browse files
authored
feat(mxc): add AppContainer sandboxing for system.run
Adds MXC AppContainer-backed system.run sandboxing, Sandbox settings, and hardened bridge packaging/policy handling.\n\nCo-authored-by: Copilot <[email protected]>
1 parent c582509 commit 62533e2

32 files changed

Lines changed: 4024 additions & 3 deletions

‎package-lock.json‎

Lines changed: 56 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
{
2+
"name": "openclaw-windows-node-mxc",
3+
"version": "0.0.0",
4+
"private": true,
5+
"description": "Node bridge dependencies for the OpenClaw tray's MXC sandbox integration. The C# tray spawns node.exe with scripts under tools/mxc/ that consume the @microsoft/mxc-sdk to drive wxc-exec.exe.",
6+
"dependencies": {
7+
"@microsoft/mxc-sdk": "^0.1.8"
8+
}
9+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
using System.Text.Json;
2+
3+
namespace OpenClaw.Shared.Mxc;
4+
5+
/// <summary>
6+
/// Abstraction for executing a capability invocation inside containment.
7+
/// Mirrors the <see cref="ICommandRunner"/> pattern that already exists for
8+
/// system.run, broadened to cover any capability shape.
9+
/// </summary>
10+
/// <remarks>
11+
/// Implementations:
12+
/// <list type="bullet">
13+
/// <item><see cref="OneShotAppContainerExecutor"/> — per-call AppContainer via Node + mxc-sdk.</item>
14+
/// <item><c>HostFallbackExecutor</c> — when containment unavailable in BestEffort mode.</item>
15+
/// </list>
16+
/// All implementations are expected to throw <see cref="SandboxUnavailableException"/>
17+
/// when they cannot serve the request because of a missing backend (e.g. unsupported
18+
/// Windows build, missing wxc-exec.exe). Callers in fail-closed mode translate that
19+
/// into a denied invocation; callers in best-effort mode swap to a host runner.
20+
/// </remarks>
21+
public interface ISandboxExecutor
22+
{
23+
/// <summary>Stable identifier for telemetry and the activity-stream badge.</summary>
24+
/// <example>"mxc-oneshot-appc", "mxc-isosession-worker", "host-fallback"</example>
25+
string Name { get; }
26+
27+
/// <summary>True if this executor enforces containment. False = host fallback path.</summary>
28+
bool IsContained { get; }
29+
30+
/// <summary>Execute the request inside containment.</summary>
31+
/// <exception cref="SandboxUnavailableException">
32+
/// Thrown when the executor's backend cannot serve this request.
33+
/// </exception>
34+
Task<SandboxExecutionResult> ExecuteAsync(
35+
SandboxExecutionRequest request,
36+
CancellationToken ct = default);
37+
}
38+
39+
/// <summary>
40+
/// Capability invocation routed through an <see cref="ISandboxExecutor"/>.
41+
/// Generic across capability shapes (shell exec, structured-data fetch, etc.).
42+
/// </summary>
43+
/// <param name="TimeoutMs">
44+
/// Effective timeout in ms. Already capped by user-settings policy if applicable.
45+
/// Pass &lt;= 0 to let the executor use its default.
46+
/// </param>
47+
/// <param name="MaxOutputBytes">
48+
/// Maximum stdout/stderr the executor will return. Pass <c>null</c> to use the
49+
/// executor's default (typically 4 MiB). The host capture cap and the bridge
50+
/// cap (run-command.cjs) honor this value.
51+
/// </param>
52+
public sealed record SandboxExecutionRequest(
53+
string CapabilityCommand,
54+
JsonElement Args,
55+
SandboxPolicy Policy,
56+
int TimeoutMs,
57+
string? Cwd = null,
58+
IReadOnlyDictionary<string, string>? Env = null,
59+
long? MaxOutputBytes = null);
60+
61+
/// <summary>
62+
/// Result of a sandboxed capability invocation. Mirrors <see cref="CommandResult"/>
63+
/// for shell-shaped invocations, and adds <see cref="StructuredResult"/> for
64+
/// capability-shaped invocations whose output is JSON.
65+
/// </summary>
66+
public sealed record SandboxExecutionResult(
67+
int ExitCode,
68+
string Stdout,
69+
string Stderr,
70+
bool TimedOut,
71+
long DurationMs,
72+
string ContainmentTag,
73+
JsonElement? StructuredResult = null);
74+
75+
/// <summary>
76+
/// Thrown by an <see cref="ISandboxExecutor"/> when its backend cannot serve a
77+
/// request (e.g. unsupported Windows build, missing wxc-exec.exe, OS feature off).
78+
/// Caller policy decides whether to fail-closed or fall back.
79+
/// </summary>
80+
public sealed class SandboxUnavailableException : Exception
81+
{
82+
public SandboxUnavailableException(string reason) : base(reason) { }
83+
public SandboxUnavailableException(string reason, Exception inner) : base(reason, inner) { }
84+
}
Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
using Microsoft.Win32;
2+
3+
namespace OpenClaw.Shared.Mxc;
4+
5+
/// <summary>
6+
/// Per-backend availability probe for MXC. Cached for the process lifetime.
7+
/// </summary>
8+
/// <remarks>
9+
/// Backends checked:
10+
/// <list type="bullet">
11+
/// <item><see cref="IsAppContainerAvailable"/> — Windows 11 build &gt;= 26100, UBR &gt;= 7965 (per @microsoft/mxc-sdk README), x64 / arm64.</item>
12+
/// <item><see cref="IsWxcExecResolvable"/> — wxc-exec.exe found at the expected node_modules path or via override.</item>
13+
/// <item><see cref="IsIsolationSessionAvailable"/> — requires AppContainer plus IsolationProxy.exe in System32.</item>
14+
/// </list>
15+
/// </remarks>
16+
public sealed class MxcAvailability
17+
{
18+
/// <summary>
19+
/// Optional override path for <c>wxc-exec.exe</c>. When set, used instead of the
20+
/// default <c>node_modules/@microsoft/mxc-sdk/bin/&lt;arch&gt;/wxc-exec.exe</c> probe.
21+
/// Wired through environment variable <c>OPENCLAW_WXC_EXEC</c>.
22+
/// </summary>
23+
public const string WxcExecOverrideEnvVar = "OPENCLAW_WXC_EXEC";
24+
25+
private const int MinSupportedBuild = 26100;
26+
27+
/// <summary>
28+
/// Highest base build for which an explicit UBR floor applies. Per the
29+
/// @microsoft/mxc-sdk README, builds in <c>[26100, 26500]</c> require the
30+
/// cumulative update bringing UBR ≥ 7965; builds beyond 26500 (e.g.
31+
/// Canary / Dev channels) ship the feature natively.
32+
/// </summary>
33+
private const int UbrCheckMaxBuild = 26500;
34+
private const int MinSupportedUbrInRange = 7965;
35+
36+
public bool IsAppContainerAvailable { get; }
37+
public bool IsIsolationSessionAvailable { get; }
38+
public bool IsWxcExecResolvable { get; }
39+
public string? WxcExecPath { get; }
40+
41+
/// <summary>
42+
/// Resolved path to <c>tools/mxc/run-command.cjs</c> (the productized Node bridge
43+
/// for MxcCommandRunner). The tray build copies this under the app base
44+
/// directory; probing intentionally does not walk parent directories so a
45+
/// user-writable parent cannot inject a replacement bridge.
46+
/// </summary>
47+
public string? RunCommandScriptPath { get; }
48+
49+
/// <summary>
50+
/// Human-readable list of reasons MXC may not be available. Empty when fully supported.
51+
/// Surface to UX so users know why the sandbox toggle is disabled.
52+
/// </summary>
53+
public IReadOnlyList<string> UnsupportedReasons { get; }
54+
55+
/// <summary>True iff at least one MXC backend is supported, the bridge script is found,
56+
/// AND <c>wxc-exec.exe</c> is resolvable. (Without wxc-exec the executor will refuse
57+
/// to run, so reporting "available" would lie to the UI.)</summary>
58+
public bool HasAnyBackend =>
59+
(IsAppContainerAvailable || IsIsolationSessionAvailable)
60+
&& RunCommandScriptPath is not null
61+
&& IsWxcExecResolvable;
62+
63+
public MxcAvailability(
64+
bool isAppContainerAvailable,
65+
bool isIsolationSessionAvailable,
66+
bool isWxcExecResolvable,
67+
string? wxcExecPath,
68+
string? runCommandScriptPath,
69+
IReadOnlyList<string> unsupportedReasons)
70+
{
71+
IsAppContainerAvailable = isAppContainerAvailable;
72+
IsIsolationSessionAvailable = isIsolationSessionAvailable;
73+
IsWxcExecResolvable = isWxcExecResolvable;
74+
WxcExecPath = wxcExecPath;
75+
RunCommandScriptPath = runCommandScriptPath;
76+
UnsupportedReasons = unsupportedReasons;
77+
}
78+
79+
/// <summary>
80+
/// Probe the running environment. Designed to be called once at app startup
81+
/// and the result cached.
82+
/// </summary>
83+
public static MxcAvailability Probe(IOpenClawLogger? logger = null)
84+
{
85+
var log = logger ?? NullLogger.Instance;
86+
var reasons = new List<string>();
87+
88+
if (!OperatingSystem.IsWindows())
89+
{
90+
reasons.Add("MXC requires Windows.");
91+
return new MxcAvailability(false, false, false, null, null, reasons);
92+
}
93+
94+
var (build, ubr) = ReadWindowsBuildAndUbr();
95+
var buildOk = build >= MinSupportedBuild;
96+
// UBR floor only applies to builds in the [26100, 26500] window;
97+
// newer Canary / Dev builds ship MXC primitives natively.
98+
var ubrCheckApplies = build <= UbrCheckMaxBuild;
99+
var ubrOk = !ubrCheckApplies || ubr >= MinSupportedUbrInRange;
100+
if (!buildOk)
101+
reasons.Add($"Windows build {build} below MXC minimum {MinSupportedBuild}.");
102+
if (buildOk && !ubrOk)
103+
reasons.Add(
104+
$"Windows UBR {ubr} below MXC minimum {MinSupportedUbrInRange} " +
105+
$"(for builds {MinSupportedBuild}-{UbrCheckMaxBuild}). " +
106+
"Install latest cumulative update.");
107+
108+
var isAppContainerSupported = buildOk && ubrOk;
109+
110+
var (wxcResolvable, wxcPath) = ResolveWxcExec();
111+
if (!wxcResolvable)
112+
reasons.Add($"wxc-exec.exe not found. Set {WxcExecOverrideEnvVar} or run `npm ci` at the repository root.");
113+
114+
var runCommandScriptPath = ResolveRunCommandScript();
115+
if (runCommandScriptPath is null)
116+
reasons.Add("tools/mxc/run-command.cjs not found in any expected location.");
117+
118+
// isolation_session additionally requires Feature_IsoBrokerSessionApis on the OS
119+
// and IsolationProxy.exe in System32. We currently only check file presence.
120+
var isolationProxyPath = Path.Combine(
121+
Environment.GetFolderPath(Environment.SpecialFolder.System),
122+
"IsolationProxy.exe");
123+
var isIsolationSessionSupported = isAppContainerSupported
124+
&& wxcResolvable
125+
&& File.Exists(isolationProxyPath);
126+
127+
log.Info(
128+
$"[mxc] availability: appcontainer={isAppContainerSupported} " +
129+
$"isolation_session={isIsolationSessionSupported} " +
130+
$"wxc-exec={(wxcResolvable ? wxcPath : "<missing>")} " +
131+
$"run-command.cjs={(runCommandScriptPath ?? "<missing>")} " +
132+
$"reasons=[{string.Join(", ", reasons)}]");
133+
134+
return new MxcAvailability(
135+
isAppContainerSupported,
136+
isIsolationSessionSupported,
137+
wxcResolvable,
138+
wxcPath,
139+
runCommandScriptPath,
140+
reasons);
141+
}
142+
143+
private static (int build, int ubr) ReadWindowsBuildAndUbr()
144+
{
145+
var build = Environment.OSVersion.Version.Build;
146+
var ubr = 0;
147+
if (!OperatingSystem.IsWindows())
148+
return (build, ubr);
149+
150+
try
151+
{
152+
#pragma warning disable CA1416 // OperatingSystem.IsWindows() guard above; analyzer doesn't recognize it through callee.
153+
using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
154+
var value = key?.GetValue("UBR");
155+
if (value is int ubrInt)
156+
ubr = ubrInt;
157+
#pragma warning restore CA1416
158+
}
159+
catch
160+
{
161+
// Best-effort registry read; failure leaves ubr = 0 which fails the gate.
162+
}
163+
164+
return (build, ubr);
165+
}
166+
167+
private static (bool resolvable, string? path) ResolveWxcExec()
168+
{
169+
var overridePath = Environment.GetEnvironmentVariable(WxcExecOverrideEnvVar);
170+
if (!string.IsNullOrWhiteSpace(overridePath) && File.Exists(overridePath))
171+
return (true, overridePath);
172+
173+
var arch = MxcArchHelper.GetSdkArchString();
174+
var probeRoots = new[]
175+
{
176+
AppContext.BaseDirectory,
177+
Path.GetDirectoryName(typeof(MxcAvailability).Assembly.Location) ?? string.Empty,
178+
};
179+
180+
foreach (var root in probeRoots)
181+
{
182+
if (string.IsNullOrWhiteSpace(root))
183+
continue;
184+
185+
var candidate = Path.Combine(
186+
root,
187+
"node_modules", "@microsoft", "mxc-sdk", "bin", arch, "wxc-exec.exe");
188+
if (File.Exists(candidate))
189+
return (true, candidate);
190+
}
191+
192+
return (false, null);
193+
}
194+
195+
private static string? ResolveRunCommandScript()
196+
{
197+
var probeRoots = new[]
198+
{
199+
AppContext.BaseDirectory,
200+
Path.GetDirectoryName(typeof(MxcAvailability).Assembly.Location) ?? string.Empty,
201+
};
202+
203+
foreach (var root in probeRoots)
204+
{
205+
if (string.IsNullOrWhiteSpace(root))
206+
continue;
207+
208+
var candidate = Path.Combine(root, "tools", "mxc", "run-command.cjs");
209+
if (File.Exists(candidate))
210+
return candidate;
211+
}
212+
213+
return null;
214+
}
215+
}
216+
217+
internal static class MxcArchHelper
218+
{
219+
/// <summary>Returns "arm64" or "x64" matching the @microsoft/mxc-sdk bin/&lt;arch&gt;/ layout.</summary>
220+
public static string GetSdkArchString() => System.Runtime.InteropServices.RuntimeInformation.OSArchitecture switch
221+
{
222+
System.Runtime.InteropServices.Architecture.Arm64 => "arm64",
223+
System.Runtime.InteropServices.Architecture.X64 => "x64",
224+
_ => "x64",
225+
};
226+
}

0 commit comments

Comments
 (0)