Skip to content

Commit 83a8b8a

Browse files
AlexAlves87claude
andcommitted
feat: gate the new approvals path when the sandbox cannot carry approved argv
The new approvals path executes an allow as a direct argv. The sandbox transport cannot carry that form yet, so a command approved while the sandbox is enabled and available would fail closed at execution. Probe the runner's transport capability up front and return a typed unavailable error before evaluation, so nothing is approved that cannot execute. The sandbox is never bypassed or disabled: the gate only fires where the sandbox would run the request, and every other flag combination (sandbox off, or enabled but unavailable) keeps executing the approved argv on the host it already used. Also make a failed coordinator construction non-sticky so a transient initialization fault is retried on the next capability rebuild instead of pinning the fail-closed handler until restart, and document the intentional flag matrix on the setting. Co-Authored-By: Claude Fable 5 <[email protected]>
1 parent 04c87c6 commit 83a8b8a

7 files changed

Lines changed: 425 additions & 12 deletions

File tree

‎src/OpenClaw.Shared/Capabilities/SystemCapability.cs‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -324,15 +324,29 @@ private async Task<NodeInvokeResponse> HandleRunAsync(NodeInvokeRequest request)
324324
{
325325
Logger.Info($"[system.run] corr={correlationId} path=v2");
326326
ExecApprovalV2Result v2Result;
327-
try
327+
if (_commandRunner is IDirectArgvSupportAwareCommandRunner argvAware
328+
&& !argvAware.CanExecuteDirectArgv())
328329
{
329-
v2Result = await _v2Handler.HandleAsync(request, correlationId);
330+
// Approved commands execute as a direct argv, which the active
331+
// sandbox transport cannot carry yet. Fail closed before any
332+
// evaluation or prompt so nothing gets approved that cannot
333+
// execute. The sandbox is never bypassed or disabled from here.
334+
v2Result = ExecApprovalV2Result.Unavailable(
335+
"sandboxed system.run cannot execute the approved command form yet; " +
336+
"keep the sandbox on and disable the new approvals path, or turn the sandbox off, to run commands");
330337
}
331-
catch (Exception ex)
338+
else
332339
{
333-
// Rail 1: no silent fallback — handler exceptions become typed denies.
334-
Logger.Error($"[system.run] corr={correlationId} path=v2 handler threw", ex);
335-
v2Result = ExecApprovalV2Result.ValidationFailed("Handler exception");
340+
try
341+
{
342+
v2Result = await _v2Handler.HandleAsync(request, correlationId);
343+
}
344+
catch (Exception ex)
345+
{
346+
// Rail 1: no silent fallback — handler exceptions become typed denies.
347+
Logger.Error($"[system.run] corr={correlationId} path=v2 handler threw", ex);
348+
v2Result = ExecApprovalV2Result.ValidationFailed("Handler exception");
349+
}
336350
}
337351

338352
Logger.Info($"[system.run] corr={correlationId} decision={v2Result.Code} reason={v2Result.Reason}");

‎src/OpenClaw.Shared/ICommandRunner.cs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,3 +107,20 @@ public interface IHostFallbackAwareCommandRunner : ICommandRunner
107107
/// </summary>
108108
string? ResolveHostFallbackShellForApproval(string? requestedShell, string effectiveShell);
109109
}
110+
111+
/// <summary>
112+
/// Optional contract for runners whose active transport may not support the
113+
/// direct-argv execution form (<see cref="CommandRequest.Argv"/>). Callers that
114+
/// must deliver an already-approved argv verbatim probe this before submitting,
115+
/// so an incompatible transport produces an explicit up-front error instead of
116+
/// a rejected execution after approval.
117+
/// </summary>
118+
public interface IDirectArgvSupportAwareCommandRunner : ICommandRunner
119+
{
120+
/// <summary>
121+
/// True when a direct-argv request submitted now would reach a runner that
122+
/// executes <see cref="CommandRequest.Argv"/> verbatim. False when the
123+
/// active transport cannot carry an argv faithfully and would fail closed.
124+
/// </summary>
125+
bool CanExecuteDirectArgv();
126+
}

