Skip to content

Preserve or reject non-UTF-8 .wslconfig files before modification #1193

Closed

Description

@joelagnel

Problem

WslGlobalConfigManager decodes every existing .wslconfig as permissive UTF-8 and rewrites the updated document as UTF-8.

private static Utf8Document ReadUtf8Document(string path) => DecodeUtf8(File.ReadAllBytes(path));
private static Utf8Document DecodeUtf8(byte[] bytes)
{
var hasBom = bytes.AsSpan().StartsWith(Encoding.UTF8.Preamble);
var text = Encoding.UTF8.GetString(bytes, hasBom ? Encoding.UTF8.Preamble.Length : 0, bytes.Length - (hasBom ? Encoding.UTF8.Preamble.Length : 0));
var newLine = text.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
return new(text, hasBom, newLine);
}
private static byte[] EncodeUtf8(string text, bool includeBom)
{
var payload = Encoding.UTF8.GetBytes(text);
if (!includeBom)
return payload;
var preamble = Encoding.UTF8.Preamble;
var result = new byte[preamble.Length + payload.Length];
preamble.CopyTo(result.AsSpan());
payload.CopyTo(result, preamble.Length);
return result;
}

This is unsafe for existing configuration files that use UTF-16 or contain invalid UTF-8 bytes:

  • UTF-16 content is decoded as NUL-filled or otherwise malformed text.
  • Invalid UTF-8 bytes are silently replaced by the default decoder fallback.
  • A successful mirrored-networking update rewrites the document as UTF-8, potentially corrupting unrelated user configuration.

The existing encoding test covers only UTF-8 with and without a BOM:

[Theory]
[InlineData("\n", false, false)]
[InlineData("\n", false, true)]
[InlineData("\n", true, false)]
[InlineData("\n", true, true)]
[InlineData("\r\n", false, false)]
[InlineData("\r\n", false, true)]
[InlineData("\r\n", true, false)]
[InlineData("\r\n", true, true)]
public void ApplyMirroredNetworking_PreservesLineBoundariesAndEncoding(
string newLine,
bool includeBom,
bool includeFinalNewLine)
{
Directory.CreateDirectory(_root);
var configPath = Path.Combine(_root, "wslconfig");
var backupPath = Path.Combine(_root, "backup");
var originalText = $"[experimental]{newLine}autoMemoryReclaim=gradual{newLine}" +
$"[wsl2]{newLine}memory=8GB" +
(includeFinalNewLine ? newLine : string.Empty);
var originalBytes = Encode(originalText, includeBom);
File.WriteAllBytes(configPath, originalBytes);
var manager = new WslGlobalConfigManager(configPath, backupPath);
var result = manager.ApplyMirroredNetworking();
Assert.True(result.Changed);
var updatedBytes = File.ReadAllBytes(configPath);
Assert.Equal(includeBom, updatedBytes.AsSpan().StartsWith(Encoding.UTF8.Preamble));
var updatedText = Decode(updatedBytes);
Assert.Contains($"memory=8GB{newLine}networkingMode=mirrored", updatedText);
Assert.DoesNotContain("memory=8GBnetworkingMode", updatedText);
Assert.Contains($"[experimental]{newLine}autoMemoryReclaim=gradual", updatedText);
Assert.Equal(includeFinalNewLine, updatedText.EndsWith(newLine, StringComparison.Ordinal));
Assert.Equal(WslGlobalConfigRestoreResult.Restored, manager.RestoreIfUnchanged());
Assert.Equal(originalBytes, File.ReadAllBytes(configPath));
}

Impact

Setup can silently corrupt a user-owned global WSL configuration while enabling mirrored networking. Although rollback retains the original bytes, a successful setup leaves the rewritten file in place, and rollback is not a substitute for safe input handling.

Expected behavior

  • Detect supported encodings before parsing.
  • Support and preserve UTF-8, UTF-8 with BOM, UTF-16 LE, and UTF-16 BE.
  • Preserve the original BOM and newline convention when writing.
  • Use strict decoder fallbacks so invalid byte sequences fail closed.
  • Reject unsupported or invalid input without modifying the config, backup, or rollback metadata.
  • Continue restoring the exact original bytes during rollback.

Tests

Add byte-level coverage for:

  • UTF-8 with and without BOM
  • UTF-16 LE with and without BOM, if BOM-less detection is intentionally supported
  • UTF-16 BE
  • CRLF and LF documents
  • Invalid UTF-8 input
  • Unsupported input remains byte-for-byte unchanged
  • Apply and rollback preserve the original encoding and bytes

Raised by @larroy during the PR #1178 review follow-up.

