Skip to content

fix(dashboard): make the skill-bundle link defence see a Windows junction - #9059

Merged
bolichen97 merged 1 commit into
kirodotdev:mainfrom
leonlaiyc:fix/discover-skill-dir-junction-defence
Sep 7, 2026
Merged

bolichen97 merged 1 commit into
kirodotdev:mainfrom
leonlaiyc:fix/discover-skill-dir-junction-defence

Conversation

@leonlaiyc

Copy link
Copy Markdown
Contributor

Problem / Motivation

_write_bundle in dashboard/handlers/discover.py (the skill-bundle install path)
opens with a deliberate leaf-link defence, and its comment states the reason:

# Symlink defense: if the skill dir itself is a symlink, every
# containment check below resolves against the symlink TARGET ...
# Remove the link itself — never follow it.
if skill_dir.is_symlink():
    skill_dir.unlink()

is_symlink() is False for a Windows junction — and the junction is precisely
the shape that matters here, because a directory symlink on Windows needs
SeCreateSymbolicLinkPrivilege while a junction needs none. So the shape an
unprivileged process can actually plant is the one the defence does not see.

With the defence inert, the very next line runs:

if overwrite and skill_dir.exists():   # exists() follows the junction → True
    shutil.rmtree(skill_dir)           # rmtree REFUSES a junction

shutil.rmtree treats a junction as a link exactly as it treats a symlink
(_rmtree_islink matches IO_REPARSE_TAG_MOUNT_POINT on Windows) and raises.
_write_bundle runs under await asyncio.to_thread(_write_bundle) with no
except in scope
, so the OSError leaves the handler uncaught.

Measured against unpatched origin/main, driving the real
POST /api/skills/-/discover/install endpoint with a real
_winapi.CreateJunction junction:

AssertionError: assert 500 == 200
  ...
  raise OSError("Cannot call rmtree on a symbolic link")
OSError: Cannot call rmtree on a symbolic link

Why it matters

Graded honestly: this is a dead defence-in-depth layer plus a 500, NOT a
containment escape.
The layer below still holds — skill_dir.resolve() follows
the junction and the relative_to(skills_root) check refuses — so nothing is
written outside the skills root either way. That is stated up front so the
severity is not read as higher than it is.

What is actually broken is that the install becomes unrecoverable through the
UI
. Without overwrite the request answers 409 exists (the junction makes
skill_dir.exists() true), and the documented way out of a 409 is to retry with
overwrite: true — which is the branch that 500s. A user who lands on a junctioned
skill dir has no path forward from the dashboard, and the response they get is an
unhandled server error rather than anything actionable.

What changed (motivation → approach → change)

Symptom: a junctioned skill dir makes bundle install answer 500.
Root cause: the leaf-link defence asks is_symlink(), which does not report a
junction, so the link is never removed and the rmtree below inherits it.
Change: route the defence through the repo's canonical pair.

if platform_compat.is_link_or_junction(skill_dir):
    logger.warning("Replacing linked skill dir: %s", skill_dir)
    platform_compat.unlink_link_or_junction(skill_dir)

The unlink half matters as much as the predicate. The obvious "fix" — reaching
for shutil.rmtree once the junction is detected — would delete through it.
unlink_link_or_junction detaches a junction with rmdir, which removes the
reparse point and leaves the target's contents alone, exactly as unlink leaves a
symlink's. Both properties are asserted.

Scope kept to that one guard. The per-file file_path.parent.is_symlink() check
further down is deliberately not touched: the file_path.resolve().relative_to( resolved_root) check immediately above it already resolves the whole parent chain,
junctions included, so that guard is genuinely belt-and-suspenders and changing it
would be a swap with no behaviour behind it.

platform_compat is imported (one line); no other import path grew.

Tests

test/test_skill_discover.py, two tests added to TestDiscoverInstall, siblings of
the existing test_install_overwrite_replaces_symlinked_skill_dir:

Test Locks in
test_install_overwrite_replaces_junctioned_skill_dir the junction is removed rather than followed; the install returns 200 and lands inside the skills root; nothing is written at the old target
test_the_junctions_target_survives_being_replaced a bystander file inside the junction's target is still readable afterwards — the link was detached, not deleted through

The links use conftest.make_dir_link, which yields a real junction on Windows, so
the platform the blind spot lives on is exercised rather than skipped.

Guard-the-guard. Each test asserts the planted shape through an oracle before
asserting anything about the handler: platform_compat.is_link_or_junction(link) is
true, and link.exists() is true (if it were not followable, rmtree would never
run and the test would pass for the wrong reason).

The second test's property is distinct from the first's on purpose: the first proves
nothing was written outside the root, the second proves nothing was deleted
outside it.

Red-before, measured on unpatched origin/main: 2 failed, both
assert 500 == 200, with OSError: Cannot call rmtree on a symbolic link in the
captured server log. After the fix: test_skill_discover.py is 21 passed, 1
skipped
, and the sibling test_discover_handlers_cov80.py is 35 passed.

Gates on this head: flake8 clean, isort --check-only clean, mypy --platform linux reports nothing in discover.py, black and subprocess-encoding gates both
pass scoped origin/main...HEAD (2 files). Both touched files are in
.github/black-baseline.txt and were deliberately not reformatted.

Manual verification

N/A — unit coverage sufficient: the tests drive the real HTTP endpoint through
aiohttp's test client against a real junction on the affected platform, which is
the same path the dashboard uses.

Related Issues

None — found by inspection while auditing is_symlink-based defences for the
Windows junction blind spot, the same family as #7881.

Pattern harvest

Rule candidate: semgrep
Pattern: is_symlink()/os.path.islink() used as a link defence immediately
above a shutil.rmtree — on Windows the predicate misses a junction while rmtree
still refuses one, so the guard silently stops guarding and the refusal it was meant
to prevent surfaces as an unhandled OSError. The pair
platform_compat.is_link_or_junction / unlink_link_or_junction already exists for
exactly this; a grep for islink/is_symlink within a few lines of rmtree finds
the remaining sites.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

🤖 Generated with Claude Code

…tion

`_write_bundle`'s leaf-link defence removes a pre-planted link at the skill dir
so the containment checks below cannot be resolved against its target. It tests
`skill_dir.is_symlink()`, which is False for a Windows junction — and a junction
is the shape that matters there, because a *directory* symlink on Windows needs
`SeCreateSymbolicLinkPrivilege` while a junction needs none.

With the defence inert, the very next line is `shutil.rmtree(skill_dir)`, and
`rmtree` refuses a junction exactly as it refuses a symlink. `_write_bundle`
runs under `await asyncio.to_thread(...)` with no `except` in scope, so the
`OSError` leaves the handler uncaught. Measured: the install request answers
**500 Internal Server Error** with `OSError: Cannot call rmtree on a symbolic
link`.

Routed through `platform_compat.is_link_or_junction` /
`unlink_link_or_junction`, the repo's canonical pair for this. The unlink half
matters as much as the predicate: a junction is a directory reparse point
detached with `rmdir`, so the target's contents survive exactly as a symlink's
do under `unlink` — a plain `rmtree` here would delete through it.

Containment itself was never breached: `skill_dir.resolve()` follows a junction
and the `relative_to(skills_root)` check below refuses. This restores the
defence-in-depth layer above it, and stops the refusal surfacing as a 500.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@leonlaiyc
leonlaiyc requested review from a team and bolichen97 September 6, 2026 16:22
@github-actions github-actions Bot added fork Pull request from a fork (external contributor) readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Sep 6, 2026
@github-actions

github-actions Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — ✅ no blocking findings

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

Review details

No findings.
[GPT-REVIEWED] 59ca6c7

@github-actions

github-actions Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — ✅ PASS

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

Design-Verdict: PASS

Root-cause fix routed through the repo's canonical platform_compat pair, with endpoint-level tests asserting both non-write and non-delete outside the root.

[DESIGN-REVIEWED] 59ca6c7

@github-actions

github-actions Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

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

Review details

The diff is a narrow, correct widening of an existing leaf-link defense from symlink-only to symlink-or-junction. Let me confirm the helpers behave correctly on POSIX and that the caller can't hit the unsafe else branch.

The verification confirms:

  • is_link_or_junction reduces to os.path.islink on POSIX (_ISJUNCTION/fallback return False for non-junctions), so no behavior change off Windows.
  • unlink_link_or_junction removes a symlink via unlink (identical to prior code) and a junction via rmdir (detaches without touching target).
  • The final os.unlink(path) else branch is unreachable from this caller, which only calls after is_link_or_junction returned True.
  • _ISJUNCTION internally swallows OSError, and it's only invoked when islink is already False.

The candidate list found nothing, and my own falsification pass re-derived no grounded defect: the change strictly widens containment, the removal path preserves link targets, and the containment/traversal guards downstream are unchanged. Nothing meets (a)+(b)+(c) at 80+.

No findings.

[OPUS-REVIEWED] 59ca6c7

@github-actions

github-actions Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

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

Premise-level review of 59ca6c7a87ce3476ecafa5ccbc18144066e3b030 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.

All claims verified against the base tree. The platform_compat pair exists and is the established mechanism (~20 call sites), make_dir_link exists in conftest, the sibling symlink test exists, and my counted grep confirms 5 unfixed sibling sites of the same guard-above-rmtree pattern. Emitting the review.

First-Principles-Verdict: CONCERNS

The fix is cause-level and reuses the canonical pair, but it is a point patch: 5 counted siblings of the same guard-above-rmtree pattern stay broken.

What this change ships