‎src/OpenClaw.Shared/Mxc/MxcCommandRunner.cs‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ namespace OpenClaw.Shared.Mxc;
1818
/// <item><c>false</c> — bypass MXC; route through the host runner.</item>
1919
/// </list>
2020
/// </remarks>
21-
public sealed class MxcCommandRunner : IHostFallbackAwareCommandRunner
21+
public sealed class MxcCommandRunner : IHostFallbackAwareCommandRunner, IDirectArgvSupportAwareCommandRunner
2222
{
2323
public string Name => "mxc";
2424
private const string DefaultSandboxShell = "cmd";
@@ -79,6 +79,30 @@ public string ResolveEffectiveShell(string? requestedShell)
7979
: hostShell;
8080
}
8181

82+
/// <summary>
83+
/// A direct-argv request can only be honored by the host runner: the sandbox
84+
/// protocol carries the legacy command/shell/args fields and cannot transport
85+
/// an argv faithfully yet. This reports which transport a request submitted
86+
/// now would reach, so callers that must execute an approved argv verbatim
87+
/// can fail closed up front instead of after approval. It never disables or
88+
/// bypasses the sandbox: when the sandbox would run the request, the answer
89+
/// is simply "not supported".
90+
/// </summary>
91+
public bool CanExecuteDirectArgv()
92+
{
93+
var settings = _settingsProvider();
94+
if (!settings.SystemRunSandboxEnabled)
95+
return true;
96+
97+
// Sandbox enabled but unavailable: the compatibility host fallback honors
98+
// Argv, and the strict-blocking variant rejects every request with its own
99+
// explicit denial, so neither case needs the up-front argv gate.
100+
if (!_isSandboxAvailable())
101+
return true;
102+
103+
return false;
104+
}
105+
82106
public async Task<CommandResult> RunAsync(CommandRequest request, CancellationToken ct = default)
83107
{
84108
var settings = _settingsProvider();

‎src/OpenClaw.Shared/SettingsData.cs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,21 @@ public record class SettingsData
177177
/// legacy policy. Default <c>false</c>. When enabled, any failure inside
178178
/// the new pipeline produces a typed deny — it never falls back silently
179179
/// to the legacy path. No Settings UI yet; enabled by editing settings.json.
180+
/// <para>
181+
/// Interaction with <see cref="SystemRunSandboxEnabled"/> (intentional, not
182+
/// a misconfiguration): the pipeline executes approved commands as a direct
183+
/// argv, and the sandbox transport cannot carry that form yet, so
184+
/// system.run behaves as follows while this setting is on:
185+
/// <list type="bullet">
186+
/// <item>sandbox enabled and available — every request returns a typed
187+
/// unavailable error before evaluation; the sandbox is never bypassed.</item>
188+
/// <item>sandbox enabled, unavailable, host fallback allowed — the approved
189+
/// argv executes uncontained on the host.</item>
190+
/// <item>sandbox enabled, unavailable, strict fallback blocking — the
191+
/// sandbox settings deny execution, as they do for the legacy path.</item>
192+
/// <item>sandbox disabled — the approved argv executes on the host.</item>
193+
/// </list>
194+
/// </para>
180195
/// </summary>
181196
public bool ExecApprovalsNewPathEnabled { get; set; } = false;
182197

‎src/OpenClaw.Tray.WinUI/Services/NodeService.cs‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -343,8 +343,13 @@ private void RegisterCapabilities()
343343
// New exec approvals path: explicit opt-in, default off.
344344
if (_settings?.ExecApprovalsNewPathEnabled == true)
345345
{
346-
_execApprovalsV2Handler ??= BuildExecApprovalsV2Handler();
347-
_systemCapability.SetV2Handler(_execApprovalsV2Handler);
346+
// One coordinator per service lifetime (it serializes approvals with
347+
// a per-instance semaphore), but a failed construction must not be
348+
// sticky: only a real coordinator is cached, so the next capability
349+
// rebuild retries a transient initialization fault instead of
350+
// pinning the fail-closed handler until restart.
351+
_execApprovalsV2Handler ??= TryBuildExecApprovalsV2Coordinator();
352+
_systemCapability.SetV2Handler(_execApprovalsV2Handler ?? ExecApprovalV2NullHandler.Instance);
348353
}
349354

350355
Register(_systemCapability);
@@ -600,7 +605,7 @@ private void DetachClientHandlers(WindowsNodeClient client)
600605
/// wired yet, so prompt-required decisions resolve through the store's
601606
/// ask fallback.
602607
/// </summary>
603-
private IExecApprovalV2Handler BuildExecApprovalsV2Handler()
608+
private IExecApprovalV2Handler? TryBuildExecApprovalsV2Coordinator()
604609
{
605610
try
606611
{
@@ -616,8 +621,10 @@ private IExecApprovalV2Handler BuildExecApprovalsV2Handler()
616621
}
617622
catch (Exception ex)
618623
{
619-
_logger.Error("[EXEC-APPROVALS] new path enabled but coordinator unavailable; failing closed", ex);
620-
return ExecApprovalV2NullHandler.Instance;
624+
_logger.Error(
625+
"[EXEC-APPROVALS] new path enabled but coordinator unavailable; " +
626+
"failing closed until the next capability rebuild retries", ex);
627+
return null;
621628
}
622629
}
623630

‎tests/OpenClaw.Shared.Tests/ExecApprovalV2RoutingTests.cs‎

Lines changed: 184 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
using OpenClaw.Shared;
88
using OpenClaw.Shared.Capabilities;
99
using OpenClaw.Shared.ExecApprovals;
10+
using OpenClaw.Shared.Mxc;
1011

1112
namespace OpenClaw.Shared.Tests;
1213

@@ -445,10 +446,193 @@ public async Task V2Deny_DoesNotInvokeRunner()
445446
Assert.Null(runner.LastRequest);
446447
}
447448

449+
// -------------------------------------------------------------------------
450+
// Sandbox flag matrix: the V2 path against the real MXC runner, driven by
451+
// SystemRunSandboxEnabled / availability / strict fallback blocking.
452+
// -------------------------------------------------------------------------
453+
454+
private static ExecApprovedExecution ApprovedEchoNoEnv()
455+
=> new(new[] { "cmd", "/c", "echo hi" }, cwd: @"C:\work", timeoutMs: 5000, env: null);
456+
457+
private static MxcCommandRunner BuildMxcRunner(
458+
SettingsData settings,
459+
bool sandboxAvailable,
460+
FakeRunner hostFallback,
461+
FakeSandboxExecutor sandboxExecutor)
462+
=> new(
463+
sandboxExecutor,
464+
hostFallback,
465+
() => settings,
466+
() => System.IO.Path.GetTempPath(),
467+
() => sandboxAvailable);
468+
469+
[Theory]
470+
[InlineData(false, false, false, true)] // sandbox off → host runner honors argv
471+
[InlineData(false, true, false, true)]
472+
[InlineData(true, true, false, false)] // sandbox on + available → no argv transport
473+
[InlineData(true, true, true, false)]
474+
[InlineData(true, false, false, true)] // on + unavailable + fallback → host honors argv
475+
[InlineData(true, false, true, true)] // on + unavailable + strict → runner denies on its own
476+
public void MxcRunner_CanExecuteDirectArgv_FollowsSandboxFlags(
477+
bool sandboxEnabled, bool sandboxAvailable, bool strictBlock, bool expected)
478+
{
479+
var settings = new SettingsData
480+
{
481+
SystemRunSandboxEnabled = sandboxEnabled,
482+
SystemRunBlockHostFallbackWhenMxcUnavailable = strictBlock,
483+
};
484+
var runner = BuildMxcRunner(settings, sandboxAvailable, new FakeRunner(), new FakeSandboxExecutor());
485+
486+
Assert.Equal(expected, runner.CanExecuteDirectArgv());
487+
}
488+
489+
[Fact]
490+
public async Task V2_SandboxEnabledAndAvailable_TypedUnavailable_NothingEvaluatesOrExecutes()
491+
{
492+
var settings = new SettingsData { SystemRunSandboxEnabled = true };
493+
var host = new FakeRunner();
494+
var sandbox = new FakeSandboxExecutor();
495+
var handler = new TrackingHandler();
496+
var logger = new CapturingLogger();
497+
var cap = new SystemCapability(logger);
498+
cap.SetCommandRunner(BuildMxcRunner(settings, sandboxAvailable: true, host, sandbox));
499+
cap.SetV2Handler(handler);
500+
501+
var res = await cap.ExecuteAsync(RunRequest());
502+
503+
Assert.False(res.Ok);
504+
Assert.Contains("Unavailable", res.Error!);
505+
Assert.False(handler.WasCalled, "gate must fire before any evaluation or prompt");
506+
Assert.Null(host.LastRequest);
507+
Assert.Equal(0, sandbox.Calls);
508+
Assert.True(logger.HasInfoContaining("decision=Unavailable"),
509+
"typed gate outcome must flow through the standard decision log");
510+
}
511+
512+
[Fact]
513+
public async Task V2Allow_SandboxUnavailable_FallbackAllowed_ExecutesApprovedArgvOnHost()
514+
{
515+
var settings = new SettingsData
516+
{
517+
SystemRunSandboxEnabled = true,
518+
SystemRunBlockHostFallbackWhenMxcUnavailable = false,
519+
};
520+
var host = new FakeRunner();
521+
var sandbox = new FakeSandboxExecutor();
522+
var approved = ApprovedEchoNoEnv();
523+
var cap = new SystemCapability(NullLogger.Instance);
524+
cap.SetCommandRunner(BuildMxcRunner(settings, sandboxAvailable: false, host, sandbox));
525+
cap.SetV2Handler(new FixedResultHandler(ExecApprovalV2Result.Allow(approved)));
526+
527+
var res = await cap.ExecuteAsync(RunRequest());
528+
529+
Assert.True(res.Ok);
530+
Assert.Equal(0, sandbox.Calls);
531+
Assert.NotNull(host.LastRequest);
532+
Assert.Equal(approved.Argv, host.LastRequest!.Argv);
533+
Assert.Equal(approved.Cwd, host.LastRequest.Cwd);
534+
Assert.Equal(approved.TimeoutMs, host.LastRequest.TimeoutMs);
535+
}
536+
537+
[Fact]
538+
public async Task V2Allow_SandboxUnavailable_StrictBlocking_DeniesWithoutExecuting()
539+
{
540+
var settings = new SettingsData
541+
{
542+
SystemRunSandboxEnabled = true,
543+
SystemRunBlockHostFallbackWhenMxcUnavailable = true,
544+
};
545+
var host = new FakeRunner();
546+
var sandbox = new FakeSandboxExecutor();
547+
var cap = new SystemCapability(NullLogger.Instance);
548+
cap.SetCommandRunner(BuildMxcRunner(settings, sandboxAvailable: false, host, sandbox));
549+
cap.SetV2Handler(new FixedResultHandler(ExecApprovalV2Result.Allow(ApprovedEchoNoEnv())));
550+
551+
var res = await cap.ExecuteAsync(RunRequest());
552+
553+
// The strict sandbox settings deny execution with their own explicit
554+
// result (exit -1), exactly as they do for the legacy path.
555+
Assert.True(res.Ok);
556+
Assert.Null(host.LastRequest);
557+
Assert.Equal(0, sandbox.Calls);
558+
var payload = JsonSerializer.Serialize(res.Payload);
559+
Assert.Contains("\"exitCode\":-1", payload);
560+
}
561+
562+
[Fact]
563+
public async Task V2Allow_SandboxDisabled_ExecutesApprovedArgvOnHost_EnvIntact()
564+
{
565+
var settings = new SettingsData { SystemRunSandboxEnabled = false };
566+
var host = new FakeRunner();
567+
var sandbox = new FakeSandboxExecutor();
568+
var approved = ApprovedEcho();
569+
var cap = new SystemCapability(NullLogger.Instance);
570+
cap.SetCommandRunner(BuildMxcRunner(settings, sandboxAvailable: true, host, sandbox));
571+
cap.SetV2Handler(new FixedResultHandler(ExecApprovalV2Result.Allow(approved)));
572+
573+
var res = await cap.ExecuteAsync(RunRequest());
574+
575+
Assert.True(res.Ok);
576+
Assert.Equal(0, sandbox.Calls);
577+
Assert.NotNull(host.LastRequest);
578+
Assert.Equal(approved.Argv, host.LastRequest!.Argv);
579+
Assert.Equal("bar", host.LastRequest.Env!["FOO"]);
580+
}
581+
582+
[Fact]
583+
public async Task V2_RunnerWithoutArgvSupportContract_IsNeverGated()
584+
{
585+
// A plain ICommandRunner that does not implement the argv-support
586+
// contract (e.g. the host-only LocalCommandRunner) must never trip the
587+
// gate: the handler runs and the approved argv executes.
588+
var runner = new FakeRunner();
589+
var handler = new TrackingHandler();
590+
var cap = new SystemCapability(NullLogger.Instance);
591+
cap.SetCommandRunner(runner);
592+
cap.SetV2Handler(handler);
593+
594+
await cap.ExecuteAsync(RunRequest());
595+
596+
Assert.True(handler.WasCalled);
597+
}
598+
599+
[Fact]
600+
public async Task V2Deny_WithRealMxcRunner_NeverReachesAnyTransport()
601+
{
602+
var settings = new SettingsData { SystemRunSandboxEnabled = true };
603+
var host = new FakeRunner();
604+
var sandbox = new FakeSandboxExecutor();
605+
var cap = new SystemCapability(NullLogger.Instance);
606+
// Sandbox unavailable + fallback allowed: the gate lets the handler run,
607+
// and the deny must still stop before any transport is touched.
608+
cap.SetCommandRunner(BuildMxcRunner(settings, sandboxAvailable: false, host, sandbox));
609+
cap.SetV2Handler(new FixedResultHandler(ExecApprovalV2Result.SecurityDeny("blocked")));
610+
611+
var res = await cap.ExecuteAsync(RunRequest());
612+
613+
Assert.False(res.Ok);
614+
Assert.Null(host.LastRequest);
615+
Assert.Equal(0, sandbox.Calls);
616+
}
617+
448618
// -------------------------------------------------------------------------
449619
// Helpers
450620
// -------------------------------------------------------------------------
451621

622+
private sealed class FakeSandboxExecutor : ISandboxExecutor
623+
{
624+
public int Calls { get; private set; }
625+
public string Name => "fake-sandbox";
626+
public bool IsContained => true;
627+
628+
public Task<SandboxExecutionResult> ExecuteAsync(
629+
SandboxExecutionRequest request, System.Threading.CancellationToken ct = default)
630+
{
631+
Calls++;
632+
return Task.FromResult(new SandboxExecutionResult(0, "sandboxed", "", false, 1, "fake"));
633+
}
634+
}
635+
452636
private sealed class FakeRunner : ICommandRunner
453637
{
454638
public string Name => "fake";

0 commit comments

Comments
 (0)