Skip to content

Commit d0fca93

Browse files
calebedenCopilotshanselman
authored
improve(setup): keep WSL operations inside the app-owned directory (#1006)
* improve(setup): validate WSL distro install paths Validate distro names and canonical install paths before setup cleanup, installation, and rollback filesystem operations. Reject reparse-point ancestors and revalidate ownership before each recursive-delete retry. Co-authored-by: Copilot App <[email protected]> Copilot-Session: f19f98b7-f377-4da5-a7ce-0f1ae34153cf * fix(setup): preserve safe legacy distro teardown Separate strict new-install naming from safe legacy teardown so existing managed distros can be removed without weakening path containment. Co-authored-by: Copilot App <[email protected]> Copilot-Session: f19f98b7-f377-4da5-a7ce-0f1ae34153cf * fix(setup): fail closed during legacy teardown Co-authored-by: Copilot App <[email protected]> Copilot-Session: 675e4cf9-9a9b-4a46-b00f-ba5a78916e0a * test(integration): use concrete exec approval rule Co-authored-by: Copilot App <[email protected]> Copilot-Session: 675e4cf9-9a9b-4a46-b00f-ba5a78916e0a --------- Co-authored-by: Copilot App <[email protected]> Co-authored-by: Scott Hanselman <[email protected]>
1 parent 01bacff commit d0fca93

9 files changed

Lines changed: 1095 additions & 46 deletions

File tree

‎docs/ARCHITECTURE.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,7 @@ leading and trailing pipe. Columns, in order:
113113
| 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 |
114114
| 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 |
115115
| 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 |
116+
| wsl-distro-install-path | authoritative | OpenClaw.SetupEngine/SetupSteps.cs | inline Path.Combine wsl distro install-path derivation | DistroInstallPathPolicy | - | new installs use the strict supported name grammar; teardown accepts only unambiguous single-segment names whose canonical path is an immediate child of LocalDataDir\wsl with no aliases, case or Unicode collisions, or reparse points at the root or child | SetupStepsTests.DistroInstallPathPolicy_ResolvesImmediateChild | behavioral | - |
116117
| 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 |
117118
| 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 |
118119
| 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 |

‎docs/SETUP_ENGINE_REDESIGN.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
The Setup Engine is a **config-driven system** for provisioning an OpenClaw WSL gateway from scratch. It consists of two setup projects plus the tray host:
66

7-
1. **`OpenClaw.SetupEngine`** — Headless pipeline library. Runs 19 steps sequentially with full JSONL logging, transaction journal, and rollback support.
7+
1. **`OpenClaw.SetupEngine`** — Headless pipeline library. Runs 24 steps sequentially with full JSONL logging, transaction journal, and rollback support.
88
2. **`OpenClaw.SetupEngine.UI`** — WinUI3 setup window/pages that wrap the same pipeline with a fluent wizard UI.
99
3. **`OpenClaw.Tray.WinUI`** — The only shipped WinUI executable. It hosts `SetupWindow` directly and self-restarts after successful setup.
1010

@@ -83,6 +83,17 @@ src/OpenClaw.SetupEngine.UI/
8383
If the setup UI cannot find, read, or deserialize the selected configuration,
8484
it opens on the setup failure page with the load error and does not start setup.
8585

86+
New WSL distros use a 1-64 character name containing ASCII letters, digits,
87+
periods, underscores, or hyphens, beginning and ending with a letter or digit.
88+
Uninstall also accepts older names with spaces or Unicode when the name is one
89+
safe Windows path segment and resolves to an immediate child of the app-owned
90+
`LocalDataDir\wsl` root. Teardown rejects filesystem aliases, case or Unicode
91+
normalization collisions, and reparse points at either the root or managed
92+
child. It also preserves the VHD directory unless WSL confirms the distro is
93+
absent or unregister succeeds. To replace such a legacy distro, uninstall it
94+
first, using `--uninstall --confirm-destructive` and the same distro name, then
95+
rerun setup with a supported new name.
96+
8697
```json
8798
{
8899
"DistroName": "OpenClawGateway",

‎src/OpenClaw.SetupEngine.UI/Pages/ProgressPage.xaml.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public sealed partial class ProgressPage : Page
3636
// Map pipeline step IDs to display groups (N:1)
3737
private static readonly (string GroupId, string DisplayName, string[] StepIds)[] StepGroups =
3838
[
39-
("preflight", "Check system", ["preflight-os", "preflight-wsl", "preflight-windows-tailscale"]),
39+
("preflight", "Check system", ["validate-distro-path", "preflight-os", "preflight-wsl", "preflight-windows-tailscale"]),
4040
("cleanup", "Removing existing gateway", ["cleanup-distro", "cleanup-gateway"]),
4141
("port", "Checking gateway port", ["preflight-port"]),
4242
("wsl-create", "Installing clean WSL gateway", ["wsl-create"]),
Lines changed: 315 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,315 @@
1+
using System.Text;
2+
3+
namespace OpenClaw.SetupEngine;
4+
5+
internal static class DistroInstallPathPolicy
6+
{
7+
public const string LegacyReplacementGuidance =
8+
"To replace an existing distro with an unsupported legacy name, rerun SetupEngine with --uninstall --confirm-destructive and the same distro name, then rerun setup with a supported name.";
9+
10+
private const int MaxDistroNameLength = 64;
11+
private const StringComparison PathComparison = StringComparison.OrdinalIgnoreCase;
12+
private static readonly char[] InvalidFileNameChars = Path.GetInvalidFileNameChars();
13+
private static readonly HashSet<string> ReservedDeviceNames = new(StringComparer.OrdinalIgnoreCase)
14+
{
15+
"CON", "PRN", "AUX", "NUL",
16+
"COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
17+
"COM¹", "COM²", "COM³",
18+
"LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
19+
"LPT¹", "LPT²", "LPT³",
20+
};
21+
22+
public static bool TryGetNewInstallPath(
23+
string localDataDir,
24+
string? distroName,
25+
out string installPath,
26+
out string error)
27+
{
28+
installPath = "";
29+
30+
if (string.IsNullOrWhiteSpace(distroName))
31+
{
32+
error = "WSL distro name is required.";
33+
return false;
34+
}
35+
36+
if (!IsValidDistroName(distroName))
37+
{
38+
error = $"Invalid WSL distro name '{distroName}'. Use 1-{MaxDistroNameLength} ASCII letters, digits, periods, underscores, or hyphens, starting and ending with a letter or digit.";
39+
return false;
40+
}
41+
42+
return TryGetManagedInstallPath(localDataDir, distroName, out installPath, out error);
43+
}
44+
45+
public static bool TryGetManagedInstallPath(
46+
string localDataDir,
47+
string? distroName,
48+
out string installPath,
49+
out string error)
50+
{
51+
installPath = "";
52+
53+
if (!IsSafeManagedPathSegment(distroName, out error))
54+
return false;
55+
56+
string localDataRoot;
57+
string wslRoot;
58+
try
59+
{
60+
localDataRoot = NormalizePath(localDataDir);
61+
wslRoot = NormalizePath(Path.Combine(localDataRoot, "wsl"));
62+
installPath = NormalizePath(Path.Combine(wslRoot, distroName!));
63+
}
64+
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
65+
{
66+
installPath = "";
67+
error = $"Invalid WSL distro install path: {ex.Message}";
68+
return false;
69+
}
70+
71+
if (!PathEquals(Path.GetDirectoryName(installPath), wslRoot))
72+
{
73+
error = $"WSL distro install path '{installPath}' must be an immediate child of '{wslRoot}'.";
74+
installPath = "";
75+
return false;
76+
}
77+
78+
if (!TryValidateAncestors(localDataRoot, wslRoot, out error))
79+
{
80+
installPath = "";
81+
return false;
82+
}
83+
84+
if (TryResolveUnambiguousManagedChild(wslRoot, distroName!, ref installPath, out error))
85+
return true;
86+
87+
installPath = "";
88+
return false;
89+
}
90+
91+
public static string WithLegacyReplacementGuidance(string? distroName, string error)
92+
=> IsLegacyTeardownOnlyName(distroName)
93+
? $"{error} {LegacyReplacementGuidance}"
94+
: error;
95+
96+
public static bool TryValidateDeleteTarget(
97+
string localDataDir,
98+
string? distroName,
99+
string candidatePath,
100+
out string deletePath,
101+
out string error)
102+
{
103+
if (!TryGetManagedInstallPath(localDataDir, distroName, out deletePath, out error))
104+
return false;
105+
106+
string candidate;
107+
try
108+
{
109+
candidate = NormalizePath(candidatePath);
110+
}
111+
catch (Exception ex) when (ex is ArgumentException or NotSupportedException or PathTooLongException)
112+
{
113+
error = $"Invalid WSL distro deletion path: {ex.Message}";
114+
return false;
115+
}
116+
117+
if (!PathEquals(candidate, deletePath))
118+
{
119+
error = $"Refusing to delete WSL path '{candidate}'; expected the app-owned distro path '{deletePath}'.";
120+
return false;
121+
}
122+
123+
return true;
124+
}
125+
126+
private static bool TryValidateAncestors(string localDataRoot, string wslRoot, out string error)
127+
{
128+
string? current = wslRoot;
129+
while (current is not null)
130+
{
131+
if (!TryGetExistingAttributes(current, out var exists, out var attributes, out error))
132+
return false;
133+
134+
if (exists && attributes.HasFlag(FileAttributes.ReparsePoint))
135+
{
136+
error = $"Refusing to operate under '{current}' because it is a reparse point; remove it manually and retry setup.";
137+
return false;
138+
}
139+
140+
if (PathEquals(current, wslRoot) &&
141+
exists &&
142+
!attributes.HasFlag(FileAttributes.Directory))
143+
{
144+
error = $"App-owned WSL root '{current}' is not a directory; remove it manually and retry setup.";
145+
return false;
146+
}
147+
148+
if (PathEquals(current, localDataRoot))
149+
{
150+
error = "";
151+
return true;
152+
}
153+
154+
current = Path.GetDirectoryName(current);
155+
}
156+
157+
error = $"WSL install path '{wslRoot}' is not contained within '{localDataRoot}'.";
158+
return false;
159+
}
160+
161+
private static bool TryResolveUnambiguousManagedChild(
162+
string wslRoot,
163+
string distroName,
164+
ref string installPath,
165+
out string error)
166+
{
167+
if (!Directory.Exists(wslRoot))
168+
{
169+
error = "";
170+
return true;
171+
}
172+
173+
string[] children;
174+
try
175+
{
176+
children = Directory.GetFileSystemEntries(wslRoot);
177+
}
178+
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException)
179+
{
180+
error = $"Cannot enumerate app-owned WSL root '{wslRoot}': {ex.Message}";
181+
return false;
182+
}
183+
184+
var requestedNormalized = distroName.Normalize(NormalizationForm.FormC);
185+
var caseMatches = children
186+
.Where(path => string.Equals(Path.GetFileName(path), distroName, PathComparison))
187+
.ToArray();
188+
var normalizationMatches = children
189+
.Where(path => string.Equals(
190+
Path.GetFileName(path).Normalize(NormalizationForm.FormC),
191+
requestedNormalized,
192+
PathComparison))
193+
.ToArray();
194+
195+
if (caseMatches.Length > 1 || normalizationMatches.Length > 1)
196+
{
197+
error = $"Managed WSL distro name '{distroName}' is ambiguous because multiple app-owned path entries differ only by case or Unicode normalization.";
198+
return false;
199+
}
200+
201+
if (caseMatches.Length == 0 && normalizationMatches.Length == 1)
202+
{
203+
error = $"Managed WSL distro name '{distroName}' aliases existing app-owned path entry '{Path.GetFileName(normalizationMatches[0])}'; use the exact stored name.";
204+
return false;
205+
}
206+
207+
if (caseMatches.Length == 1)
208+
installPath = NormalizePath(caseMatches[0]);
209+
210+
if (!TryGetExistingAttributes(installPath, out var exists, out var attributes, out error))
211+
return false;
212+
213+
if (exists && caseMatches.Length == 0)
214+
{
215+
error = $"Managed WSL distro name '{distroName}' resolves through a filesystem alias instead of an exact app-owned path entry.";
216+
return false;
217+
}
218+
219+
if (exists && attributes.HasFlag(FileAttributes.ReparsePoint))
220+
{
221+
error = $"App-owned WSL path '{installPath}' is a reparse point; remove it manually and retry setup.";
222+
return false;
223+
}
224+
225+
error = "";
226+
return true;
227+
}
228+
229+
private static bool TryGetExistingAttributes(
230+
string path,
231+
out bool exists,
232+
out FileAttributes attributes,
233+
out string error)
234+
{
235+
try
236+
{
237+
attributes = File.GetAttributes(path);
238+
exists = true;
239+
error = "";
240+
return true;
241+
}
242+
catch (FileNotFoundException)
243+
{
244+
attributes = default;
245+
exists = false;
246+
error = "";
247+
return true;
248+
}
249+
catch (DirectoryNotFoundException)
250+
{
251+
attributes = default;
252+
exists = false;
253+
error = "";
254+
return true;
255+
}
256+
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or System.Security.SecurityException)
257+
{
258+
attributes = default;
259+
exists = false;
260+
error = $"Cannot verify managed WSL path '{path}': {ex.Message}";
261+
return false;
262+
}
263+
}
264+
265+
private static bool IsValidDistroName(string name)
266+
=> name.Length <= MaxDistroNameLength &&
267+
char.IsAsciiLetterOrDigit(name[0]) &&
268+
char.IsAsciiLetterOrDigit(name[^1]) &&
269+
name.All(IsAllowedDistroNameCharacter);
270+
271+
private static bool IsAllowedDistroNameCharacter(char value)
272+
=> char.IsAsciiLetterOrDigit(value) || value is '.' or '_' or '-';
273+
274+
private static bool IsLegacyTeardownOnlyName(string? name)
275+
=> !string.IsNullOrWhiteSpace(name) &&
276+
!IsValidDistroName(name) &&
277+
IsSafeManagedPathSegment(name, out _);
278+
279+
private static bool IsSafeManagedPathSegment(string? name, out string error)
280+
{
281+
if (string.IsNullOrWhiteSpace(name))
282+
{
283+
error = "WSL distro name is required.";
284+
return false;
285+
}
286+
287+
if (!string.Equals(name, name.Trim(), StringComparison.Ordinal) ||
288+
name.EndsWith('.') ||
289+
name is "." or ".." ||
290+
Path.IsPathRooted(name) ||
291+
name.IndexOfAny(InvalidFileNameChars) >= 0 ||
292+
name.Contains(Path.DirectorySeparatorChar) ||
293+
name.Contains(Path.AltDirectorySeparatorChar) ||
294+
IsReservedDeviceName(name))
295+
{
296+
error = $"Invalid managed WSL distro name '{name}'. The name must be one unambiguous Windows path segment.";
297+
return false;
298+
}
299+
300+
error = "";
301+
return true;
302+
}
303+
304+
private static bool IsReservedDeviceName(string name)
305+
{
306+
var stem = name.Split('.')[0].TrimEnd(' ', '.');
307+
return ReservedDeviceNames.Contains(stem);
308+
}
309+
310+
private static string NormalizePath(string path)
311+
=> Path.TrimEndingDirectorySeparator(Path.GetFullPath(path));
312+
313+
private static bool PathEquals(string? left, string right)
314+
=> string.Equals(left, right, PathComparison);
315+
}

‎src/OpenClaw.SetupEngine/Program.cs‎

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,19 @@ public static async Task<int> Main(string[] args)
164164
}
165165
Console.WriteLine();
166166

167+
if (!uninstall &&
168+
!wizardOnly &&
169+
!DistroInstallPathPolicy.TryGetNewInstallPath(
170+
localDataDir ?? SetupContext.ResolveLocalDataDir(),
171+
config.DistroName,
172+
out _,
173+
out var distroPathError))
174+
{
175+
Console.Error.WriteLine(
176+
$"ERROR: {DistroInstallPathPolicy.WithLegacyReplacementGuidance(config.DistroName, distroPathError)}");
177+
return 2;
178+
}
179+
167180
if (dryRun && !uninstall)
168181
{
169182
Console.WriteLine("DRY RUN: config validated, exiting.");
@@ -251,13 +264,10 @@ public static async Task<int> Main(string[] args)
251264
result = await pipeline.UninstallAsync(ctx);
252265

253266
// Post-rollback tray-artifact cleanup (autostart, run.marker, settings, logs)
254-
if (result.Outcome == PipelineOutcome.Success || result.Outcome == PipelineOutcome.Failed || result.Outcome == PipelineOutcome.Cancelled)
267+
if (SetupPipeline.ShouldRunTrayArtifactCleanup(result, config.DryRun))
255268
{
256-
if (!config.DryRun)
257-
{
258-
logger.Info("Running tray-artifact cleanup...");
259-
TrayArtifactCleanup.Run(ctx, preserveLogs, autoStartName, startupTaskName);
260-
}
269+
logger.Info("Running tray-artifact cleanup...");
270+
TrayArtifactCleanup.Run(ctx, preserveLogs, autoStartName, startupTaskName);
261271
}
262272
}
263273
else

0 commit comments

Comments
 (0)