Activity

  1. added
    clawsweeper:needs-live-repro
    impact:data-loss
    issue-rating: 🐚 platinum hermit
    P2
    on Aug 21, 2026
  2. clawsweeper commented on Aug 21, 2026

    @clawsweeper

    Codex review: keeping this open for maintainer follow-up; there is still a little grit to resolve. Reviewed August 21, 2026, 3:59 PM ET / 19:59 UTC.

    Summary
    Current main does not modify the host .wslconfig, but the active linked Local AI PR introduces that path and the reported non-UTF-8 corruption risk needs a targeted correction before it can land.

    Reproducibility: no. current-main reproduction exists because main has no host .wslconfig writer; the supplied linked-PR source path provides a clear source-level reproduction target using a UTF-16 or invalid-UTF-8 file.

    Regression provenance
    Possible regression — suspected (reviewed change). No predecessor PR is attributed.

    Root-cause cluster
    Relationship: canonical
    Canonical: #1193
    Summary: This is the focused encoding-safety follow-up for the host configuration path introduced by the active Local AI PR.

    Members:

    Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

    Ways to help us reproduce this

    • Add a screenshot or short recording showing the behavior.
    • Add expected vs actual behavior.
    • Include redacted logs or terminal output.

    Next step
    An active paired PR already owns the host configuration path, so this issue should guide its branch-level repair rather than start a competing fix PR.

    Review details

    Best possible solution:

    Repair the linked PR with a small encoding-preserving read/write helper, strict decoder fallbacks, byte-level regression tests, and a no-mutation failure path for unsupported input.

    Do we have a high-confidence way to reproduce the issue?

    No current-main reproduction exists because main has no host .wslconfig writer; the supplied linked-PR source path provides a clear source-level reproduction target using a UTF-16 or invalid-UTF-8 file.

    Is this the best way to solve the issue?

    Yes. Strictly decoding supported encodings and failing before any mutation is the narrowest way to preserve user configuration while retaining the requested mirrored-networking update.

    AGENTS.md: found and applied where relevant.

    Remaining risk / open question:

    • Landing the linked PR without strict byte decoding can silently rewrite a user-owned UTF-16 or invalid-byte .wslconfig as malformed UTF-8 after a successful setup run.

    Codex review notes: model internal, reasoning high; reviewed against d3ed6c78bf14.

    Label changes

    Label changes:

    • add P2: The reported setup path can corrupt user-owned configuration, but it is confined to an unmerged opt-in feature path.
    • add impact:data-loss: A successful update can overwrite unrelated .wslconfig bytes and lose the user's original configuration encoding.
    • add issue-rating: 🐚 platinum hermit: Current issue advisory state selects this label.
    • add clawsweeper:needs-live-repro: Current issue advisory state selects this label.

    Label justifications:

    • P2: The reported setup path can corrupt user-owned configuration, but it is confined to an unmerged opt-in feature path.
    • impact:data-loss: A successful update can overwrite unrelated .wslconfig bytes and lose the user's original configuration encoding.
    Evidence reviewed

    What I checked:

    • Current-main ownership boundary: Current main writes the per-distro /etc/wsl.conf through ConfigureWslInstanceStep; a current-tree search found no host .wslconfig writer or WslGlobalConfigManager, so this issue is not already fixed or shipped on main. (src/OpenClaw.SetupEngine/ConfigureWslInstanceStep.cs:66, d3ed6c78bf14)
    • Active implementation candidate: The supplied issue context identifies WslGlobalConfigManager lines 127-148 at the open Local AI PR head as the permissive decode-and-rewrite path. That PR is actively landing, so the paired issue should remain open until the branch repairs it. (src/OpenClaw.SetupEngine/WslGlobalConfigManager.cs:127, 31dffdb0dbd9)
    • Setup-path provenance: Blame assigns the current WSL configuration step to the setup refactor commit, which introduced the focused owner currently responsible for WSL configuration behavior. (src/OpenClaw.SetupEngine/ConfigureWslInstanceStep.cs:66, b37307cbd51f)
    • Release check: The supplied latest release predates current main, and current main has no host .wslconfig manager. There is therefore no release containing the requested behavior or a fix.

    Likely related people:

    • Barbara Kudiess: Authored the current ConfigureWslInstanceStep during the setup refactor that owns WSL configuration on main. (role: recent setup-area contributor; confidence: high; commits: b37307cbd51f; files: src/OpenClaw.SetupEngine/ConfigureWslInstanceStep.cs)
    • larroy: The issue records this as a follow-up raised during review of the linked Local AI PR. (role: reviewer who raised the encoding follow-up; confidence: medium; files: src/OpenClaw.SetupEngine/WslGlobalConfigManager.cs)
    How this review workflow works
    • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
    • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
    • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
    • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
    • Maintainers can also comment @clawsweeper review to request a fresh review only.
    • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
    • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
    • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
  3. added
    status: 🚢 actively landing
    on Aug 25, 2026
  4. added
    clawsweeper:bulk-filed
    clawsweeper:needs-maintainer-review
    clawsweeper:no-new-fix-pr
    clawsweeper:source-repro
    issue-rating: 🦞 diamond lobster
    and removed
    issue-rating: 🐚 platinum hermit
    clawsweeper:needs-live-repro
    on Aug 25, 2026
  5. locked as resolved and limited conversation to collaborators on Aug 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P2clawsweeper:bulk-filedclawsweeper:needs-maintainer-reviewclawsweeper:no-new-fix-prclawsweeper:source-reproimpact:data-lossissue-rating: 🦞 diamond lobsterstatus: 🚢 actively landing

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions