diff --git a/windows-node-host.Tests/CommandConsentTests.cs b/windows-node-host.Tests/CommandConsentTests.cs index 39eed17..b7e6f4b 100644 --- a/windows-node-host.Tests/CommandConsentTests.cs +++ b/windows-node-host.Tests/CommandConsentTests.cs @@ -23,6 +23,19 @@ public CommandConsentTests() private NodeInvokeRequest Request(params string[] argv) => CommandConsent.Request(argv, _root, 10_000, "main", "agent:main:test"); + [Fact] + public void ConsentRequestOmitsTimeoutForUpstreamValidationButPreservesFiniteTimeout() + { + var command = new[] { Path.Combine(Environment.SystemDirectory, "hostname.exe") }; + var noTimeout = CommandConsent.Request(command, _root, null, "main", "agent:main:test"); + var finiteTimeout = CommandConsent.Request(command, _root, 10_000, "main", "agent:main:test"); + + Assert.False(noTimeout.Args.TryGetProperty("timeoutMs", out _)); + Assert.True(ExecApprovalV2InputValidator.Validate(noTimeout).IsValid); + Assert.Equal(10_000, finiteTimeout.Args.GetProperty("timeoutMs").GetInt32()); + Assert.True(ExecApprovalV2InputValidator.Validate(finiteTimeout).IsValid); + } + [Fact] public async Task PreparationDoesNotRememberAndPolicyCannotApproveAMiss() { diff --git a/windows-node-host.Tests/CwdPolicyTests.cs b/windows-node-host.Tests/CwdPolicyTests.cs index 5943ceb..1b7dd70 100644 --- a/windows-node-host.Tests/CwdPolicyTests.cs +++ b/windows-node-host.Tests/CwdPolicyTests.cs @@ -74,12 +74,17 @@ await WriteActivationLease(leasePath, leaseSecret, ActivationLeaseMode.Active, policyFingerprint: fingerprint, commandConsent: consent); - async Task Run(string payload, string? cwd, string decision, bool requiresApproval = true) + async Task Run( + string payload, + string? cwd, + string decision, + bool requiresApproval = true, + int? timeoutMs = 30_000) { var input = JsonSerializer.SerializeToElement(new { command = new[] { Path.Combine(Environment.SystemDirectory, "cmd.exe"), "/d", "/s", "/c", payload }, - cwd, rawCommand = payload, agentId = "main", sessionKey = "agent:main:test", + cwd, rawCommand = payload, agentId = "main", sessionKey = "agent:main:test", timeoutMs, }); var prepared = await capability.ExecuteAsync(new NodeInvokeRequest { @@ -102,7 +107,7 @@ async Task Run(string payload, string? cwd, string decision, bool r var dispatch = JsonSerializer.SerializeToElement(new { command = argv, cwd, rawCommand = commandText, - agentId = "main", sessionKey = "agent:main:test", systemRunPlan = plan, + agentId = "main", sessionKey = "agent:main:test", timeoutMs, systemRunPlan = plan, }); var now = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); var proof = new ApprovalProofRecord( @@ -113,7 +118,7 @@ async Task Run(string payload, string? cwd, string decision, bool r var request = JsonSerializer.SerializeToElement(new { command = argv, cwd, rawCommand = commandText, - agentId = "main", sessionKey = "agent:main:test", + agentId = "main", sessionKey = "agent:main:test", timeoutMs, systemRunPlan = plan, microclawApprovalProof = proof, }); var response = await capability.ExecuteAsync(new NodeInvokeRequest @@ -143,6 +148,10 @@ async Task Run(string payload, string? cwd, string decision, bool r Assert.True(fileRead.GetProperty("success").GetBoolean(), fileRead.GetRawText()); Assert.Equal("consent-file-content", fileRead.GetProperty("stdout").GetString()!.Trim()); + var noTimeout = await Run("echo no-timeout", _root, "allow-once", timeoutMs: null); + Assert.True(noTimeout.GetProperty("success").GetBoolean(), noTimeout.GetRawText()); + Assert.Equal("no-timeout", noTimeout.GetProperty("stdout").GetString()); + var denied = await Run("echo should-not-run", _root, "policy"); Assert.False(denied.GetProperty("success").GetBoolean()); Assert.Equal("command-consent-denied", denied.GetProperty("errorCode").GetString()); @@ -383,6 +392,57 @@ public void PowerShellRunStripsDeclarationBeforeMxcCommandLine(string command) Assert.Contains("\\\"C:\\Users\\sunt\\Desktop\\MXC-Approval-Smoke-20261020-1150\\\"", commandLine); } + [Fact] + public void ParseRunUsesDefaultTimeoutWhenFieldIsMissing() + { + var capability = Capability(Policy([])); + + var run = capability.ParseRun(Parse("""{"command":["cmd.exe"]}""")); + + Assert.Equal(30_000, run.TimeoutMs); + } + + [Theory] + [InlineData("null")] + [InlineData("0")] + public void ParseRunTreatsNullAndZeroAsNoTimeout(string value) + { + var capability = Capability(Policy([])); + + var run = capability.ParseRun(Parse( + """{"command":["cmd.exe"],"timeoutMs":""" + value + "}")); + + Assert.Equal(0, run.TimeoutMs); + } + + [Theory] + [InlineData("1000", 1000)] + [InlineData("2147483648", 600_000)] + public void ParseRunPreservesFiniteTimeoutsAndClampsTheMaximum(string value, int expected) + { + var capability = Capability(Policy([])); + + var run = capability.ParseRun(Parse( + """{"command":["cmd.exe"],"timeoutMs":""" + value + "}")); + + Assert.Equal(expected, run.TimeoutMs); + } + + [Theory] + [InlineData("-1")] + [InlineData("1.5")] + [InlineData("\"30000\"")] + [InlineData("true")] + public void ParseRunRejectsInvalidTimeoutValues(string value) + { + var capability = Capability(Policy([])); + + var error = Assert.Throws(() => capability.ParseRun(Parse( + """{"command":["cmd.exe"],"timeoutMs":""" + value + "}"))); + + Assert.Equal("invalid-timeout", error.Code); + } + [Fact] public async Task CanonicalCmdHostExecutionPreservesQuotedPathsAndMetacharacters() { diff --git a/windows-node-host.Tests/HostCommandRunnerTests.cs b/windows-node-host.Tests/HostCommandRunnerTests.cs index 81ffc01..add88fe 100644 --- a/windows-node-host.Tests/HostCommandRunnerTests.cs +++ b/windows-node-host.Tests/HostCommandRunnerTests.cs @@ -78,12 +78,24 @@ public async Task CanonicalCmdTimesOutAndStopsItsProcessTree() Assert.InRange(result.DurationMs, 1, 10_000); } + [Fact] + public async Task CanonicalCmdDoesNotApplyADeadlineWhenTimeoutIsZero() + { + var result = await HostCommandRunner.RunAsync( + Cmd("ping -n 3 127.0.0.1 >nul & echo completed", timeoutMs: 0), + TestContext.Current.CancellationToken); + + Assert.False(result.TimedOut); + Assert.Equal(0, result.ExitCode); + Assert.Equal("completed", result.Stdout); + } + [Fact] public async Task CancellationStopsCanonicalCmd() { using var cancellation = new CancellationTokenSource(TimeSpan.FromMilliseconds(300)); await Assert.ThrowsAnyAsync(() => - HostCommandRunner.RunAsync(Cmd("ping -n 30 127.0.0.1 >nul"), cancellation.Token)); + HostCommandRunner.RunAsync(Cmd("ping -n 30 127.0.0.1 >nul", timeoutMs: 0), cancellation.Token)); } [Fact] diff --git a/windows-node-host.Tests/MxcProcessRunnerTests.cs b/windows-node-host.Tests/MxcProcessRunnerTests.cs index db1c351..2a6b6c3 100644 --- a/windows-node-host.Tests/MxcProcessRunnerTests.cs +++ b/windows-node-host.Tests/MxcProcessRunnerTests.cs @@ -1,11 +1,201 @@ using System.Diagnostics; +using System.Text; using Microsoft.Mxc.Sdk.V1; using MicroClaw.WindowsNodeHost; +using OpenClaw.Shared; +using OpenClaw.Shared.Mxc; +using OpenClaw.Shared.Telemetry; namespace MicroClaw.WindowsNodeHost.Tests; public sealed class MxcProcessRunnerTests { + public static bool NativeAvailable => CwdPolicyTests.NativeMxcAvailable; + + [Fact] + public void MxcNoTimeoutWorkloadDisablesTheExecutorDeadline() + { + var workload = new MxcNoTimeoutRunner.UnboundedCommand(new CommandRequest()); + + Assert.Equal(0, workload.TimeoutMs); + Assert.Equal(Timeout.Infinite, workload.ExecutionTimeout(600_000)); + } + + [Fact] + public async Task NoTimeoutOutlivesConfiguredDeadlineAndCompletesWithinSandbox() + { + using var fixture = new ExecutorFixture(); + var process = new ControlledProcess("sandbox output"); + ContainerRequest? submitted = null; + var tracker = new MxcProcessTracker(request => + { + submitted = request; + return Task.FromResult(process); + }); + using var executor = fixture.CreateExecutor(tracker); + var run = MxcNoTimeoutRunner.RunAsync(executor, fixture.Command(), TestContext.Current.CancellationToken); + + try + { + await process.Started.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + await Task.Delay(1_000, TestContext.Current.CancellationToken); + Assert.False(run.IsCompleted); + Assert.False(process.Killed); + process.Complete(); + var result = await run.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + + Assert.Equal(NodeToolExecutionMode.Sandbox, result.ExecutionMode); + Assert.Equal(0, result.ExitCode); + Assert.False(result.TimedOut); + Assert.Equal("sandbox output", result.Stdout); + Assert.True(process.Disposed); + Assert.False(process.Killed); + Assert.NotNull(submitted); + Assert.Null(submitted.TimeoutMs); + Assert.IsType(submitted.Containment); + Assert.Equal(NetworkAction.Deny, submitted.Network!.Egress!.Default); + Assert.Equal(NetworkAction.Deny, submitted.Network.Ingress!.HostLoopback); + Assert.Contains(fixture.DeniedPath, submitted.Filesystem!.DeniedPaths); + tracker.AssertSettled(); + Assert.Empty(Directory.GetDirectories(fixture.Runs)); + } + finally + { + process.Complete(); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + } + } + + [Fact] + public async Task NoTimeoutCommandStillEnforcesOutputBudget() + { + using var fixture = new ExecutorFixture(); + var process = new ControlledProcess(new string('x', 100)); + var tracker = new MxcProcessTracker(_ => Task.FromResult(process)); + using var executor = fixture.CreateExecutor(tracker, outputBudget: 24); + var run = MxcNoTimeoutRunner.RunAsync(executor, fixture.Command(), TestContext.Current.CancellationToken); + try + { + await process.Started.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + process.Complete(); + var result = await run.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + + Assert.EndsWith("\n[truncated]", result.Stdout); + Assert.True(Encoding.UTF8.GetByteCount(result.Stdout) <= 24); + tracker.AssertSettled(); + } + finally + { + process.Complete(); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + } + } + + [Fact] + public async Task CancelledNoTimeoutCommandKillsAndSettlesItsOwnedProcess() + { + using var fixture = new ExecutorFixture(); + var process = new ControlledProcess("partial output"); + var tracker = new MxcProcessTracker(_ => Task.FromResult(process)); + using var executor = fixture.CreateExecutor(tracker); + using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var run = MxcNoTimeoutRunner.RunAsync(executor, fixture.Command(), cancel.Token); + + try + { + await process.Started.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken); + cancel.Cancel(); + await Assert.ThrowsAnyAsync(() => run); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + + Assert.True(process.Killed); + Assert.True(process.Disposed); + tracker.AssertSettled(); + Assert.Empty(Directory.GetDirectories(fixture.Runs)); + } + finally + { + cancel.Cancel(); + process.Complete(); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + } + } + + [Fact] + public async Task FiniteMxcCommandStillHonorsConfiguredDeadline() + { + using var fixture = new ExecutorFixture(); + var process = new ControlledProcess("output"); + var tracker = new MxcProcessTracker(_ => Task.FromResult(process)); + using var executor = fixture.CreateExecutor(tracker); + var request = fixture.Command(); + request.TimeoutMs = 10_000; + + var result = await new MxcCommandRunner(executor).RunAsync(request, TestContext.Current.CancellationToken); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + + Assert.True(result.TimedOut); + Assert.True(process.Killed); + Assert.True(process.Disposed); + tracker.AssertSettled(); + Assert.Empty(Directory.GetDirectories(fixture.Runs)); + } + + [Fact(SkipUnless = nameof(NativeAvailable), Skip = "Requires a verified native SDK and isolated test scratch.")] + public async Task NativeNoTimeoutCommandCompletesAndCancellationSettlesProcess() + { + var availability = MxcAvailability.Probe(); + Assert.True(availability.CanRunSystemRunSandbox, + string.Join(" ", availability.SystemRunSandboxUnsupportedReasons)); + using var fixture = new ExecutorFixture(); + var spawned = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var runtime = new Stopwatch(); + var tracker = new MxcProcessTracker(async request => + { + var process = await MxcContainer.SpawnAsync(request, + new SpawnOptions { Telemetry = new TelemetryConfig { Enabled = false } }, CancellationToken.None); + runtime.Restart(); + spawned.TrySetResult(); + return process; + }); + using var executor = fixture.CreateNativeExecutor(tracker); + using var cancel = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var command = fixture.Command(); + command.Argv = [Path.Combine(Environment.SystemDirectory, "cmd.exe"), + "/d", "/s", "/c", "ping -n 3 127.0.0.1 >nul & echo completed"]; + try + { + var result = await MxcNoTimeoutRunner.RunAsync(executor, command, cancel.Token) + .WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + Assert.Equal(NodeToolExecutionMode.Sandbox, result.ExecutionMode); + Assert.Equal(0, result.ExitCode); + Assert.False(result.TimedOut); + Assert.Contains("completed", result.Stdout); + Assert.True(runtime.ElapsedMilliseconds > 300); + tracker.AssertSettled(); + + spawned = new(TaskCreationOptions.RunContinuationsAsynchronously); + command.Argv = [Path.Combine(Environment.SystemDirectory, "cmd.exe"), + "/d", "/s", "/c", "ping -n 30 127.0.0.1 >nul"]; + var run = MxcNoTimeoutRunner.RunAsync(executor, command, cancel.Token); + await spawned.Task.WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); + cancel.Cancel(); + await Assert.ThrowsAnyAsync(() => run); + await executor.WaitForOwnedOperationsAsync(TestContext.Current.CancellationToken); + tracker.AssertSettled(); + Assert.Empty(Directory.GetDirectories(fixture.Runs)); + } + finally + { + cancel.Cancel(); + await executor.WaitForOwnedOperationsAsync(CancellationToken.None) + .WaitAsync(TimeSpan.FromSeconds(30), TestContext.Current.CancellationToken); + } + } + [Fact] public async Task TrackerRequiresACompletedWaitAndDisposal() { @@ -91,4 +281,118 @@ private sealed class FakeProcess : IMxcProcess public void Kill() { } public void Dispose() { } } + + private sealed class ExecutorFixture : IDisposable + { + private readonly string _root = Path.Combine( + Environment.GetEnvironmentVariable("MICROCLAW_MXC_NATIVE_TEST_SCRATCH") ?? Path.GetTempPath(), + "microclaw-mxc-timeout-" + Guid.NewGuid().ToString("N")); + private readonly MxcRequestContext _context; + public string Runs => Path.Combine(_root, "runs"); + public string DeniedPath => Path.Combine(_root, "profile", ".ssh"); + + public ExecutorFixture() + { + var profile = Path.Combine(_root, "profile"); + var folders = new[] + { + new MxcUserFolder("Profile", profile), + new MxcUserFolder("Documents", Path.Combine(profile, "Documents")), + new MxcUserFolder("Desktop", Path.Combine(profile, "Desktop")), + new MxcUserFolder("Downloads", Path.Combine(_root, "downloads")), + new MxcUserFolder("OneDrive", Path.Combine(_root, "onedrive"), IsOptional: true), + }; + foreach (var folder in folders) Directory.CreateDirectory(folder.Path!); + Directory.CreateDirectory(DeniedPath); + _context = new MxcRequestContext + { + WindowsDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Windows), + SystemDirectory = Environment.SystemDirectory, + UserFolders = folders, + ProtectedPaths = [DeniedPath], + }; + } + + public CommandRequest Command() => new() + { + Argv = [Path.Combine(Environment.SystemDirectory, "whoami.exe")], + TimeoutMs = 0, + }; + + public NodeSandboxExecutor CreateExecutor(MxcProcessTracker tracker, long outputBudget = 4 * 1024 * 1024) => + new(new NodeSandboxPolicyStore(new SettingsData + { SandboxTimeoutMs = 300, SandboxMaxOutputBytes = outputBudget }), + () => Path.Combine(_root, "settings"), + () => new MxcAvailability(true, false, true, [], + isolationTier: "base-container", supportsProtectedPathDenies: true), + spawn: tracker.SpawnAsync, + probe: _ => new ProbeOutput + { + Tier = IsolationTier.BaseContainer, + NeedsDaclAugmentation = false, + Probes = new() + { + BaseContainerApiPresent = true, + BaseContainerSupportsDenyPaths = true, + UiCapabilities = new(), + }, + }, + scratchRoot: Runs, + contextProvider: () => _context); + + public NodeSandboxExecutor CreateNativeExecutor(MxcProcessTracker tracker) => + new(new NodeSandboxPolicyStore(new SettingsData { SandboxTimeoutMs = 300 }), + () => Path.Combine(_root, "settings"), + spawn: tracker.SpawnAsync, + scratchRoot: Runs, + contextProvider: () => _context); + + public void Dispose() + { + if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true); + } + } + + private sealed class ControlledProcess(string output) : IMxcProcess + { + private readonly TaskCompletionSource _exit = new(TaskCreationOptions.RunContinuationsAsynchronously); + private readonly MemoryStream _input = new(); + private readonly MemoryStream _output = new(Encoding.UTF8.GetBytes(output)); + private readonly MemoryStream _error = new(); + private int _killed; + public TaskCompletionSource Started { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); + public bool Killed => Volatile.Read(ref _killed) != 0; + public bool Disposed { get; private set; } + public uint Id => 0; + public Stream? StandardInput => _input; + public Stream? StandardOutput => _output; + public Stream? StandardError => _error; + public IMxcStreamCloser? StandardOutputCloser => null; + public IMxcStreamCloser? StandardErrorCloser => null; + public IReadOnlyList Warnings => []; + public ExecutionMetadata? OutputMetadata => null; + public void Complete() => _exit.TrySetResult(new WaitResult { ExitCode = 0 }); + public WaitResult Wait() => _exit.Task.GetAwaiter().GetResult(); + public Task WaitAsync(CancellationToken cancellationToken = default) => _exit.Task; + public bool TryGetExitCode(out int exitCode) + { + Started.TrySetResult(); + exitCode = 0; + return _exit.Task.IsCompleted; + } + public Task<(WaitResult Result, byte[] Stdout, byte[] Stderr)> WaitForExitWithOutputAsync( + CancellationToken cancellationToken = default) => throw new NotSupportedException(); + public void Kill() + { + Interlocked.Exchange(ref _killed, 1); + Complete(); + } + public void Dispose() + { + Disposed = true; + _input.Dispose(); + _output.Dispose(); + _error.Dispose(); + } + } } diff --git a/windows-node-host/BundledSystemCapability.cs b/windows-node-host/BundledSystemCapability.cs index 008a4f7..994f136 100644 --- a/windows-node-host/BundledSystemCapability.cs +++ b/windows-node-host/BundledSystemCapability.cs @@ -26,6 +26,8 @@ internal sealed class BundledSystemCapability( string? policyFingerprint = null, CommandConsent? commandConsent = null) : INodeCapability, IDisposable { + private const int DefaultRunTimeoutMs = 30_000; + private const int MaximumRunTimeoutMs = 600_000; private readonly SemaphoreSlim _runGate = new(1, 1); private readonly MxcExecutionContext? _mxcExecution = policy.RequestedStrength == "full" ? MxcSdkRunner.CreateExecutor(policy, approvalsPath) @@ -121,7 +123,8 @@ private async Task PrepareSerializedAsync( if (commandConsent is not null && run.AgentId != ReadinessProbeContract.AgentId) { consentPreparation = await commandConsent.PrepareAsync(CommandConsent.Request( - run.Argv, run.Cwd, run.TimeoutMs, run.AgentId, run.SessionKey)); + run.Argv, run.Cwd, run.TimeoutMs == 0 ? null : run.TimeoutMs, + run.AgentId, run.SessionKey)); resolvedCarrier = consentPreparation.Execution.Argv[0]; } else @@ -136,7 +139,8 @@ private async Task PrepareSerializedAsync( if (commandConsent is not null && run.AgentId != ReadinessProbeContract.AgentId) { var preparation = consentPreparation ?? await commandConsent.PrepareAsync(CommandConsent.Request( - run.Argv, run.Cwd, run.TimeoutMs, run.AgentId, run.SessionKey)); + run.Argv, run.Cwd, run.TimeoutMs == 0 ? null : run.TimeoutMs, + run.AgentId, run.SessionKey)); if (run.ProviderInitialization is not null && !preparation.Execution.Argv.SequenceEqual(run.ProviderInitialization.FinalArgv, StringComparer.Ordinal)) throw new HostPolicyException("powershell-initialization-invalid", @@ -303,7 +307,9 @@ private async Task RunExclusiveAsync( if (commandConsent is not null) { consentExecution = await commandConsent.AuthorizeAsync(CommandConsent.Request( - request.Argv, request.Cwd, request.TimeoutMs, request.AgentId, request.SessionKey), + request.Argv, request.Cwd, + request.TimeoutMs == 0 ? null : request.TimeoutMs, + request.AgentId, request.SessionKey), validatedApproval.ConsentDecision); if (!consentExecution.Argv.SequenceEqual(request.Argv, StringComparer.Ordinal)) throw new HostPolicyException("consent-command-changed", @@ -364,6 +370,8 @@ private async Task RunExclusiveAsync( try { var hostRequest = consentExecution.ToCommandRequest(); + // The approval model requires a positive timeout; preserve the caller's no-timeout value for execution. + hostRequest.TimeoutMs = request.TimeoutMs; if (string.IsNullOrEmpty(currentCwd.LaunchPath)) { var stateRoot = Path.GetDirectoryName(approvalsPath) @@ -443,7 +451,9 @@ private async Task RunExclusiveAsync( $"[filesystem-policy] launchLocation={(currentCwd.MatchedRoot is null ? "isolated-scratch" : "selected-grant")} effectiveAccess={currentCwd.Access} containmentStrength={policy.RequestedStrength}"); try { - var result = await runner.RunAsync(commandRequest, cancellationToken); + var result = commandRequest.TimeoutMs == 0 + ? await MxcNoTimeoutRunner.RunAsync(executor, commandRequest, cancellationToken) + : await runner.RunAsync(commandRequest, cancellationToken); if (result.ExecutionMode == NodeToolExecutionMode.Host) throw new HostPolicyException( "mxc-host-fallback", "MXC unexpectedly selected host execution; sandbox activation is blocked."); @@ -488,9 +498,7 @@ internal RunRequest ParseRun(JsonElement args, bool allowMissingGrants = false) var cwd = args.TryGetProperty("cwd", out var cwdElement) && cwdElement.ValueKind == JsonValueKind.String ? cwdElement.GetString() : null; - var timeout = args.TryGetProperty("timeoutMs", out var timeoutElement) && timeoutElement.TryGetInt32(out var value) - ? Math.Clamp(value, 1, 600_000) - : 30_000; + var timeout = ParseTimeoutMs(args); var agentId = args.TryGetProperty("agentId", out var agentElement) && agentElement.ValueKind == JsonValueKind.String ? agentElement.GetString() : null; @@ -515,6 +523,7 @@ internal RunRequest ParseRun(JsonElement args, bool allowMissingGrants = false) return new RunRequest(argv, cwd, timeout, agentId, sessionKey, rawCommand, commandPreview, verified.Access, verified.Initialization); } + if (PowerShellFilesystemScope.ContainsMarker(argv)) throw new HostPolicyException("powershell-initialization-metadata-required", "The PowerShell filesystem initializer requires its complete prepared plan."); @@ -560,6 +569,21 @@ internal RunRequest ParseRun(JsonElement args, bool allowMissingGrants = false) declaredAccess); } + private static int ParseTimeoutMs(JsonElement args) + { + if (!args.TryGetProperty("timeoutMs", out var timeoutElement)) + return DefaultRunTimeoutMs; + if (timeoutElement.ValueKind == JsonValueKind.Null) + return 0; + if (timeoutElement.ValueKind != JsonValueKind.Number + || !timeoutElement.TryGetInt64(out var value) + || value < 0) + throw new HostPolicyException( + "invalid-timeout", + "timeoutMs must be a non-negative integer or null."); + return value == 0 ? 0 : (int)Math.Min(value, MaximumRunTimeoutMs); + } + private static string? GetSystemRunPlanCommandPreview(JsonElement args) { if (!args.TryGetProperty("systemRunPlan", out var plan) diff --git a/windows-node-host/CommandConsent.cs b/windows-node-host/CommandConsent.cs index 942dfe4..1149f6d 100644 --- a/windows-node-host/CommandConsent.cs +++ b/windows-node-host/CommandConsent.cs @@ -74,7 +74,7 @@ public async Task RevalidateAsync(ExecApprovedExecution execution, CancellationT } internal static NodeInvokeRequest Request( - IReadOnlyList argv, string? cwd, int timeoutMs, string? agentId, string? sessionKey) => + IReadOnlyList argv, string? cwd, int? timeoutMs, string? agentId, string? sessionKey) => new() { Id = Guid.NewGuid().ToString("N"), diff --git a/windows-node-host/MxcNoTimeoutRunner.cs b/windows-node-host/MxcNoTimeoutRunner.cs new file mode 100644 index 0000000..1c8de52 --- /dev/null +++ b/windows-node-host/MxcNoTimeoutRunner.cs @@ -0,0 +1,122 @@ +using System.Diagnostics; +using Microsoft.Mxc.Sdk.V1; +using OpenClaw.Shared; +using OpenClaw.Shared.Mxc; +using OpenClaw.Shared.Telemetry; + +namespace MicroClaw.WindowsNodeHost; + +internal static class MxcNoTimeoutRunner +{ + private const int StatusDllInitFailed = unchecked((int)0xC0000142); + + internal static async Task RunAsync( + NodeSandboxExecutor executor, + CommandRequest request, + CancellationToken cancellationToken) + { + if (request.TimeoutMs != 0) + throw new ArgumentOutOfRangeException(nameof(request), "The no-timeout runner requires timeoutMs to be zero."); + + var stopwatch = Stopwatch.StartNew(); + CommandResult result; + try + { + result = await executor.RunAsync(new UnboundedCommand(request), cancellationToken) + .ConfigureAwait(false); + } + catch (NodeSandboxExecutionException ex) + { + result = new() + { + ExitCode = -1, + Stderr = ex.Message, + ExecutionMode = ex.ExecutionMode, + ErrorCategory = ex.Category, + SandboxDenialReason = ex.Category == NodeToolErrorCategory.SandboxDenied + ? NodeToolSandboxDenialReason.UnsupportedSandboxRequest + : null, + }; + } + + result.DurationMs = stopwatch.ElapsedMilliseconds; + if (result.ExitCode == StatusDllInitFailed && !result.TimedOut + && result.ExecutionMode == NodeToolExecutionMode.Sandbox) + { + const string hint = + "Command initialization failed (0xC0000142). This can involve Windows UI APIs (USER32) " + + "or another DLL dependency. Check Windows runtime and desktop compatibility. " + + "Containment was not relaxed."; + result.Stderr = string.IsNullOrWhiteSpace(result.Stderr) + ? hint + : result.Stderr + Environment.NewLine + hint; + } + return result; + } + + internal sealed class UnboundedCommand(CommandRequest command) : NodeSandboxExecutor.Workload + { + private CommandOutputCapture _capture = null!; + private CommandResult? _deadline; + + internal override int TimeoutMs => 0; + // The executor still links caller cancellation; only its runtime deadline is disabled. + internal override int ExecutionTimeout(int setting) => Timeout.Infinite; + internal override string? ExpectedPolicy => command.ExpectedMxcPolicy; + internal override CommandRequest Command(FixedFileWorkerLease? image) => command; + + internal override void Initialize(NodeSandboxPolicy policy) + { + var budget = policy.Settings.SandboxMaxOutputBytes; + _capture = new(budget > 0 ? budget : 4 * 1024 * 1024); + } + + internal override async ValueTask RevalidateAsync(CancellationToken stop, NodeToolExecutionMode mode) + { + if (command.RevalidateApproval is not { } revalidate) return; + var authorization = await revalidate(stop).ConfigureAwait(false); + if (authorization.IsCurrent) return; + throw authorization.IsPolicyDenial + ? NodeSandboxExecutor.Failure("Command approval changed before launch. Retry for a fresh approval.", + NodeToolErrorCategory.ExecPolicyDenied, mode) + : NodeSandboxExecutor.Failure("Command approval could not be revalidated before launch. Retry for a fresh approval.", + NodeToolErrorCategory.InternalFailure, mode); + } + + internal override NodeSandboxIoOperation StartIo( + NodeSandboxProcessIo io, + CancellationToken stop) + { + io.CloseInput(); + _capture.BindRootExit(io.RootExit, () => (io.RootExit.Result, false)); + var output = io.ExecutionMode == NodeToolExecutionMode.Sandbox + ? Task.Run(() => _capture.StandardOutput.Collect(io.StandardOutput)) + : _capture.StandardOutput.CollectAsync(io.StandardOutput, stop); + var error = io.ExecutionMode == NodeToolExecutionMode.Sandbox + ? Task.Run(() => _capture.StandardError.Collect(io.StandardError)) + : _capture.StandardError.CollectAsync(io.StandardError, stop); + var drains = Task.WhenAll(output, error); + return new(ReadyAsync(), drains, Interrupt, () => _capture.Snapshot(io.ExecutionMode)); + + async Task ReadyAsync() + { + await CommandOutputCapture.WaitForExitOrInterruptionAsync( + io.RootExit, output, error, stop).ConfigureAwait(false); + if (io.RootExit.IsCompletedSuccessfully) + await CommandOutputCapture.DrainAfterExitAsync(drains, stop).ConfigureAwait(false); + } + + void Interrupt() + { + _capture.CaptureRootExit(); + _capture.StandardOutput.Interrupt(); + _capture.StandardError.Interrupt(); + } + } + + internal override void CaptureDeadline(NodeToolExecutionMode mode) => + _deadline = _capture.Snapshot(mode, deadlineExpired: true); + + internal override CommandResult DeadlineResult(NodeToolExecutionMode mode) => _deadline!; + } +}