Skip to content

Commit 63e5a9b

Browse files
calebedenCopilot
andcommitted
Merge origin/main into setup path hardening
Preserve the finalized WSL quoting ownership rows from #1001 and append the WSL distro install-path policy row. Co-authored-by: Copilot App <[email protected]> Copilot-Session: f19f98b7-f377-4da5-a7ce-0f1ae34153cf
2 parents e2c7889 + 4706ca7 commit 63e5a9b

4 files changed

Lines changed: 93 additions & 22 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
7474
| `src/OpenClaw.Shared/Models.cs` | per-domain model files + `*Mapper` classes |
7575
| `src/OpenClaw.Shared/Capabilities/SystemCapability.cs` | `ExecApprovalService` |
7676
| `src/OpenClaw.Connection/GatewayConnectionManager.cs` | `NodeConnectionCoordinator`, `BootstrapTokenLifecycle`, `DevicePairApprovalCoordinator` |
77-
| `src/OpenClaw.SetupEngine/SetupSteps.cs` | one file per step; `WslShellClient`, `WslShellQuoting`, `GatewayConfigScriptBuilder`, `KeepaliveProcessManager` |
77+
| `src/OpenClaw.SetupEngine/SetupSteps.cs` | one file per step; `WslShellClient`, `GatewayConfigScriptBuilder`, `KeepaliveProcessManager`. WSL/POSIX quoting is done — use `WslShellQuoting`, never a local `ShellEscape`. |
7878
| Any test hand-rolling a temp dir / env save-restore / CLI capture | `OpenClaw.TestSupport` fixtures |
7979

8080
## Ledger
@@ -108,7 +108,8 @@ leading and trailing pipe. Columns, in order:
108108
| test-gateway-builder | authoritative | OpenClaw.Connection.Tests | per-file MakeRecord(id,url) helpers | OpenClaw.Connection.Tests.GatewayRecordBuilder | pre-existing MakeRecord until migrated | gateway record test data has one builder | TestSupportFixtureTests.GatewayRecordBuilder_BuildsRecord | behavioral | when MakeRecord helpers are removed |
109109
| test-settings-builder | authoritative | scattered test files | ad hoc SettingsData construction in migrated tests | OpenClaw.TestSupport.SettingsDataBuilder | pre-existing un-migrated tests until adopted | settings test data starts from production defaults | TestSupportFixtureTests.SettingsDataBuilder_StartsFromDefaults | behavioral | when settings tests adopt the builder |
110110
| json-read-helpers | authoritative | OpenClaw.Shared (multiple files) | duplicate non-nullable fallback-returning JsonElement getters | JsonReadHelpers | null-sentinel / non-negative / whitespace-absent / trimming variants stay separate | canonical non-nullable fallback JSON coercion; divergent-contract helpers are not blindly routed here | JsonReadHelpersTests.GetString_ReturnsNull_WhenPropertyMissing | behavioral | when the non-nullable fallback getters are all routed here |
111-
| wsl-posix-quoting | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | ad hoc ShellEscape with divergent wrap semantics | WslShellQuoting | SetupSteps ShellEscape until PR 3 migration | WSL scripts use POSIX quoting not cmd/PowerShell quoting | WslShellQuotingTests.QuotePosixSingleQuote_WrapsAndEscapesEmbeddedQuote | behavioral | when SetupSteps call sites use WslShellQuoting |
111+
| wsl-posix-quoting | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | ad hoc ShellEscape with divergent wrap semantics | WslShellQuoting | - | WSL command lines use POSIX single-quote quoting via WslShellQuoting not cmd/PowerShell quoting | WslShellQuotingTests.QuotePosixSingleQuote_WrapsAndEscapesEmbeddedQuote | behavioral | when no code builds WSL command lines outside WslShellQuoting |
112+
| setup-shellescape-closed | closed | src/OpenClaw.SetupEngine/SetupSteps.cs | private ShellEscape helpers with divergent wrap semantics | WslShellQuoting | - | SetupSteps builds WSL command lines only via WslShellQuoting; no local ShellEscape helper | SetupStepsShellEscapeClosureTests.SetupSteps_DoesNotReintroduce_PrivateShellEscape | source-shape | when SetupSteps.cs no longer builds any WSL command strings |
112113
| wsl-distro-install-path | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | inline Path.Combine wsl distro install-path derivation | DistroInstallPathPolicy | - | distro install path is a validated immediate child of LocalDataDir\wsl with no reparse-point ancestors before any recursive delete or wsl --install | SetupStepsTests.DistroInstallPathPolicy_ResolvesImmediateChild | behavioral | - |
113114
| app-window-manager | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | window creation/show/hide/shutdown | IWindowManager | composition/delegation only | startup/shutdown ordering deterministic; disposed once | none | review-only | extracted in Phase 3 |
114115
| app-tray-controller | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | tray icon/menu/action routing | ITrayController | composition/delegation only | tray actions route unchanged | none | review-only | extracted in Phase 3 |

‎src/OpenClaw.SetupEngine/SetupSteps.cs‎

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1269,15 +1269,15 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
12691269

12701270
internal static string BuildInstallCommand(string installUrl, string? requestedVersion)
12711271
{
1272-
var escapedUrl = ShellEscape(installUrl);
1272+
var escapedUrl = WslShellQuoting.EscapePosixSingleQuoteInner(installUrl);
12731273
if (string.IsNullOrWhiteSpace(requestedVersion))
12741274
return $"curl -fsSL --proto '=https' --tlsv1.2 '{escapedUrl}' | bash";
12751275

12761276
var trimmedVersion = requestedVersion.Trim();
12771277
if (trimmedVersion.Contains('\n') || trimmedVersion.Contains('\r'))
12781278
throw new ArgumentException("Gateway version cannot contain newlines.");
12791279

1280-
var escapedVersion = ShellEscape(trimmedVersion);
1280+
var escapedVersion = WslShellQuoting.EscapePosixSingleQuoteInner(trimmedVersion);
12811281
return $"curl -fsSL --proto '=https' --tlsv1.2 '{escapedUrl}' | bash -s -- --version '{escapedVersion}'";
12821282
}
12831283

@@ -1328,8 +1328,6 @@ echo OPENCLAW_PATH_READY
13281328
return StepResult.Ok();
13291329
}
13301330

1331-
private static string ShellEscape(string value) => value.Replace("'", "'\\''");
1332-
13331331
public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
13341332
{
13351333
var user = ctx.Config.Wsl.User;
@@ -1369,7 +1367,7 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
13691367
var env = new Dictionary<string, string> { ["OPENCLAW_GATEWAY_TOKEN"] = token };
13701368

13711369
var allowedCommandsJson = JsonSerializer.Serialize(ctx.Config.Capabilities.GetEnabledCommandIds());
1372-
var escapedAllowedCommands = ShellEscape(allowedCommandsJson);
1370+
var escapedAllowedCommands = WslShellQuoting.QuotePosixSingleQuote(allowedCommandsJson);
13731371
var extraConfigOverridesAllowCommands = gw.ExtraConfig?.ContainsKey("gateway.nodes.allowCommands") == true;
13741372
if (gw.ExtraConfig is { Count: > 0 })
13751373
{
@@ -1432,7 +1430,7 @@ openclaw config set gateway.nodes.allowCommands {escapedAllowedCommands}
14321430
if (GetDefaultDevicePairPublicUrl(gw, port) is { } defaultPublicUrl &&
14331431
gw.ExtraConfig?.ContainsKey(DevicePairPublicUrlKey) != true)
14341432
{
1435-
configCommands += $"\n openclaw config set {DevicePairPublicUrlKey} {ShellEscape(defaultPublicUrl)}";
1433+
configCommands += $"\n openclaw config set {DevicePairPublicUrlKey} {WslShellQuoting.QuotePosixSingleQuote(defaultPublicUrl)}";
14361434
}
14371435

14381436
// The gateway ships the `device-pair` plugin bundled but DISABLED by default.
@@ -1460,7 +1458,7 @@ openclaw config set gateway.nodes.allowCommands {escapedAllowedCommands}
14601458
if (!IsSafeExtraConfigKey(key))
14611459
throw new ArgumentException($"Invalid Gateway.ExtraConfig key '{key}'. Keys may contain only letters, digits, '.', '_', and '-'.", nameof(gw));
14621460

1463-
var escapedValue = ShellEscape(value);
1461+
var escapedValue = WslShellQuoting.QuotePosixSingleQuote(value);
14641462
configCommands += $"\n openclaw config set {key} {escapedValue}";
14651463
}
14661464
}
@@ -1492,8 +1490,6 @@ private static int CountConfigSetCommands(string configCommands)
14921490
internal static string? GetDefaultDevicePairPublicUrl(GatewayConfig gw, int port) =>
14931491
gw.Bind == "loopback" ? $"http://127.0.0.1:{port}" : null;
14941492

1495-
private static string ShellEscape(string value) => "'" + value.Replace("'", "'\\''") + "'";
1496-
14971493
internal static bool IsSafeExtraConfigKey(string value)
14981494
=> System.Text.RegularExpressions.Regex.IsMatch(value, "^[A-Za-z0-9._-]+$");
14991495
}
@@ -2813,7 +2809,7 @@ internal static bool IsMissingDistroResult(CommandResult result)
28132809

28142810
internal static async Task<StepResult> RunOpenclawSetupAsync(SetupContext ctx, string distro, string user, string workspaceAbsolute, CancellationToken ct)
28152811
{
2816-
var workspaceArg = ShellEscape(workspaceAbsolute);
2812+
var workspaceArg = WslShellQuoting.QuotePosixSingleQuote(workspaceAbsolute);
28172813

28182814
// The pinned 2026.6.11 CLI uses plain `setup` for baseline initialization;
28192815
// newer/custom CLIs require `--baseline`. Detect the installed contract.
@@ -3032,11 +3028,11 @@ internal static string BuildApplyScript(string absoluteWorkspacePath)
30323028
=> $$"""
30333029
set -e
30343030
set -o pipefail
3035-
workspace={{ShellEscape(absoluteWorkspacePath)}}
3031+
workspace={{WslShellQuoting.QuotePosixSingleQuote(absoluteWorkspacePath)}}
30363032
agents="$workspace/AGENTS.md"
3037-
block_b64={{ShellEscape(ManagedBlockBase64())}}
3038-
begin_marker={{ShellEscape(WindowsNodeContextSection.BeginMarker)}}
3039-
end_marker={{ShellEscape(WindowsNodeContextSection.EndMarker)}}
3033+
block_b64={{WslShellQuoting.QuotePosixSingleQuote(ManagedBlockBase64())}}
3034+
begin_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.BeginMarker)}}
3035+
end_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.EndMarker)}}
30403036
if [ -L "$agents" ]; then
30413037
echo "AGENTS_SYMLINK:$agents" >&2
30423038
exit 2
@@ -3087,10 +3083,10 @@ internal static string BuildRollbackScript(string absoluteWorkspacePath)
30873083
=> $$"""
30883084
set -e
30893085
set -o pipefail
3090-
workspace={{ShellEscape(absoluteWorkspacePath)}}
3086+
workspace={{WslShellQuoting.QuotePosixSingleQuote(absoluteWorkspacePath)}}
30913087
agents="$workspace/AGENTS.md"
3092-
begin_marker={{ShellEscape(WindowsNodeContextSection.BeginMarker)}}
3093-
end_marker={{ShellEscape(WindowsNodeContextSection.EndMarker)}}
3088+
begin_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.BeginMarker)}}
3089+
end_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.EndMarker)}}
30943090
if [ ! -e "$agents" ]; then
30953091
echo "WINDOWS_NODE_CONTEXT_ABSENT"
30963092
exit 0
@@ -3134,8 +3130,6 @@ exit 4
31343130
private static string ManagedBlockBase64()
31353131
=> Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(WindowsNodeContextSection.ManagedBlock));
31363132

3137-
private static string ShellEscape(string value) => "'" + value.Replace("'", "'\\''") + "'";
3138-
31393133
private static string FirstNonEmpty(params string[] values)
31403134
=> values.Select(v => v.Trim()).FirstOrDefault(v => v.Length > 0) ?? "no output";
31413135

@@ -3642,7 +3636,6 @@ internal static bool IsKeepaliveCommandLine(string? commandLine, string distro)
36423636
try
36433637
{
36443638
// Use WMI to get the command line
3645-
var result = new System.Diagnostics.Process();
36463639
var psi = new System.Diagnostics.ProcessStartInfo("powershell.exe",
36473640
$"-NoProfile -Command \"(Get-CimInstance Win32_Process -Filter 'ProcessId={pid}').CommandLine\"")
36483641
{

‎tests/OpenClaw.SetupEngine.Tests/SetupStepsTests.cs‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1350,6 +1350,29 @@ public void ConfigureGateway_DoesNotOverrideExplicitDevicePairPublicUrl()
13501350
commands);
13511351
}
13521352

1353+
// Characterization (PR 3 WslShellQuoting migration): the ExtraConfig value is emitted
1354+
// as a fully-wrapped POSIX token, so an embedded single quote must close-escape-reopen
1355+
// ('\'') and remain single-quoted. Pins the generated command byte-for-byte.
1356+
[Fact]
1357+
public void ConfigureGateway_QuotesExtraConfigValueWithEmbeddedSingleQuote()
1358+
{
1359+
var commands = ConfigureGatewayStep.BuildConfigCommands(
1360+
new GatewayConfig
1361+
{
1362+
Bind = "lan",
1363+
ExtraConfig = new Dictionary<string, string>
1364+
{
1365+
["gateway.custom.note"] = "a'b",
1366+
},
1367+
},
1368+
18789,
1369+
"'[]'");
1370+
1371+
Assert.Contains(
1372+
"openclaw config set gateway.custom.note 'a'\\''b'",
1373+
commands);
1374+
}
1375+
13531376
[Fact]
13541377
public async Task ConfigureGateway_UsesExtendedTimeoutForWslConfig()
13551378
{
@@ -1861,6 +1884,25 @@ public void WindowsNodeContext_BuildRollbackScript_UsesAbsolutePathAndMinimalSha
18611884
Assert.DoesNotContain("<<'NODE'", script);
18621885
}
18631886

1887+
// Characterization (PR 3 WslShellQuoting migration): the workspace path is emitted as a
1888+
// fully-wrapped POSIX token, so an embedded single quote must close-escape-reopen ('\'')
1889+
// and remain single-quoted. Pins the generated script byte-for-byte.
1890+
[Fact]
1891+
public void WindowsNodeContext_BuildApplyScript_QuotesWorkspacePathWithEmbeddedSingleQuote()
1892+
{
1893+
var script = WindowsNodeBootstrapContextStep.BuildApplyScript("/home/o'brien/.openclaw/workspace");
1894+
1895+
Assert.Contains("workspace='/home/o'\\''brien/.openclaw/workspace'", script);
1896+
}
1897+
1898+
[Fact]
1899+
public void WindowsNodeContext_BuildRollbackScript_QuotesWorkspacePathWithEmbeddedSingleQuote()
1900+
{
1901+
var script = WindowsNodeBootstrapContextStep.BuildRollbackScript("/home/o'brien/.openclaw/workspace");
1902+
1903+
Assert.Contains("workspace='/home/o'\\''brien/.openclaw/workspace'", script);
1904+
}
1905+
18641906
[Theory]
18651907
[InlineData("/home/openclaw/.openclaw/workspace", "/home/openclaw", "/home/openclaw/.openclaw/workspace")]
18661908
[InlineData("~", "/home/openclaw", "/home/openclaw")]
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
using System;
2+
using System.Linq;
3+
using System.Text.RegularExpressions;
4+
using Xunit;
5+
6+
namespace OpenClaw.Shared.Tests.Architecture;
7+
8+
/// <summary>
9+
/// Source-shape guard for the ledger row <c>setup-shellescape-closed</c>. PR 3 migrated
10+
/// <c>SetupSteps</c>' WSL quoting to <see cref="OpenClaw.Shared.WslShellQuoting"/> and deleted
11+
/// the two divergent private <c>ShellEscape</c> helpers (one escape-only, one fully-wrapped).
12+
/// Re-adding a local <c>ShellEscape</c> to <c>SetupSteps</c> would silently reintroduce the
13+
/// divergent wrap-semantics bug this refactor closed — a wrong variant yields an unquoted or
14+
/// double-quoted WSL argument, i.e. a broken or injectable setup script — so this test fails
15+
/// if such a helper (or any call to one) reappears in <c>SetupSteps.cs</c>.
16+
/// </summary>
17+
public sealed class SetupStepsShellEscapeClosureTests
18+
{
19+
[Fact]
20+
public void SetupSteps_DoesNotReintroduce_PrivateShellEscape()
21+
{
22+
var setupSteps = ProductionSourceFiles.All
23+
.FirstOrDefault(f => f.Path.EndsWith("SetupSteps.cs", StringComparison.Ordinal));
24+
25+
Assert.NotNull(setupSteps);
26+
27+
var shellEscapeReference = new Regex(@"\bShellEscape\s*\(");
28+
Assert.False(
29+
shellEscapeReference.IsMatch(setupSteps!.Text),
30+
"SetupSteps.cs must not declare or call a local ShellEscape helper; build WSL command " +
31+
"lines with OpenClaw.Shared.WslShellQuoting (EscapePosixSingleQuoteInner for a value the " +
32+
"caller wraps itself, QuotePosixSingleQuote for a standalone token). " +
33+
"See docs/ARCHITECTURE.md -> wsl-posix-quoting / setup-shellescape-closed.");
34+
}
35+
}

0 commit comments

Comments
 (0)