Skip to content

Commit 963a8ea

Browse files
bkudiessCopilot
andcommitted
refactor(setup): route SetupSteps WSL quoting through WslShellQuoting
Migrate SetupSteps.cs off three divergent private ShellEscape helpers onto the shared WslShellQuoting contract (added in PR 2), then delete the duplicates. Behavior-preserving: generated scripts are byte-identical. - InstallCliStep (escape-only, caller supplies its own outer quotes) -> WslShellQuoting.EscapePosixSingleQuoteInner. - ConfigureGatewayStep + WindowsNodeBootstrapContextStep (standalone fully-wrapped tokens) -> WslShellQuoting.QuotePosixSingleQuote. - Delete all three private ShellEscape methods. WslShellQuoting stays internal, reachable via the existing InternalsVisibleTo("OpenClaw.SetupEngine"). Add characterization tests pinning generated command/script output for embedded-quote inputs, and a source-shape ledger guard (setup-shellescape-closed) that fails CI if a local ShellEscape reappears in SetupSteps.cs. Co-authored-by: Copilot App <[email protected]>
1 parent e0afbc4 commit 963a8ea

4 files changed

Lines changed: 93 additions & 21 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
| 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 |
113114
| 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 |
114115
| app-activation-router | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | deep-link/toast/single-instance activation | IActivationRouter | composition/delegation only | activation routes land on the same UI/actions; current-user pipe security preserved | none | review-only | extracted in Phase 3 |

‎src/OpenClaw.SetupEngine/SetupSteps.cs‎

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

12431243
internal static string BuildInstallCommand(string installUrl, string? requestedVersion)
12441244
{
1245-
var escapedUrl = ShellEscape(installUrl);
1245+
var escapedUrl = WslShellQuoting.EscapePosixSingleQuoteInner(installUrl);
12461246
if (string.IsNullOrWhiteSpace(requestedVersion))
12471247
return $"curl -fsSL --proto '=https' --tlsv1.2 '{escapedUrl}' | bash";
12481248

12491249
var trimmedVersion = requestedVersion.Trim();
12501250
if (trimmedVersion.Contains('\n') || trimmedVersion.Contains('\r'))
12511251
throw new ArgumentException("Gateway version cannot contain newlines.");
12521252

1253-
var escapedVersion = ShellEscape(trimmedVersion);
1253+
var escapedVersion = WslShellQuoting.EscapePosixSingleQuoteInner(trimmedVersion);
12541254
return $"curl -fsSL --proto '=https' --tlsv1.2 '{escapedUrl}' | bash -s -- --version '{escapedVersion}'";
12551255
}
12561256

@@ -1301,8 +1301,6 @@ echo OPENCLAW_PATH_READY
13011301
return StepResult.Ok();
13021302
}
13031303

1304-
private static string ShellEscape(string value) => value.Replace("'", "'\\''");
1305-
13061304
public override async Task RollbackAsync(SetupContext ctx, CancellationToken ct)
13071305
{
13081306
var user = ctx.Config.Wsl.User;
@@ -1342,7 +1340,7 @@ public override async Task<StepResult> ExecuteAsync(SetupContext ctx, Cancellati
13421340
var env = new Dictionary<string, string> { ["OPENCLAW_GATEWAY_TOKEN"] = token };
13431341

13441342
var allowedCommandsJson = JsonSerializer.Serialize(ctx.Config.Capabilities.GetEnabledCommandIds());
1345-
var escapedAllowedCommands = ShellEscape(allowedCommandsJson);
1343+
var escapedAllowedCommands = WslShellQuoting.QuotePosixSingleQuote(allowedCommandsJson);
13461344
var extraConfigOverridesAllowCommands = gw.ExtraConfig?.ContainsKey("gateway.nodes.allowCommands") == true;
13471345
if (gw.ExtraConfig is { Count: > 0 })
13481346
{
@@ -1405,7 +1403,7 @@ openclaw config set gateway.nodes.allowCommands {escapedAllowedCommands}
14051403
if (GetDefaultDevicePairPublicUrl(gw, port) is { } defaultPublicUrl &&
14061404
gw.ExtraConfig?.ContainsKey(DevicePairPublicUrlKey) != true)
14071405
{
1408-
configCommands += $"\n openclaw config set {DevicePairPublicUrlKey} {ShellEscape(defaultPublicUrl)}";
1406+
configCommands += $"\n openclaw config set {DevicePairPublicUrlKey} {WslShellQuoting.QuotePosixSingleQuote(defaultPublicUrl)}";
14091407
}
14101408

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

1436-
var escapedValue = ShellEscape(value);
1434+
var escapedValue = WslShellQuoting.QuotePosixSingleQuote(value);
14371435
configCommands += $"\n openclaw config set {key} {escapedValue}";
14381436
}
14391437
}
@@ -1465,8 +1463,6 @@ private static int CountConfigSetCommands(string configCommands)
14651463
internal static string? GetDefaultDevicePairPublicUrl(GatewayConfig gw, int port) =>
14661464
gw.Bind == "loopback" ? $"http://127.0.0.1:{port}" : null;
14671465

1468-
private static string ShellEscape(string value) => "'" + value.Replace("'", "'\\''") + "'";
1469-
14701466
internal static bool IsSafeExtraConfigKey(string value)
14711467
=> System.Text.RegularExpressions.Regex.IsMatch(value, "^[A-Za-z0-9._-]+$");
14721468
}
@@ -2786,7 +2782,7 @@ internal static bool IsMissingDistroResult(CommandResult result)
27862782

27872783
internal static async Task<StepResult> RunOpenclawSetupAsync(SetupContext ctx, string distro, string user, string workspaceAbsolute, CancellationToken ct)
27882784
{
2789-
var workspaceArg = ShellEscape(workspaceAbsolute);
2785+
var workspaceArg = WslShellQuoting.QuotePosixSingleQuote(workspaceAbsolute);
27902786

27912787
// The pinned 2026.6.11 CLI uses plain `setup` for baseline initialization;
27922788
// newer/custom CLIs require `--baseline`. Detect the installed contract.
@@ -3005,11 +3001,11 @@ internal static string BuildApplyScript(string absoluteWorkspacePath)
30053001
=> $$"""
30063002
set -e
30073003
set -o pipefail
3008-
workspace={{ShellEscape(absoluteWorkspacePath)}}
3004+
workspace={{WslShellQuoting.QuotePosixSingleQuote(absoluteWorkspacePath)}}
30093005
agents="$workspace/AGENTS.md"
3010-
block_b64={{ShellEscape(ManagedBlockBase64())}}
3011-
begin_marker={{ShellEscape(WindowsNodeContextSection.BeginMarker)}}
3012-
end_marker={{ShellEscape(WindowsNodeContextSection.EndMarker)}}
3006+
block_b64={{WslShellQuoting.QuotePosixSingleQuote(ManagedBlockBase64())}}
3007+
begin_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.BeginMarker)}}
3008+
end_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.EndMarker)}}
30133009
if [ -L "$agents" ]; then
30143010
echo "AGENTS_SYMLINK:$agents" >&2
30153011
exit 2
@@ -3060,10 +3056,10 @@ internal static string BuildRollbackScript(string absoluteWorkspacePath)
30603056
=> $$"""
30613057
set -e
30623058
set -o pipefail
3063-
workspace={{ShellEscape(absoluteWorkspacePath)}}
3059+
workspace={{WslShellQuoting.QuotePosixSingleQuote(absoluteWorkspacePath)}}
30643060
agents="$workspace/AGENTS.md"
3065-
begin_marker={{ShellEscape(WindowsNodeContextSection.BeginMarker)}}
3066-
end_marker={{ShellEscape(WindowsNodeContextSection.EndMarker)}}
3061+
begin_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.BeginMarker)}}
3062+
end_marker={{WslShellQuoting.QuotePosixSingleQuote(WindowsNodeContextSection.EndMarker)}}
30673063
if [ ! -e "$agents" ]; then
30683064
echo "WINDOWS_NODE_CONTEXT_ABSENT"
30693065
exit 0
@@ -3107,8 +3103,6 @@ exit 4
31073103
private static string ManagedBlockBase64()
31083104
=> Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(WindowsNodeContextSection.ManagedBlock));
31093105

3110-
private static string ShellEscape(string value) => "'" + value.Replace("'", "'\\''") + "'";
3111-
31123106
private static string FirstNonEmpty(params string[] values)
31133107
=> values.Select(v => v.Trim()).FirstOrDefault(v => v.Length > 0) ?? "no output";
31143108

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1079,6 +1079,29 @@ public void ConfigureGateway_DoesNotOverrideExplicitDevicePairPublicUrl()
10791079
commands);
10801080
}
10811081

1082+
// Characterization (PR 3 WslShellQuoting migration): the ExtraConfig value is emitted
1083+
// as a fully-wrapped POSIX token, so an embedded single quote must close-escape-reopen
1084+
// ('\'') and remain single-quoted. Pins the generated command byte-for-byte.
1085+
[Fact]
1086+
public void ConfigureGateway_QuotesExtraConfigValueWithEmbeddedSingleQuote()
1087+
{
1088+
var commands = ConfigureGatewayStep.BuildConfigCommands(
1089+
new GatewayConfig
1090+
{
1091+
Bind = "lan",
1092+
ExtraConfig = new Dictionary<string, string>
1093+
{
1094+
["gateway.custom.note"] = "a'b",
1095+
},
1096+
},
1097+
18789,
1098+
"'[]'");
1099+
1100+
Assert.Contains(
1101+
"openclaw config set gateway.custom.note 'a'\\''b'",
1102+
commands);
1103+
}
1104+
10821105
[Fact]
10831106
public async Task ConfigureGateway_UsesExtendedTimeoutForWslConfig()
10841107
{
@@ -1590,6 +1613,25 @@ public void WindowsNodeContext_BuildRollbackScript_UsesAbsolutePathAndMinimalSha
15901613
Assert.DoesNotContain("<<'NODE'", script);
15911614
}
15921615

1616+
// Characterization (PR 3 WslShellQuoting migration): the workspace path is emitted as a
1617+
// fully-wrapped POSIX token, so an embedded single quote must close-escape-reopen ('\'')
1618+
// and remain single-quoted. Pins the generated script byte-for-byte.
1619+
[Fact]
1620+
public void WindowsNodeContext_BuildApplyScript_QuotesWorkspacePathWithEmbeddedSingleQuote()
1621+
{
1622+
var script = WindowsNodeBootstrapContextStep.BuildApplyScript("/home/o'brien/.openclaw/workspace");
1623+
1624+
Assert.Contains("workspace='/home/o'\\''brien/.openclaw/workspace'", script);
1625+
}
1626+
1627+
[Fact]
1628+
public void WindowsNodeContext_BuildRollbackScript_QuotesWorkspacePathWithEmbeddedSingleQuote()
1629+
{
1630+
var script = WindowsNodeBootstrapContextStep.BuildRollbackScript("/home/o'brien/.openclaw/workspace");
1631+
1632+
Assert.Contains("workspace='/home/o'\\''brien/.openclaw/workspace'", script);
1633+
}
1634+
15931635
[Theory]
15941636
[InlineData("/home/openclaw/.openclaw/workspace", "/home/openclaw", "/home/openclaw/.openclaw/workspace")]
15951637
[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)