Intent: make a dashboard skill-bundle install recoverable when the skill dir is a pre-planted Windows junction (today: 409 → retry with overwrite → unhandled 500, no way forward). This is a FIX.

  1. Overwrite-install on a junctioned skill dir now succeeds instead of answering 500 — justified, cause-level
  2. The junction is detached in place; the target's files survive — justified (existing helper, not a second spelling)
  3. Warning log relabeled "symlinked" → "linked" skill dir — rides along, entailed (old text would misname a junction)
  4. Two regression tests driving the real endpoint against a real junction — justified

No new config key, flag, export, or schema property; the change consumes the existing platform_compat.is_link_or_junction / unlink_link_or_junction pair (~20 existing call sites), so nothing here duplicates or generalizes.

Watch

  • Counted unfixed siblings: grepping is_symlink()|os.path.islink within ~6 lines above shutil.rmtree finds 6 sites; this fixes 1. Left: pod/provision.py:229 (same shape, no ignore_errors — a junction raises uncaught exactly like the defect fixed here), plus node_modules_txn.py:70, apps/builtins/dev_fleet/sync_runner.py:78, frontend.py:407, apps/builtins/auto_improvement/backend/pr_watchers.py:224 (all ignore_errors=True, so a junction silently survives rather than 500s). The description declares the family and the grep; accepted-and-deferred, but pod/provision.py:229 is the one sibling with the identical failure mode and is a 2-line fix.

[FIRST-PRINCIPLES-REVIEWED] 59ca6c7

@github-actions github-actions Bot added readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Sep 6, 2026

@bolichen97 bolichen97 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tech Lead review — approved.

Correct helper. AGENTS.md's cross-platform table names is_link_or_junction / unlink_link_or_junction as the canonical pair and lists path.is_symlink() as the wrong spelling ("misses a Windows junction"). This routes the guard through exactly that pair. The unlink half is the part that matters: unlink_link_or_junction detaches a junction with rmdir, so the target's contents survive — verified in platform_compat.py, and asserted by test_the_junctions_target_survives_being_replaced. Reaching for rmtree after detection would have deleted through the link; the PR explicitly avoids that.

Scope is the whole of this link-defence path. The only other is_symlink in _write_bundle is the per-file file_path.parent.is_symlink() guard, and leaving it is right: the file_path.resolve().relative_to(resolved_root) check immediately above already resolves the full parent chain (junctions included), and the guard's failure action is continue, not rmtree — so a junction there cannot produce the uncaught OSError this PR fixes. Swapping it would be a no-behaviour churn. Within this defence path, this was the last site with a real behavioural gap.

Consistent with #8873 (same author, same defect class, merged): same remedy shape — route the predicate through platform_compat, add an endpoint-level test using a real junction via conftest.make_dir_link.

Severity graded honestly in the description — a dead defence-in-depth layer plus an unrecoverable 409→overwrite→500 loop, not a containment escape, since resolve() + relative_to(skills_root) still holds. I confirmed that reading.

Signals. 66 check-runs, 61 success / 5 skipped, 0 failures; Windows backend shards ran, so the junction tests execute on the platform the blind spot lives on. GPT 5.6 and Opus 4.8: no blocking findings. Design Review: PASS. First Principles: CONCERNS (advisory) for 5 counted siblings of the guard-above-rmtree pattern in other modules — correctly out of scope here and declared in the Pattern harvest section; pod/provision.py:229 is the one with the identical uncaught-OSError shape and is worth a follow-up. readiness: passed applied 17:02Z, after the single commit (16:19Z) and all review lanes. The one Focus Cue Gate annotation is a pre-existing notice, not from this diff.

@bolichen97
bolichen97 merged commit acd1ff3 into kirodotdev:main Sep 7, 2026
67 checks passed
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Sep 7, 2026
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
…tion (kirodotdev#9059)

`_write_bundle`'s leaf-link defence removes a pre-planted link at the skill dir
so the containment checks below cannot be resolved against its target. It tests
`skill_dir.is_symlink()`, which is False for a Windows junction — and a junction
is the shape that matters there, because a *directory* symlink on Windows needs
`SeCreateSymbolicLinkPrivilege` while a junction needs none.

With the defence inert, the very next line is `shutil.rmtree(skill_dir)`, and
`rmtree` refuses a junction exactly as it refuses a symlink. `_write_bundle`
runs under `await asyncio.to_thread(...)` with no `except` in scope, so the
`OSError` leaves the handler uncaught. Measured: the install request answers
**500 Internal Server Error** with `OSError: Cannot call rmtree on a symbolic
link`.

Routed through `platform_compat.is_link_or_junction` /
`unlink_link_or_junction`, the repo's canonical pair for this. The unlink half
matters as much as the predicate: a junction is a directory reparse point
detached with `rmdir`, so the target's contents survive exactly as a symlink's
do under `unlink` — a plain `rmtree` here would delete through it.

Containment itself was never breached: `skill_dir.resolve()` follows a junction
and the `relative_to(skills_root)` check below refuses. This restores the
defence-in-depth layer above it, and stops the refusal surfacing as a 500.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
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)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants