Skip to content

feat(windows): sandbox Windows subprocess spawns through WSL2 - #7140

Closed
GoZippy wants to merge 1 commit into
kirodotdev:mainfrom
GoZippy:feat/windows-wsl2-sandbox
Closed

GoZippy wants to merge 1 commit into
kirodotdev:mainfrom
GoZippy:feat/windows-wsl2-sandbox

Conversation

@GoZippy

@GoZippy GoZippy commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Windows has no OS-level sandbox backend of its own, so sandbox.wrap_argv()
fail-closes for every subprocess spawn that is not an explicitly-identified
kiro-cli spawn (PR #5620's delegation). Concretely: app install/enable
scripts, script hooks, and command cron jobs either refuse outright with
SandboxUnavailableError, or (command cron jobs specifically) are refused
before wrap_argv is even reached, because Git-for-Windows's sh.exe is
bash and performs brace expansion that would hide a credential path from the
cron command vet gate. The only documented remedy today is
agent.sandbox_allow_unsandboxed_exec=true, which removes isolation
entirely for the affected paths.

Meanwhile WSL2 — already installed on a meaningful share of Windows dev
machines — genuinely exposes working Linux user namespaces
(sandbox.is_wsl()'s own docstring already says so), but nothing in the
codebase reaches into it.

Why it matters

This is a first-run-adjacent outage for a common Windows workflow: installing
a Kiro Crew app (the built-in App Store) runs the app's onEnable script
through exactly this fail-closed path, and fails with no better remedy than
"turn off isolation everywhere." Command cron jobs are simply unsupported on
Windows today. Both are one WSL2 distro away from working with real
isolation instead of none.

What changed (motivation → approach → change)

Adds agent.sandbox: "wsl2" (opt-in, never auto-selected — the same
positive-identity posture PR #5620 established for Kiro CLI delegation) as a
third selectable backend on Windows. It reuses the existing Linux
namespace launcher script unmodified
— same unshare(CLONE_NEWUSER) +
bind-mount logic — executed inside a WSL2 distribution's real kernel via
wsl.exe, rather than reimplementing sandbox logic for a fourth platform.

Scope is deliberately narrow: only the three call sites that already build
POSIX sh/bash -c argv benefit — app lifecycle scripts
(apps/lifecycle_scripts.py), command cron jobs (cron_script.py,
previously unsupported on Windows entirely — WSL2's /bin/sh is a real
POSIX shell, unlike Git-for-Windows's bash-flavored sh.exe, so this is a
genuine capability unlock, not just a re-route), and script hooks
(hooks.py, previously locked to cmd.exe syntax on Windows — with wsl2
selected they use the same /bin/sh -c form macOS/Linux already do, so a
POSIX-shell hook needs no rewrite). Single portable-binary invocations
(git, the AWS CLI, tectonic, Piper) are unaffected either way: no shell
is involved, so routing them through a Linux VM would buy no isolation and
would need Windows↔WSL path translation for every argument.

Complements, does not duplicate, the open #6808 (read-only WSL2 discovery in
the Electron desktop shell) — that PR's own scope note explicitly defers "a
settings UI plus gateway spawn routing into the chosen distro" as follow-up
work once real requirements are known; this is that follow-up, in the Python
gateway rather than the Electron shell, since the gateway is what actually
calls wrap_argv.

Mechanics, and two bugs found and fixed while proving them live:

  • WSL_UTF8=1 is forced on every wsl.exe invocation. Verified live:
    without it, WSL emits UTF-16LE and a plain text=True subprocess capture
    either raises UnicodeEncodeError or silently mis-decodes — corrupting
    every string comparison downstream (distro listing, stderr
    classification).
  • Launcher staging is one wsl.exe call, writing to a Python-generated
    random name (secrets.token_hex(16)) under set -C (noclobber) rather
    than a name captured from the guest's own mktemp. An earlier two-call
    form (create, then a separate write+chmod) both hit a real WSL2 quirk —
    a command substitution combined with piped stdin in one wsl.exe -- sh -c
    invocation reproducibly drops the captured value, verified live — and,
    caught in review, left an empty, discoverable file exposed to a same-UID
    sibling for the whole gap between the two round trips. Naming the file in
    Python needs no substitution at all, closing both at once; set -C also
    refuses the write outright if the target already exists, rather than
    silently overwriting a file a sibling pre-created.
  • uid/gid/home are resolved inside the guest, not read from the
    Windows-side builder process (which has no os.getuid() at all).
    _build_launcher_script gained an identity override for this — every
    real Linux caller leaves it None and sees no behavior change.
  • os.path.join → posixpath.join for the launcher script's
    home-relative path construction: identical behavior on real Linux
    (os.path is posixpath there), but load-bearing when the builder is
    Windows Python, which would otherwise embed a backslash into a script
    meant to run on a Linux filesystem.
  • A caller's working directory threads through as wsl.exe --cd, not
    the ordinary cwd= a caller passes to Popen — that sets wsl.exe's own
    (Windows-side) launch directory, not the guest shell's. The Windows→WSL
    path translation is verified against the guest's live mount table before
    being trusted (wslpath itself proved unreliable for this — verified
    live, it silently drops backslashes on some multi-segment Windows paths
    even invoked through a plain argv list, no shell involved), and refuses
    to translate rather than guess if the guest doesn't mount drives at the
    default /mnt/<letter> location.
  • Probing never blocks the gateway event loop. _probe_wsl2 mirrors
    _probe_unshare's exact discipline: on-loop calls defer to a background
    thread and return a transient (never-cached) failure immediately; off-loop
    calls retry once. This matters more here than for the Linux probe — a cold
    WSL2 round trip measured 7.5s live, far slower than the Linux
    unshare() syscall.
  • Failure is fail-closed throughout: an unreadable config never grants a
    looser backend than configured (mirrors _allow_unsandboxed_exec's own
    contract), and a probe or staging failure raises the same
    SandboxUnavailableError shape the existing no-backend path uses, with a
    remedy naming the specific fix (wsl --install, wsl --install -d <name>, or the shared AppArmor-class guidance when the guest's own kernel
    refuses unshare).

Dashboard: agent.sandbox's Settings dropdown and the PATCH /api/config/kirocrew allowlist now read live selectable values ("wsl2"
offered only when plausible — Windows, with wsl.exe present) instead of a
static list, following the exact pattern already established for
agent.acp_backend — the same file even names the reason: "three
independent derivations is how the old literal list drifted."

Distribution picker. A host can have several WSL2 distributions — this
was raised in review on a real machine with two Ubuntu installs plus Docker
Desktop's own WSL2 backend. agent.sandbox_wsl_distro now has its own live
picker (same schema pattern as above), populated from wsl.exe -l -v
(10s-cached to avoid repeat shellouts on rapid Settings loads) and
deliberately excluding Docker Desktop's internal utility instances
(docker-desktop, docker-desktop-data) from what is offered — they are
minimal VMs purpose-built for the container runtime, not general-purpose,
and not guaranteed to ship unshare or the other tools the launcher needs.
This is a picker default, not a hard restriction: the field stays a plain
pattern-matched string at the write layer, so an operator who deliberately
wants one can still set it by hand. Verified live against a real host
carrying exactly this shape (one general-purpose distro, one Docker Desktop
instance): the raw listing shows both, the picker offers only the real one.

On Windows Sandbox as an alternative backend (raised in review,
referencing Microsoft's own docs): investigated and not pursued here for
two disqualifying reasons rather than a scope call — "Windows Sandbox
currently doesn't allow multiple instances to run simultaneously" (a
machine-wide, one-at-a-time limitation that rules out sandboxing concurrent
spawns), and there is no documented headless launch, synchronous completion
signal, or stdout/exit-code capture — LogonCommand is built for "a human
opens a window, does something, closes it," not a service dispatching a job
and reading back a result, which wrap_argv's contract requires. It is also
Pro/Enterprise/Education-only (excludes Home) and runs native Windows
executables only, with no Linux/POSIX support. This is a real gap in the
tool's automation surface, not an implementation-effort judgment call, and a
different feature (an interactive "open this untrusted thing in a disposable
desktop" tool) would be a better fit for it than this one.

Security findings from review, and the fixes

Three independent AI reviewers on the original revision of this PR converged
on the same finding, plus two more from a fourth pass. All four are fixed in
the current revision, not worked around.

The credential/keystone leak (the serious one). The wsl2 backend's
credential-hiding only masked the WSL2 guest's own home directory — a
mostly-empty account. WSL2's default DrvFs mount makes the operator's REAL
Windows filesystem reachable inside the guest at /mnt/<drive>/...,
including C:\Users\<user>\.aws/.ssh and the governance keystone under
config_dir() — none of it was masked, so a sandboxed app-lifecycle script,
command cron, or hook could read or overwrite the operator's actual
credentials and the file security.py's _SENSITIVE_HOME_DIRS exists
specifically so the agent can never read or write. My own manual
verification (previous revision) had only planted markers in the guest's
own home, missing exactly this. Fixed: wsl_namespace_argv() now computes
the same sensitive-directory set the native backend would mask, resolves it
against the REAL Windows home, translates each entry through DrvFs, and
passes it in via the existing extra_hidden_dirs mechanism; DrvFs
verification now runs unconditionally and the function fails closed if it
cannot confirm the mount. Re-verified live with a synthetic Windows home
(never my real one) carrying marker credential files — see Manual
verification below for the actual transcript.

Launcher-staging TOCTOU. A same-UID sibling (a concurrently-sandboxed
cron job or hook — exactly the untrusted workload this backend confines)
could race the two-call staging sequence, replacing the file's content
before it ever executed. Fixed by collapsing staging to one round trip with
a set -C-protected write to an unpredictable name (see the mechanics
bullet above).

A genuinely blocking call on the dashboard's event loop.
wsl2_distro_choices() shelled out synchronously (subprocess.run, up to
30s) directly from GET /api/config/schema's handler — every Settings page
load could stall chat, cron, and the liveness heartbeat for every connected
client. This is exactly the discipline the rest of this PR was careful
about (_probe_wsl2's own never-block-on-loop handling) but missed at this
one call site. Fixed: every live-enum supplier in that handler now
dispatches through the existing subprocess_executor() pool.

WSLENV. WSL forwards a Windows env var into the guest shell only when
WSLENV names it — setting a var on the Windows-side env= a caller passes
to wsl.exe does not make it visible inside the guest. So
$KIROCREW_HOOK_EVENT/$KIROCREW_HOOK_CONTEXT and lifecycle scripts'
$NONINTERACTIVE/extra_env all read empty under wsl2 despite the docs'
existing claim they work. Fixed with a small wsl2_env_passthrough()
helper both call sites use for exactly the metadata keys they inject — never
the platform-baseline ones (PATH, HOME, ...), which the guest must
supply from its own values, not the Windows host's.

A second look at review turned up two more, this time in cron_script.py.
cron_script.py has TWO wrap_argv call sites, and they are not
interchangeable once wsl2 exists:

  • The command-cron shell resolver trusted /bin/sh by name instead of
    probing it
    , unlike every other platform's candidate. The existing
    _shell_is_posix_strict probe (already sandbox-routed — it calls
    wrap_argv on the candidate itself) would have caught an unusual distro
    whose /bin/sh is secretly bash, transparently, with zero new WSL2-specific
    probe code — but the resolver never called it for this branch, just
    returned /bin/sh directly. Fixed by calling it, with a distro-qualified
    cache key
    (wsl2:<distro>:/bin/sh): /bin/sh names a different binary
    depending on which distro is selected, and the un-qualified cache would
    have let a verdict from one distro vouch for a different one after
    agent.sandbox_wsl_distro changes.
  • run_script_sandboxed would have silently broken the moment wsl2 was
    selected.
    It builds a native-Windows argv ([sys.executable, launcher_path]) and passed it through wrap_argv with zero wsl2
    awareness — unlike the command-cron path above. Once an operator selected
    agent.sandbox: "wsl2", this currently-working Windows feature (script
    crons) would have routed through the guest launcher, which appends argv
    verbatim after itself expecting a POSIX command; a Windows path is neither
    a valid guest path nor runnable there. This is a real functional
    regression, not just a security gap. Fixed by giving wrap_argv a new
    posix_shell_argv parameter (default True — unchanged for the three
    call sites that genuinely build POSIX argv); this call site passes
    False, so wrap_argv reports wsl2 unavailable for it and falls through
    to the exact fail-closed/sandbox_allow_unsandboxed_exec handling Windows
    already had for script crons before this backend existed.

Both verified live: the shell probe against the real distro's actual
/bin/sh (dash, correctly accepted), and the script-cron guard by spying on
wsl_namespace_argv — with wsl2 selected and posix_shell_argv=False it
is never called, and the call fails closed with the identical message
Windows gave for this case before wsl2 existed.

A fifth thing surfaced by this review that is deliberately NOT fixed
here.
Investigating the credential-masking finding above meant diffing
_build_launcher_script's own sensitive-dir list — shared by every backend,
including this one — against security.sensitive_home_dirs()'s full,
authoritative set. The gap is large: most of the .kiro/crew/* governance
tree (security_policy.json, admission_policy.json, profiles/, and
more) is not masked at its default location, on any platform — I proved
this live by planting a keystone marker in the WSL2 guest's own home (using
the identical _build_launcher_script mechanism native Linux uses, no
Windows/DrvFs involvement at all) and reading it straight through the
sandbox. This backend has exact parity with what native Linux/macOS already
does today, which is what this PR set out to deliver — but "parity with
native" is not the same claim as "the keystone is masked," and reconciling
two independently-maintained lists across a launcher every backend shares
is a bigger, riskier change than a platform port should carry. Filed
separately as #7332 rather than folded into this PR; this backend inherits
whatever that resolves to automatically once landed.

The biggest finding, from a first-principles review that counted real call
sites.
wrap_argv/sandboxed_spawn_argv are shared chokepoints with
dozens of callers across the codebase, most of which build native-Windows
executable invocations (an MCP server spawn, an npm install, a terminal
command, a git call) rather than POSIX shell argv. My initial revision
defaulted the new posix_shell_argv parameter to True — opt-out: only
callers known NOT to be POSIX-shaped had to say so. Counting actual call
sites, that polarity meant roughly nine unexamined production spawns —
in cron_script.py (an MCP server spawn), mcp_gateway/resolve_once.py,
five dashboard/handlers/*.py modules, and git_coord.py — would have
silently started routing through the wsl2 guest launcher the moment an
operator selected it, each appending a Windows-shaped argv after a Linux
launcher expecting a POSIX command. This directly contradicted my own "scope
is deliberately narrow" claim earlier in this description, which the
reviewer caught as a real inconsistency between what I said and what the
code did.

Fixed by inverting the default to False (opt-in): only the three
genuinely-POSIX call sites (apps/lifecycle_scripts.py, cron_script.py's
run_command_sandboxed, hooks.py) pass True explicitly. Every other
caller — all nine named above, and any future one — now keeps its exact
pre-wsl2 behavior with zero code change of its own, which is what the scope
description always claimed and what the default now actually guarantees
rather than merely asserts. Locked with a new test that asserts the default
on the real function signatures (wrap_argv, wrap_argv_async,
sandboxed_spawn_argv, sandboxed_spawn_argv_async), not just the wsl2
dispatch branch, so a future edit cannot silently flip it back. This also
surfaced two pre-existing tests (test_cron_cancel.py,
test_mcp_cron_security.py) whose wrap_argv mocks had a signature too
narrow for the new keyword argument — fixed alongside.

Tests

  • test/test_sandbox_wsl2.py (42 tests): config-reading fail-closed
    behavior, detect_backend's cache policy (positive/permanent/transient,
    mirroring the existing Linux probe's own pinned tests), the
    never-block-on-loop discipline, the pure path-translation function, the
    wrap_argv dispatch arm (extra_hidden_dirs rejection, failure→
    SandboxUnavailableError wrapping, no-cleanup-path honesty), the
    _no_backend_guidance remedy selection, and the distro-picker's filtering
    and caching. Added in this revision, driving wsl_namespace_argv()
    directly rather than through the wrap_argv-level mock the tests above
    use (that mock is exactly what would hide a regression in this function):
    extra_hidden_dirs reaching _build_launcher_script with the
    DrvFs-translated real .aws/.ssh paths (this test caught a real gap
    during development — .ssh isn't in the base sensitive-dir list, it is
    masked by a separate HIDE_SSH mechanism scoped to the guest home only,
    which needed its own explicit translation), the fail-closed path when
    DrvFs can't be verified, the single-round-trip staging with its
    noclobber guard, staged-path uniqueness across calls, and
    wsl2_env_passthrough's no-op/merge/set behavior. No test depends on a
    real WSL2 host — every wsl.exe boundary is mocked, matching how feat(desktop): add WSL2 runtime discovery with host runtime readout #6808's
    own WSL2 discovery work is tested. Two rounds of real bugs in the tests
    themselves, both caught by CI rather than locally
    : (1) the three new
    tests above called the real Path.home() unmocked to build their expected
    masking paths — on my Windows dev machine that happens to already be
    drive-rooted, so they passed there, but the Linux CI runners this matrix
    also uses resolve it to /home/runner, which wsl_namespace_argv() then
    correctly (fail-closed) refused to translate; (2) fixing that alone still
    left _relocated_policy_cache_dirs() and _voice_runtime_sandbox_paths()
    reading the REAL config_dir()/KIROCREW_HOME this repo's own test
    harness pins to an isolated Linux tmp dir per test — inconsistent with the
    now-mocked Windows home, so the "is this relocated from the default?"
    check always answered yes and handed back an unmasked POSIX path. Both are
    now explicitly neutralized in the test fixture rather than left to the
    ambient environment, the same class of host-dependence bug as the ntpath
    fix below, this time in test code rather than the function under test.
  • test/test_spawn_audit.py: one BENIGN_SPAWNS entry for the new
    sandbox.py::_wsl_run chokepoint — the centralized point every WSL2
    helper's wsl.exe invocation routes through. Sandboxing it would be
    circular (it constructs the boundary an agent-influenced spawn is later
    confined by), the same disposition already given to
    ensure_agents_slice_limits.
  • test/test_sandbox_wsl2.py: one more test for wrap_argv's new
    posix_shell_argv parameter — with it False, wsl_namespace_argv must
    never be called even when detect_backend says "wsl2", and the call must
    fail closed exactly like Windows' pre-existing no-backend path.
  • test/test_cron_script.py (TestCommandCronShellResolution, 3 new
    tests): the wsl2 branch of _resolve_command_shell actually calls
    _shell_is_posix_strict (not trusting /bin/sh by name), rejects when the
    probe fails, and — driving the real (unmocked) _POSIX_STRICT_CACHE
    rather than stubbing the probe away — that a cached verdict for one distro
    is never consulted for a different one.
  • Full backend suite, this branch vs. current upstream/main in a fresh
    worktree: 265 passed, 74 skipped, 0 failed (skips are the existing
    Linux/macOS-only tests, expected on Windows) — re-run a second time after
    upstream advanced one commit mid-review (#7053, unrelated numeric config
    bounds) to confirm parity with its new test_config_load_bounds_parity.py
    ratchet too.
  • flake8, isort, this fork's harness-parity gate: clean.
  • Frontend: tsc, eslint, and — for the distro-picker's new UI text —
    the full npm run i18n:check gate (all 19 checks pass) plus the
    catalogParity.test.ts suite (77/77) confirming key parity across all 12
    shipped languages, including the regenerated en-XA pseudolocale. The
    non-English translations are a good-faith first pass (produced without a
    native reviewer for several of the 10 languages); happy to have a
    maintainer or community translator refine them — the catalog already
    tracks this class of debt via its own "untranslated passthrough" metric,
    so it is not a novel category of imperfection.
  • black (pinned 26.3.1, matching pyproject.toml/setup.cfg exactly):
    clean. This venv's Python 3.12.5 hits a documented upstream AST safety bug
    that makes black refuse to run at all (.fork/preflight.sh itself
    detects and skips this case) — worked around by installing the exact
    pinned version under a separate Python 3.10 interpreter instead of
    guessing at output from a mismatched version.
  • mypy: now confirmed clean against the current commit
    (.fork/preflight.sh lint, mypy --cache-dir ... src/kiro_crew/ PASS) —
    the earlier I/O-bound timeouts on this host did not recur this round.
  • Rebased onto upstream/main at b3c3151c3 (from this PR's original base,
    122 commits behind) after CI on the prior push caught a transient upstream
    inconsistency — .github/agent-sdk-boundary-baseline.txt briefly
    recorded a stale count for src/kiro_crew/subagent.py — already
    self-corrected upstream by the time of the rebase. Full suite re-run
    post-rebase: 2627 passed, 183 skipped, 0 failed.
  • Rebased a second time onto upstream/main at 7eea2bea1 (97 commits
    further) after the PR sat long enough for mergeable to flip to
    CONFLICTING, which was also the likely reason CI stopped triggering on
    the prior commit entirely (zero check-runs registered, even while CI's own
    queue was otherwise healthy). One real conflict, in hooks.py: an
    unrelated upstream commit (fix(dashboard): preserve access-control xattrs across steering and file writes #6961, xattr access-control preservation) had
    landed content adjacent to this PR's own hunk; the first conflict
    resolution pass accidentally duplicated a block upstream had since
    refactored into an atomic_write import (caught by flake8 F811, fixed
    by deferring to the import as upstream now does). Re-verified post-rebase:
    .fork/preflight.sh fast/lint/surface all green for this PR's own
    diff — lint's one failure (Frontend Lint & Type Check, a TabsProps
    type mismatch in tabs.tsx/DiscoverPage.tsx/McpManagement.tsx/
    SystemPage.tsx) and surface's 10 failures (9 WinError 1314
    symlink-privilege gaps plus 1 already-cataloged timing flake) all land in
    files this PR does not touch, confirmed pre-existing via
    git diff upstream/main HEAD --stat -- <file> returning empty for each.
    The directly-touched files (test_sandbox_wsl2.py and the other five
    modified test modules): 321 passed, 6 skipped, 0 failed.
  • Two real bugs found from this PR's own CI (both fixed, not reformatted
    around): (1) black had reflowed two # fmt: skip-protected
    os.chmod(...) lines onto three lines each, which silently broke the
    trailing # nosemgrep suppression's same-line anchoring and produced two
    fresh Semgrep findings on lines this PR never touches — restored to the
    original single-line form. (2) _translate_windows_path_to_wsl2 used
    os.path.splitdrive, which is posixpath.splitdrive on a POSIX host and
    never recognizes a drive letter — invisible on a Windows dev machine
    (where os.path already is ntpath), but it rejected every real
    Windows path on Linux CI. Fixed by importing ntpath explicitly, since
    this function parses a Windows-style path string and its behavior must
    not depend on the host running the test.
  • A third bug, from upstream CI on the post-rebase push: Backend Tests (namespace sandbox) failed one test —
    test/test_script_hooks.py::TestRunScriptHook::test_subprocess_routes_allowlist_through_safe_spawn_funnel
    mocks sandboxed_spawn_argv with a narrow (argv, *, env) signature; this
    PR's own hooks.py change now calls it with an added posix_shell_argv
    keyword, which the mock didn't accept. The same class of fix already
    applied to two other test files during earlier review; this one file was
    missed. Fixed by widening the mock to (argv, *, env, **kwargs).

Manual verification

Live-tested end to end against a real WSL2/Ubuntu-26.04 host, including the
isolation itself, not just "the command ran":

  • wrap_argv(["/bin/bash", "-c", …], mode="strict", cwd=<a real Windows path>) → executed inside the guest with uid=1000(sysop), correct
    $HOME, and pwd landing exactly at the --cd-translated path.
  • apps/lifecycle_scripts.run_lifecycle_script (the exact path a Crew
    Manager-style app install failure hits) reproduced the original failure
    first, then confirmed the fix: first on-loop attempt defers transiently
    (background warm thread kicked, no block), second attempt ~20s later
    succeeds with INSTALL_SCRIPT_RAN, correct translated cwd, correct uid.
  • Re-ran the identical live verification against this PR's actual diff
    applied to a fresh upstream/main worktree (not just the fork's dev-beta
    branch it was originally developed against) — same result, confirming the
    ported diff and not just the original implementation.
  • The credential-masking fix, tested against the correct threat model.
    A prior verification pass here planted markers only in the WSL2 guest's
    own home — exactly the gap review caught. This pass built an isolated,
    synthetic Windows-side home (never my real one), planted
    .aws/credentials and .ssh/id_rsa markers there, pointed Path.home()
    at it (USERPROFILE), and called wsl_namespace_argv() for real against
    a live distro. Both markers, read through their real DrvFs-translated
    /mnt/... path from inside the sandboxed process, come back No such file or directory; a control file outside any hidden dir, same
    directory, stayed readable. This is the actual leak path the reviewers
    described, now closed and proven closed — not merely "the mechanism
    looks right."
  • WSLENV, same live-real-distro approach: a /bin/sh -c 'echo $KIROCREW_HOOK_EVENT $KIROCREW_HOOK_CONTEXT' spawn read both
    values correctly with WSLENV set to name them, and empty without it —
    confirming the forwarding is real, not just constructed correctly by
    wsl2_env_passthrough's own (also unit-tested) string logic.

Screenshots / video

The Settings > Developer > Config panel, with agent.sandbox set to wsl2
(the option itself is live-advertised — only offered on Windows with a
working wsl.exe — via the same schema endpoint agent.acp_backend already
uses, not a hardcoded list). Selecting it reveals the new WSL2
Distribution
row underneath, populated from this machine's real wsl -l -v output:

Sandbox set to wsl2, with the WSL2 Distribution row visible

Related Issues

Complements #6808 (does not duplicate — that PR is Electron-side discovery
only, and defers this exact gateway-side follow-up in its own scope note).
Discovered and filed #7332 (pre-existing, cross-platform gap in the shared
sandbox launcher's masked-dir list — see "Security findings from review"
above) while reviewing this PR; not fixed here, out of this PR's scope.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • No secrets, credentials, or internal references in the diff

@GoZippy
GoZippy requested review from a team and krishdhasmana August 30, 2026 23:46
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Aug 30, 2026
@GoZippy
GoZippy force-pushed the feat/windows-wsl2-sandbox branch from 126875a to 8496482 Compare August 31, 2026 06:13
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Aug 31, 2026
@GoZippy
GoZippy force-pushed the feat/windows-wsl2-sandbox branch from 8496482 to b6e26a8 Compare August 31, 2026 06:14
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Aug 31, 2026
@GoZippy
GoZippy force-pushed the feat/windows-wsl2-sandbox branch from b6e26a8 to 9a883ac Compare August 31, 2026 07:17
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Aug 31, 2026
@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5, fork) — 🟡 CONCERNS

Premise-level review of a76967c80001e5f35aa94ffdb06c29ff649738b1 via the fork AI-review pipeline — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

First-Principles-Verdict: CONCERNS

The Windows per-feature docs table ships its three rows twice, and the two copies contradict each other about the default unsandboxed posture.

Not justified as shipped

  • Item 9 — second spelling: docs/guides/windows-install.md's per-feature table keeps the edited rows ("run unconfined under this platform's default (declare sandbox_allow_unsandboxed_exec=false to refuse them)") AND appends a second trio ("need the agent.sandbox_allow_unsandboxed_exec opt-in above — … wrap_argv, which fail-closes where no OS sandbox backend exists"), separated by a blank line that splits the table. Counted: the hunk removes 3 rows and adds 6 plus a blank. The two sets state opposite defaults, and the "fail-closes" set contradicts the base's own behavior — _allow_unsandboxed_exec resolves the undeclared key True on a no-backend platform (src/kiro_crew/sandbox.py:7986), which nothing in this diff changes.
    Subtraction: delete one trio — the appended "need the opt-in / fail-closes" set, which restates the base row's "run unconfined under this platform's default" as its opposite with no code change backing it.
    Clears when: the table carries each of the three features exactly once, in one table, matching wrap_argv's actual Windows default.

What this change ships

Inventory (10 items) — 9 justified

Intent: give Windows operators real OS-level isolation for app scripts, command crons, and hooks by routing them through an opt-in WSL2 distro — an ADDITION.

  1. New opt-in agent.sandbox: "wsl2"; app install/lifecycle scripts run inside a real Linux namespace on Windows — justified
  2. Command cron jobs become possible on Windows (base doc pins them "not supported") when wsl2 is selected — justified
  3. Script hooks run POSIX /bin/sh instead of cmd.exe, only when wsl2 is selected; old default untouched — justified
  4. New config key agent.sandbox_wsl_distro plus a live Settings picker (Docker Desktop instances filtered from offers only) — justified
  5. Sandbox dropdown values now host-derived; _supply_live_enum becomes the path→callable map its own base comment prescribed ("turn it into a … map when a second dynamic enum appears", agents.py:1373) — justified
  6. New posix_shell_argv (opt-in) and cwd parameters on the spawn chokepoints; every non-opting caller keeps exact pre-wsl2 behavior, pinned by new tests — justified
  7. aws_control container forces sandbox_wsl_distro: ""; isolation test generalizes safe values by declared type (mandated by the prefix-ratchet test) — justified
  8. Fail-closed refusals naming the specific WSL2 remedy when wsl2 is selected but broken — justified
  9. Windows guide per-feature rows updated — but each row ships twice with contradictory posture — see above
  10. WSLENV passthrough helper so hook/lifecycle env vars reach the guest shell — justified

[FIRST-PRINCIPLES-REVIEWED] a76967c

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Fable 5, fork) — 🔴 BLOCK

UX-level review of a76967c80001e5f35aa94ffdb06c29ff649738b1 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: BLOCK

cannot evaluate: missing screenshots of the new Settings controls — the Sandbox picker's 'wsl2' option and the WSL2 Distribution select.

Evidence gaps

  • Sandbox select showing the new wsl2 option and its changed hint ("Switching to or from 'wsl2' takes effect after a gateway restart") — KiroCrewCfgTab.tsx — closed by a Settings screenshot from a Windows host with WSL2 present, attached to the PR description.
  • The new "WSL2 Distribution" select (visible only when sandbox = wsl2), including the "(WSL default)" option and its "Restart required…" hint — closed by a screenshot of that state, ideally both with a populated distro list and the degraded default-only list.

Watch

  • docs/guides/windows-install.md "Per-feature status on Windows": the Script cron / Command cron / Script hooks rows are added twice with divergent wording, and the blank line between the two sets splits the table — every row after it (Pull-request drawer, Issue Radar, Spec Builder) loses the header and renders as broken plain text. Every Windows reader hits this, persistently. Delete one of the two row sets (the first set also has a run-on: "…uncaught error) agent.sandbox: "wsl2" does not cover…").
  • Selecting wsl2 reports only "Saved"; the picker offers it on a bare wsl.exe presence check, so a broken setup (no distro, no python3, userns refused) is first discovered later, inside an app-install or cron failure after a restart. Remedy text there is good; the smallest fix is one clause in the sandbox hint saying availability is verified at first use and failures name the fix.

[UX-REVIEWED] a76967c

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — 🔴 changes requested (blocking)

Reviewed a76967c80001e5f35aa94ffdb06c29ff649738b1 via the fork AI-review pipeline; updated in place on each push.

1 of 1 blocking finding(s) are security-class and were withheld from adjudication, so the blocking verdict stands.

BLOCKING -- src/kiro_crew/sandbox.py:6719 -- Guest launcher writes namespace records through an untranslated Windows path
identity=identity,
WSL2 lifecycle spawn -> launcher interprets embedded Windows config_dir() as a relative guest path -> creates stray directories and PID records inside the app working tree.
Anchor: residual/crash-data-loss-corruption
Fix: Pass a DrvFs-translated namespace-record directory into _build_launcher_script.

FINDING -- src/kiro_crew/dashboard/handlers/agents.py:1383 -- function-local from kiro_crew.sandbox import wsl2_distro_choices violates top-level-imports -> Fix: move the import to module scope.

[BLOCK-MERGE] a76967c
[GPT-REVIEWED] a76967c

Adjudication (Opus 4.8) — is blocking on each finding proportionate?

I've confirmed the mechanism. Line src/kiro_crew/sandbox.py:5443 bakes _namespace_dir = {str(config_dir().resolve() / "member-memory-bindings" / "pids")!r} into the launcher script unconditionally — it is NOT gated by the new identity parameter (the patch adds if identity is None guards around every other builder-host resolution, but not this one). When wsl_namespace_argv (patch:1812) calls _build_launcher_script(..., identity=identity, ...) from native Windows Python, config_dir() resolves a Windows path (C:\Users\...\member-memory-bindings\pids), and the guest's os.makedirs/os.replace at sandbox.py:5444,5456 treat that backslash string as a single relative path component created under the guest cwd (the DrvFs-mapped workspace).

Fenced finding assessment:

F1 — Harm rung: the fence classified this residual/crash-data-loss-corruption. Conditions: sandbox.py:5443 bakes an untranslated config_dir() into the launcher; wsl_namespace_argv at patch:1812–1819 passes identity but this line has no identity is None guard (unlike every sibling resolver at patch:1331,1375,1391,1417); the parent-branch block at sandbox.py:5444–5456 runs on every launcher spawn. Recovery/self-correction: none — the stray directory accumulates and the namespace record never lands where the Windows-side reader looks. Rarity: the required condition is only "wsl2 backend selected," and the defect then fires on EVERY spawn through that backend — the opposite of an extreme/contradictory combination. I cannot complete a rarity argument, so no FLAG record exists.

[ADJUDICATION] a76967c total=0 uphold=0 downgrade=0
[GPT-ADJUDICATED] a76967c
[ADJUDICATION-FENCED] a76967c fenced=1 flagged=0
UPHOLD-FENCED F1 src/kiro_crew/sandbox.py:6719 -- The untranslated Windows config_dir() baked at sandbox.py:5443 fires on every wsl2 spawn, not a rare condition, so no rarity argument for a FLAG can be completed.
[GPT-ADJUDICATED-FENCED] a76967c

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — 🔴 BLOCK (blocking)

Design-level review of a76967c80001e5f35aa94ffdb06c29ff649738b1 via the fork AI-review pipeline — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: BLOCK

Cannot evaluate: missing screenshot of the new Settings sandbox/WSL2-distribution picker — no rendered evidence of this revision.

Blockers

Required rendered evidence missing for a reshaped Settings control set.
KiroCrewCfgTab.tsx adds a conditionally-rendered row ({cfg.agent.sandbox === 'wsl2' && (<CfgSelect … label={…wsl2_distribution}) and switches the sandbox dropdown to live schema options — a user-visible surface change under website/src/. The description's only image is https://github.com/GoZippy/KiroCrewPublic/raw/8437990…/settings-sandbox-wsl2.png, hosted off a commit outside this PR, and the workflow's evidence list records 0 downloaded attachments with 0 transport failures — so no evidence of this revision exists, and the row's rendered shape (placement, (WSL default) labeling, hint wording, behavior when the schema is in flight) cannot be judged. On a fork PR a committed image would not clear it either.
Fix: attach the screenshot directly to the PR description as a github.com/user-attachments upload.
Clears when: the description carries a user-attachments screenshot (or recording) of this revision's Settings panel with wsl2 selected and the WSL2 Distribution row visible, which the evidence workflow downloads and types as an image.

Watch

  • The guest launch chain runs attacker-influenceable code before unshare(): the native backend execs sys.executable (absolute, gateway-owned), but the wsl2 arm builds ["--", "python3", …] — wsl.exe -- routes through the guest's default shell, which resolves python3 via the guest user's PATH and may source rc files, and the guest home stays writable to sandboxed workloads (only sensitive dirs are masked; only the staging dir is sealed). A confined cron/hook that plants ~/.local/bin/python3 or an rc hook gets its code run unconfined, pre-unshare, with full DrvFs reach to the exact Windows-side credentials this PR's masking work protects. The -S flag closed the sibling usercustomize.py channel; this one is open.
    Clears when: the spawn uses wsl --exec with an absolute guest interpreter path (probed, e.g. /usr/bin/python3), or live evidence that wsl.exe -- neither PATH-resolves the command through guest-writable dirs nor sources guest rc files.
  • docs/guides/windows-install.md's per-feature table now contains the Script-cron / Command-cron / Script-hooks rows twice with divergent wording (the edited originals at one hunk, a re-written trio appended after a blank line that splits the table) — a rebase artifact shipping contradictory guidance on whether these paths "run unconfined under this platform's default" or "need the opt-in".
    Clears when: the table carries each row once.

[DESIGN-REVIEWED] a76967c

@github-actions

github-actions Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

Reviewed a76967c80001e5f35aa94ffdb06c29ff649738b1 via the fork AI-review pipeline; updated in place on each push.

Review details

No findings.

[OPUS-REVIEWED] a76967c

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Aug 31, 2026
@GoZippy
GoZippy force-pushed the feat/windows-wsl2-sandbox branch from 0d949db to d066988 Compare August 31, 2026 09:34
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Aug 31, 2026
@GoZippy
GoZippy force-pushed the feat/windows-wsl2-sandbox branch from d066988 to f8a2ab7 Compare August 31, 2026 10:19
@github-actions github-actions Bot removed the readiness: action required A blocking check or review needs attention label Aug 31, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 2, 2026
@bolichen97

Copy link
Copy Markdown
Contributor

Open PR relationship audit

This is a consolidated, point-in-time code-level audit note. It compares complete merge-base diffs and current/merged code; it does not treat a shared topic as duplication or partial coverage as completion.

Relationship findings

  • PR #6230 is OVERLAPPING relative to this PR. The goals differ or the implementations can complement each other; this is not a duplicate claim. Recommended action for PR #6230: REBASE. Both should land. Whichever merges second should carry WSLENV forwarding (or DrvFs translation) for the managed bundle variables so the Windows corporate-proxy fix survives under agent.sandbox: 'wsl2'. Files: src/kiro_crew/sandbox.py, src/kiro_crew/hooks.py.
  • PR #7414 is OVERLAPPING relative to this PR. The goals differ or the implementations can complement each other; this is not a duplicate claim. Recommended action for PR #7414: KEEP. Complementary goals, but they cannot land independently: whichever merges second must rebase, and the reconciliation is not mechanical — _BRACE_OFF_SHELLS must adopt PR #7140's cache key rather than the bare shell string, or the brace-off form recorded for a WSL2 guest shell will be applied to the native shell. Worth an explicit merge-order decision between the two authors before either lands. Files: src/kiro_crew/cron_script.py.
  • PR #7670 is OVERLAPPING relative to this PR. The goals differ or the implementations can complement each other; this is not a duplicate claim. Recommended action for PR #7670: KEEP. Large independent feature touching the same two cron spawn lines; a sequencing conflict only, already cross-referenced by its own author. Files: src/kiro_crew/cron_script.py, src/kiro_crew/sandbox.py.
  • PR #7963 is OVERLAPPING relative to this PR. The goals differ or the implementations can complement each other; this is not a duplicate claim. Recommended action for PR #7963: MERGE_DISCUSSION. Whichever lands second must extend credential_mask_applies to cover the other's new wrap_argv outcomes, or 7963's compensating control silently stops applying on the newly reachable configurations. Files: src/kiro_crew/sandbox.py. The two independent directions used different labels; the matrix conservatively retains OVERLAPPING for coordination.

No PR, Issue, label, branch, or review state was changed by the relationship-note portion of this audit.

@GoZippy

GoZippy commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

@bolichen97 — both required changes landed in 79b699302, pushed about ten hours after your review, so the CHANGES_REQUESTED state predates them. Re-review would be appreciated.

1. The guest launcher now pins -I -S, sourced from the constant rather than re-spelled — src/kiro_crew/sandbox.py:3897:

wrapped += ["--", "python3", *_LAUNCHER_INTERPRETER_FLAGS, staged_path, *argv]

The comment above it records the reason in your terms: without -S, a same-UID workload's usercustomize.py under the guest's own site-packages runs before unshare() — unconfined, with DrvFs in reach. The flags precede the script exactly as namespace_argv places them, so _launcher_script_of reads the same slot on both backends and the Description's "reused unmodified" claim now holds for the invocation too, not just the script text.

2. The Script-cron-jobs row now states the opposite of what it claimed — docs/guides/windows-install.md:356 no longer offers agent.sandbox: "wsl2" as a remedy. It reads:

agent.sandbox: "wsl2" does not cover them: a script cron is a native-Windows Python invocation, not a POSIX shell command, so the wsl2 backend reports itself unavailable for it and the job stays unsandboxed exactly as it was before wsl2 existed.

That matches cron_script.py's posix_shell_argv=False and wrap_argv's requirement, and the misleading "real isolation instead of none" reading is gone.


One further commit, unrelated to your review (1a19e9c90): the PR was red on Fork workflow-change guard for a reason that had nothing to do with wsl2. Running black over cron_script.py made it black-clean, which graduated it from .github/black-baseline.txt; check_black_formatting.py hard-fails on a graduated entry, so the line had to be pruned — but pruning touches .github/**, which the fork guard blocks outright. The two gates are individually right and jointly unsatisfiable from a fork.

Resolved the way AGENTS.md already prescribes (formatting a baselined file is optional and belongs in its own commit): the four formatting-only hunks black introduced were reverted — a logger.error reflow, an argument split, a boolean-or join, and slice spacing. The file is non-black-clean again, so it stays baselined, the baseline line is restored, and the diff against .github/ is empty. The guard now reports SKIPPED. Every functional hunk is untouched: the wsl2 imports, posix_shell_argv, and the guest /bin/sh resolution with its distro-qualified probe cache.

Verified locally before pushing: black gate passes, .github/ diff empty, test/test_cron_script.py 125 passed / 3 skipped.

Worth flagging as a repo-level issue independent of this PR: any fork PR that black-formats a baselined file hits the same deadlock, and the only escapes are reverting the formatting or a maintainer override label.

@GoZippy
GoZippy force-pushed the feat/windows-wsl2-sandbox branch from 1a19e9c to 18b35a6 Compare September 7, 2026 01:12
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: action required A blocking check or review needs attention labels Sep 7, 2026
@bolichen97

Copy link
Copy Markdown
Contributor

@GoZippy Heads-up on an overlap with the newer #7669 (@rnoack1), which rewrites the same function this PR edits.

The shared file is src/kiro_crew/hooks.py, and the shared function is run_script_hook. This PR touches its spawn region in three hunks so Windows spawns route through WSL2. #7669 rewrites that function wholesale: it pre-binds proc before the try, adds an asyncio.CancelledError arm that reaps and audits, inlines _audit_hook_invocation_now on every terminal path, and refuses the run with exit 2 when the audit singleton cannot be warmed (sel_is_warm / warm_sel_singleton). A textual conflict in the spawn body is near certain, and two of its behaviours matter beyond the text. Its TestProcIsNeverUnbound pins exactly two if proc is not None and proc.returncode is None: reap sites and leaves no unguarded reap, so a wsl2 spawn that reintroduces one fails that test rather than only conflicting. Its cold-audit refusal sits above the spawn, so a wsl2 spawn path has to sit below that refusal.

Concrete suggestion: land #7669 first, since it rewrites the function wholesale and pins the resulting shape with tests, then rebase this PR's three hunks onto the new body and guard the wsl2 reap the same way. The reverse order is harder, because #7669's rewrite would then have to carry the wsl2 branch through itself. Neither PR references the other today, and this one is already 99 commits behind main with mergeable_state dirty, so the rebase is not extra cost.

Posted from the 2026-09-08 open-PR relationship audit (read-only, one auditor per PR); reply here if any of this is wrong.

@bolichen97

Copy link
Copy Markdown
Contributor

Rebased onto main acc99f21 by a maintainer as part of the 2026-09-08 open-PR audit (was 99 commits behind).

Conflicts resolved:

  • src/kiro_crew/sandbox.py (_build_launcher_script): kept your posixpath.join + identity is None gate, and kept main's new _pod_os_home_targets() extend (fix(pod): scope pod kiro-cli oauth grants to the pod home #8528) inside that same gate, since it is a builder-host resolution like its three siblings.
  • src/kiro_crew/sandbox.py: union-merged three kwarg lists where main's is_kiro_cli met your posix_shell_argv.
  • docs/system-specs/modules/security.md: took main's delegation paragraph (main reverted fix(security): sandbox verify + UI-stream timeout + mem-info gate #8117, so kiro_internal_sandbox_enabled() is gone) and re-applied only your agent.sandbox: "wsl2" clause.
  • Dropped commit 0715c0be ("keep cron_script.py baselined"): main has since removed cron_script.py from .github/black-baseline.txt itself, so its four de-formatting hunks are now a ratchet regression and the diff against .github/** is empty either way. That was the sole cause of the fork workflow-change guard block.

Gates run locally on changed files: black, isort, flake8, tsc --noEmit, and pytest over the touched test files plus the pod-mask suites (966 passed). Pre-existing, not caused by the rebase: 5 failures in test/test_sandbox_wsl2.py around wrap_argv's win32 arm fail identically on your old head be6bed4e on a Linux host.

Please review the resolutions. A maintainer push makes the maintainer the last pusher, so under the repo's last-push rule a second approver is needed. Reply here if anything looks wrong.

@chenmingwei23

Copy link
Copy Markdown
Contributor

Kiro Crew [operator: chenmingwei23#de330d0c]: This PR has been inactive for 7+ days. I reviewed the blockers but they require your input:

  • Blocking review verdicts stand on the current head. GPT 5.6 Review is changes-requested (2 security-class blocking findings) and Design Review is BLOCK on 69f04a4. These are design/security decisions, not mechanical fixes.
  • Overlap with feat(hooks): make SessionLaneChanged an authorable hook event #7669 (@rnoack1), which rewrites the same run_script_hook in src/kiro_crew/hooks.py that this PR edits in three hunks. Which PR owns that function needs a maintainer/author decision.
  • Platform-specific + large new subsystem. 33 files / +2356 introducing a Windows WSL2 sandbox backend; it can't be safely verified on a Linux host and is past the size the pipeline auto-drives.
  • Backend Lint & Type Check and PR Hygiene are red on top; worth clearing once the direction above is settled.

When you've addressed these, the pipeline will re-assess on its next cycle.

Windows has no seatbelt and no user namespaces, so `sandbox.wrap_argv`
delegated unconditionally and the child ran unconfined. The official Kiro
backend hides that because kiro-cli brings its own sandbox, but any spawn
that does not -- a script cron, a hook, an app lifecycle script -- reached
the host with nothing between it and the operator's files.

This adds a WSL2 backend: the same namespace construction the Linux arm
builds, run inside a distro, with the Windows-side ceilings materialized
and masked before the guest starts. Detection, distro selection and the
failure reason are surfaced in config and on the Agent settings tab, so an
operator can see which distro was chosen and why a spawn refused.

Docker Desktop's utility instances are filtered out of the distro choices:
they exist to run the daemon, not arbitrary workloads, and offering them
produces a sandbox that fails in a way nobody can read. The state column
`wsl.exe --list` prints is locale-dependent, so nothing here branches on
it -- only dict membership decides whether a requested distro exists.

The guest staging directory is sealed in every launcher path, and the
Windows-side ceilings are materialized before the spawn rather than left
to an existence check that a default install fails: an absent
computer_use.json got no seal and stayed writable through DrvFs, which
handed a sandboxed workload the ability to turn on desktop control for
itself.

Removes the settings screenshot that was committed for the pull request
description; it does not belong in the tree.
@github-actions

Copy link
Copy Markdown
Contributor

Security Scope Review (fork) — 🟡 CONCERNS

Which legitimate operations does a76967c80001e5f35aa94ffdb06c29ff649738b1 newly refuse? Model proposes, scripts/deny_diff.py decides — updated in place on each push. A script-confirmed regression blocks PR readiness.

the reviewer's own judgement; no confirmed regression

Scope-Verdict: CONCERNS

TIGHTENING: The sandbox spawn-wrap layer, not the shell deny composite. wrap_argv grows a wsl2 arm whose masking is fail-closed everywhere — wsl_namespace_argv "computes the same sensitive-directory set _build_launcher_script would mask natively, resolves it against the REAL Windows home, translates each entry through DrvFs, and passes the result in as extra_hidden_dirs", and "Raises RuntimeError on any resolution/staging/translation failure — this function NEVER falls back to returning argv unwrapped" — the ONE threat it refuses: a WSL2-guest-sandboxed workload (app lifecycle script, command cron, script hook) reaching the operator's real Windows-side credentials and governance ceilings through the DrvFs mount at /mnt/c/... ("Left unmasked, a sandboxed app-lifecycle script, command cron, or hook could read or overwrite those real files"). No file in the four-check tool-call deny composite (path fence, sensitive-command tier, exfiltration shapes, rule catalog) is touched by this patch.

ADJUDICATED: 14 candidates, 0 confirmed newly-refused
No harness verdict handed to this review confirmed a flip, and a regression without a verdict is not a finding. The candidates probe the change's own remedy commands (wsl -l -v, wsl --install -d, wsl -d ... sudo apt install -y python3), the probes the code itself spawns (echo x.{a,a}, mountpoint -q /mnt/c, unshare --user --map-root-user true, the stale-launcher find ... -delete sweep), the hook context-variable reads in both spellings, and the new test file's invocation in both interpreter spellings.

PLATFORM COVERAGE: windows — 6 rows covering the spellings this diff newly assumes: wsl/wsl.exe invocations (including the probe's compound sh -c form and the sudo apt remedy), %KIROCREW_HOOK_EVENT% cmd.exe hook syntax, and the backslash .venv\Scripts\python.exe -m pytest test\test_sandbox_wsl2.py interpreter/path shape. posix — 8 rows covering the guest-side spellings the diff embeds verbatim (/bin/sh -c 'echo x.{a,a}', mountpoint -q /mnt/c, unshare --user --map-root-user, /etc/wsl.conf read, the ~/.kirocrew-sandbox-run sweep, $KIROCREW_HOOK_EVENT). No any rows: every candidate carries a path, an executable name, or a shell-specific spelling. No platform assumption in the diff went unprobed at the shell-row level; what could not be probed at all is below.

UNADJUDICATED: The tightening lives almost entirely in guards the shell-command classifier cannot reach — no shell row flows through wrap_argv's dispatch, so no verdict exists for any of these, and an empty adjudicated set is not evidence they are well-scoped:

  • wrap_argv's posix_shell_argv gate and wsl2 arm (src/kiro_crew/sandbox.py, backend == "wsl2" and not posix_shell_argv → backend = "none"; extra_hidden_dirs/extra_visible_dirs → SandboxUnavailableError). Call path: hooks.run_script_hook / cron_script.run_command_sandboxed / apps/lifecycle_scripts.run_lifecycle_script → sandboxed_spawn_argv(_async) / wrap_argv_async → wrap_argv → detect_backend. Candidate legitimate inputs I could not get a verdict for: any future POSIX-shell call site that forgets the opt-in flag reads as ordinary fail-closed-on-Windows (the diff's own docs admit the command-cron probe shipped without it during development and refused every command cron while tests stayed green; test_every_posix_shell_spawn_declares_its_wsl2_disposition now pins the current set, but only the current set).
  • wsl_namespace_argv's fail-closed refusals (same file): (a) guest identity uid=0 → refuse — a distro imported via wsl --import defaults its user to root, so an operator on an imported distro loses every wsl2-routed spawn (app installs, command crons, hooks) with a per-spawn kind="transient" error rather than a permanent-remedy verdict; (b) unverifiable DrvFs mount (custom /etc/wsl.conf automount root or enabled=false) → refuse all wsl2 spawns even ones needing no Windows path; (c) a UNC or mapped-network-drive cwd → refuse — an operator whose app source or project directory lives on a network share loses app install scripts under wsl2.
  • The Windows-side masking set (_wsl2_windows_side_masking): its own docstring states it is deliberately stricter than native parity — "Whole directories where the native path re-exposes a single file (known_hosts): stricter, never looser" — so the cc tier's native .aws/config re-exposure and the strict tier's known_hosts re-exposure have no Windows-side equivalent through DrvFs. A guest workload that legitimately read the operator's non-secret C:\Users\<u>\.aws\config (region/profile) via /mnt/c at the cc tier loses it. Arguable narrowing, not confirmable here.
  • Dashboard PATCH validator (dashboard/handlers/core.py): agent.sandbox_wsl_distro is gated by pattern ^[A-Za-z0-9._\- ]*$ — an imported distro whose name carries a character outside that class (non-ASCII, parentheses) cannot be set through the dashboard, only by hand-editing config.json; and agent.sandbox PATCH now offers/accepts wsl2 only on a Windows host with wsl.exe present, so a config prepared from another machine must be file-edited.
  • Hook language flip (hooks.py): with wsl2 selected, hook argv becomes /bin/sh -c instead of cmd /c — an operator's existing cmd.exe-language hooks stop working the moment they opt into wsl2. Operator-initiated and documented, but the loss is silent per-hook (the hook runs and fails, not refused with a named cause).

The honest verdict is CONCERNS: zero confirmed shell-level regressions, with the substantive tightening living in guards no shell row can classify.

[SCOPE-REVIEWED] a76967c

Security scope review -- adjudicated candidates

  • macos-latest (platform posix): 7 classified, 0 newly refused, 7 still allowed.
  • ubuntu-latest (platform posix): 7 classified, 0 newly refused, 7 still allowed.
  • windows-latest (platform windows): 7 classified, 0 newly refused, 7 still allowed.

No candidate flipped from allowed to refused.

Copy link
Copy Markdown
Contributor

Open-PR triage (2026-10-05): DISTINCT, needs REBASE, plus a merge discussion with #7414 and #7669

I checked head a76967c8 against origin/main af1eb612 using the full merge-base diff (base 50d5553f).

Coverage on main: none. git grep wsl2 origin/main -- src/kiro_crew returns nothing. Main has is_wsl() and nothing else. The merged PRs this PR cites don't implement this backend:

So this PR is not superseded and not a duplicate, and it should not be closed.

Rebase needed. The branch is 2672 commits behind main and mergeable_state=dirty. git merge-tree shows conflicts in 28 files, including:

Still open at this head (it was raised by the GPT review but isn't fixed): _build_launcher_script still bakes _namespace_dir = str(config_dir().resolve() / "member-memory-bindings" / "pids") unconditionally (sandbox.py:5538). It isn't behind the identity is None guard. For the wsl2 arm (wsl_namespace_argv → identity=identity, sandbox.py:6719), the guest receives a Windows path string. Linux treats that string as a relative path, so the launcher creates stray dirs and PID records under the spawn's cwd. The gateway also never sees those records. Please pass a DrvFs-translated path, or skip the record on the guest. I rate this P1, not P0: the backend is opt-in, the default posix_shell_argv=False keeps every other caller unchanged, and no credential exposure follows from it.

Breaking change: none. agent.sandbox: "wsl2" is opt-in and never auto-selected, and the new posix_shell_argv keyword defaults to False.

Merge discussion (OVERLAPPING, the PRs complement each other):

Recommendation: REBASE onto current main (re-port onto the split sandbox modules), fix the namespace-record path, then re-request review.

@iamwhatever

Copy link
Copy Markdown
Contributor

Thank you for this WSL2 sandbox backend; Windows isolation is a real gap. We are closing this PR because the branch is about 7,400 commits behind main and the open security reviews (the guest launcher drops the -I -S confinement flags, the script-cron isolation claim, and two GPT security findings) would need a fresh security review after a rebase. The need is tracked in #21928. A new PR from current main that keeps the native launcher's flags is very welcome.

The branch is left untouched, so you can reopen this PR at any time, or open a fresh one on current main, if you want to pick it back up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

fork Pull request from a fork (external contributor) merge conflict Branch has merge conflicts with its base — author must resolve before merge needs-author-decision PR blocked on author input

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants