Skip to content

fix(code-review-sage): refuse a junctioned runs root in the follow-up guard - #8869

Merged
NicholasRBowers merged 1 commit into
kirodotdev:mainfrom
leonlaiyc:fix/sage-followup-junction-containment
Sep 13, 2026
Merged

NicholasRBowers merged 1 commit into
kirodotdev:mainfrom
leonlaiyc:fix/sage-followup-junction-containment

Conversation

@leonlaiyc

@leonlaiyc leonlaiyc commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

sage_lib/followup.py::followup_dir() refuses a linked ancestor before it resolves anything, and its own docstring says why the order matters:

a link planted at runs is followed by resolve(), the anchor moves to the attacker's directory, and every child underneath then compares as legitimately "inside" it

That pre-resolve check asked Path.is_symlink(). A Windows directory junction answers False to is_symlink(), needs no privilege to create, and is followed by resolve() exactly like a symlink — so on Windows the plant walks straight through the guard and the anchor is handed over anyway.

Measured on origin/main (9f3c07dc7), calling the function directly with a junction at the runs root:

runs : RETURNED  escapes_to_attacker=True
run  : refused (ERR_LINKED_DIR)
chat : refused (ERR_LINKED_DIR)

followup_dir("runJ", root) returns a path whose resolve() lands inside the attacker's directory. The reviewer running a review has shell and these paths are predictable — the threat model this guard is written against.

Why it matters

followup_dir() is what the descriptor writer builds on: mkdir(exist_ok=True) then mkstemp(dir=...). With the anchor relocated, those writes land outside the app's data tree entirely, at a path the attacker chose.

The exposure is Windows-specific in a way that inverts the usual coverage story: os.symlink on Windows needs SeCreateSymbolicLinkPrivilege, so the symlink plant is the hard one there — while the junction plant, which needs nothing, is the one the guard did not see.

What changed (motivation → approach → change)

Root cause is the link predicate, not the ordering — the ordering was already right.

The check now routes through platform_compat.is_link_or_junction, the shim-table row for exactly this question (AGENTS.md: "Detect/remove a dir link → is_link_or_junction(path) NOT path.is_symlink() (misses a Windows junction)"). Same move as merged #7881 and #8766.

The import is guarded like this module's other kiro_crew imports, which exist because it can run standalone. The fallback is symlink-only and deliberately not a local reparse-point probe: re-implementing a platform_compat row locally is what the shim table exists to prevent, and answering only for the case it can see leaves the caller no weaker than today.

Scope is one plant site, and that is measured, not assumed. A junction at the run directory or at chat/ is already refused on main: the anchor stays legitimate there, so the resolved containment check catches it. The runs root is the one case that check cannot catch — it is measuring against the attacker's own anchor — which is precisely what the pre-resolve check exists for.

The two other link guards in this app are not siblings, checked individually:

  • learning.py:141 — lock_path.is_symlink() guards a file path, and is backed by O_NOFOLLOW plus an fstat S_ISREG/st_nlink check that cannot be raced.
  • results.py:394 — src.is_symlink() guards a <change_id>.json file path.

A junction is directory-only, so at either site it fails is_file() and the surrounding guard declines anyway.

Tests

tests/test_followup.py. The plant is staged with a local mirror of test/conftest.py::make_dir_link, which calls _winapi.CreateJunction unconditionally on Windows — a plain symlink on POSIX, a real directory junction on Windows — so these run on every platform and the junction arm is the one actually exercised there.

It is deliberately not platform_compat.symlink_or_junction: that tries os.symlink FIRST and falls back to a junction only where the privilege is missing, so a runner with Developer Mode gets a SYMLINK and the junction arm is never exercised — silently, while still reporting green. The first head of this PR shipped that mistake; a guard-the-guard test asserting the plant really was a junction is what caught it, on the Windows CI shard. It is mirrored rather than imported because only the test/ testpath gets that conftest.

They assert on followup_dir() directly rather than through write_descriptor(). That matters: write_descriptor() has preconditions of its own that return False for unrelated reasons, and a first draft of these tests passed on unpatched main for precisely that reason — a green test that proved nothing. Asserting at the guard is what makes the evidence divisible.

Red on origin/main:

  • test_a_junctioned_runs_ROOT_is_refused — AssertionError: FileNotFoundError not raised.

Green on both sides, pinned as preservation rather than fixes:

  • test_a_junctioned_run_directory_stays_refused — the resolved containment check already covers it; pinned so the predicate change cannot quietly weaken it.
  • test_a_junctioned_chat_directory_stays_refused — same.
  • test_the_staged_plant_is_really_a_junction_on_windows — guards the guard: it asserts the plant really is a junction on Windows, so the tests above cannot quietly stop exercising the junction arm. This is the test that caught the symlink_or_junction mistake on the first head.

Local (Windows, repo-pinned toolchain): tests/test_followup.py 35 passed / 6 skipped (the 6 are the pre-existing symlink tests). Full code_review_sage suite: 773 passed / 33 skipped / 1 failed — test_adapters.py::TestEnterpriseHosts::test_malformed_links_are_rejected_not_crashed_on, which reproduces identically on a pristine origin/main tree and touches nothing this PR changes. flake8 clean; scripts/check_black_formatting.py passes in scope.

Manual verification

N/A — unit coverage sufficient: the whole change is one predicate inside one function, and the tests stage the real plant through the repo's own link seam on the affected platform rather than simulating it.

Related Issues

no linked issue: found by source review of the is_symlink()-versus-junction seam after #8766/#8767

Pattern harvest

Rule candidate: semgrep
Pattern: Path.is_symlink() used as a security link guard on a path that can be a directory. It is False for a Windows junction, which needs no privilege and is followed by resolve() — so the guard is bypassed on the platform where the plant is cheapest. The repo's own shim table already names is_link_or_junction as the required call; the residual risk is a guard that predates it. Note the narrowing that keeps this from being a blanket sweep: a link guard on a file path is not affected, because a junction cannot exist there.

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

@leonlaiyc
leonlaiyc requested review from a team and dwu96 September 6, 2026 03:18
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention fork Pull request from a fork (external contributor) 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

Design Review (Fable 5, fork) — ✅ PASS

Design-level review of d2341045fc9adc474dcf7eb655125387d901bd4f 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

Real Windows-only guard bypass, fixed at the root (the link predicate) through the repo's own platform_compat seam, with junction-arm tests that self-verify.

I verified the load-bearing claims against the base tree: is_link_or_junction exists in platform_compat.py:4280 and covers junctions; the pre-resolve ordering in followup_dir is unchanged; and the standalone symlink-only fallback is effectively inert for the dangerous write path, because standalone mode also loses kiro_sessions_dir, so write_descriptor refuses before followup_dir is ever reached — the fallback genuinely "leaves the caller no weaker." Windows CI shards exist (ci.yml:763), so the junction arm is exercised where it matters, and the guard-the-guard test pins that it stays exercised.

[DESIGN-REVIEWED] d234104

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

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

Review details

The change is a strict security strengthening: is_link_or_junction reduces to os.path.islink on POSIX (equivalent to the old is_symlink), catches Windows junctions additionally, and returns False (never raises) on nonexistent/non-link paths — so the existing loop over possibly-nonexistent parts behaves as before. The ImportError shim is no weaker than the pre-change code. No guard removed or weakened, no reachable defect in the changed lines, no matching AUTOSDE rule. Nothing survives falsification and I found no new grounded defect.

No findings.

[OPUS-REVIEWED] d234104

@github-actions

github-actions Bot commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — ✅ no blocking findings

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

Review details

No findings.
[GPT-REVIEWED] d234104

@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 d2341045fc9adc474dcf7eb655125387d901bd4f 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. I have everything needed for the review: the fix is derived from a documented shim-table invariant (platform-compat.md:53) with a checkable mechanism; the author's in-app non-sibling claims are accurate; but the repo-wide sweep found at least one genuine unfixed sibling (mcp_gateway/spill.py:61), and the test helper is now a third private copy.

First-Principles-Verdict: CONCERNS

The predicate fix is derived and correct, but it point-patches one of at least two live directory-guard sites, and adds a third copy of the junction test helper.

Not justified as shipped

  1. duplicate of test/conftest.py:201 — _make_dir_link is now the third private copy of the same helper (grepped CreateJunction: test/conftest.py:215, auto_improvement/tests/test_pollute.py:47, and this PR), all with the same docstring; three copies will diverge.

What this change ships

Inventory (5 items) — 4 justified

Intent: stop a Windows directory junction planted at the follow-up runs root from relocating the containment anchor into an attacker-chosen directory — a FIX.

  1. A junction at the runs root is now refused on Windows instead of handing the anchor over — justified
  2. Junctions at the run and chat directories now trip the earlier pre-resolve refusal (same outcome as before, pinned by tests) — justified
  3. Standalone runs (kiro_crew unimportable) fall back to symlink-only detection — justified
  4. Junction-plant coverage now actually runs on Windows, including a guard-the-guard test — justified
  5. A third private copy of the junction-staging test helper — duplicate of test/conftest.py:201

Watch

The description's sibling count is app-scoped ("The two other link guards in this app are not siblings" — verified true), but repo-wide the same root cause survives: grepped is_symlink\(\) across src/kiro_crew (203 hits) and verified mcp_gateway/spill.py:61 guards a directory with bare is_symlink() while its own docstring claims it stops an agent "swapped the spill dir" confused-deputy — a junction passes it and the deletion sweep runs in the attacker's target. The pattern-harvest note defers the sweep without naming any concrete site.
Clears when: cleanup_old_spill_files routes through is_link_or_junction, or a filed issue names the verified sibling sites for the deferred sweep.

Subtractions

Collapse the three make_dir_link spellings (test/conftest.py:201, test_pollute.py, this PR's _make_dir_link) to one importable helper and delete the two mirrors — net minus two copies of privilege-sensitive link-staging logic.

[FIRST-PRINCIPLES-REVIEWED] d234104

@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 Sep 6, 2026
@leonlaiyc
leonlaiyc force-pushed the fix/sage-followup-junction-containment branch from 5cdcea7 to e62f303 Compare September 6, 2026 05:30
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 6, 2026
@NicholasRBowers NicholasRBowers added needs-pr-triage PR scanner: awaiting automated triage drive-to-green PR claimed by drive-to-green pipeline and removed needs-pr-triage PR scanner: awaiting automated triage labels Sep 13, 2026
@NicholasRBowers

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: NicholasRBowers#a942f9ca]: This PR has been inactive for 7+ days with failing CI. I've assessed the blockers and they appear resolvable — I'll push fixes directly to this branch as a co-author.

Assessment: The only CI red is test/test_approval_threading.py::TestSubagentPassesParentKey::test_tool_approval_receives_parent_session_key, a file this 2-file diff never touches; it was fixed on main on 2026-09-07 as a flake (#9139), and this branch's base is 7 days stale. Coverage Gate and PR Readiness are downstream of that one shard. GPT, Opus and Design are all clean on e62f3037; First Principles is advisory CONCERNS (one Watch item, the mcp_gateway/spill.py:61 sibling, already declared as deferred by the PR). Fix plan: rebase onto current main and push to re-fire CI and the fork review lanes, post the First Principles disposition, and drop the leftover CLA placeholder from the body. No code change to the fix itself is expected.

If you'd prefer I don't touch this PR, add the pr-no-autofix label.

… guard

followup_dir() refuses a linked ancestor before it resolves anything, and its
docstring says why the order matters: resolving first makes containment
attacker-relative, because a link planted at the runs root is followed by
resolve(), the anchor moves into the attacker's directory, and every child
underneath then compares as legitimately inside it.

That pre-resolve check asked Path.is_symlink(), which is False for a Windows
directory junction. A junction needs no privilege to create, and resolve()
follows it exactly like a symlink -- so on Windows the plant walks straight
through the guard. Measured on origin/main: with a junction at the runs root,
followup_dir("runJ", root) RETURNS a path whose resolve() lands inside the
attacker's directory.

Route the check through platform_compat.is_link_or_junction, the shim-table row
for exactly this question. The import is guarded like this module's other
kiro_crew imports; the fallback is symlink-only and never a local reparse-point
probe, and its signature matches the real routine exactly because mypy requires
every conditional variant of a name to agree.

Only the runs ROOT is affected. Measured per plant site on main: a junction at
the run directory or at chat/ is already refused, because the anchor stays
legitimate there and the resolved containment check catches it. The runs root is
the one case that check cannot catch -- it is measuring against the attacker's
own anchor -- which is precisely what the pre-resolve check exists for.

The two other link guards in this app are not siblings: learning.py's lock path
and results.py's record path both guard FILE paths, and a junction is
directory-only, so a junction there fails is_file() and the guard declines.

The test stages the plant with a local mirror of test/conftest.py::make_dir_link,
which calls _winapi.CreateJunction unconditionally on Windows. It is mirrored
rather than imported because only the test/ testpath gets that conftest. It is
NOT platform_compat.symlink_or_junction: that tries os.symlink first, so a
runner with Developer Mode gets a symlink and the junction arm is never
exercised -- silently, while still reporting green.

test_a_junctioned_runs_ROOT_is_refused fails on origin/main with
"FileNotFoundError not raised". The run/ and chat/ cases are pinned as
preservation tests, green on both sides.

The test file is in .github/black-baseline.txt, so it is deliberately not
black-formatted here: running black over it reformatted 56 pre-existing lines.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@NicholasRBowers

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: NicholasRBowers#a942f9ca]

Drive-to-green round 1 — rebase-only, no change to the fix.

What changed and why:

  • Rebased the single commit onto current main (28dcab655), new head d2341045f. The sole CI red on the previous head — test/test_approval_threading.py::TestSubagentPassesParentKey::test_tool_approval_receives_parent_session_key on the Backend Tests (3.12, 1) shard — is base drift: that file is untouched by this diff and the failure was fixed on main by test: fix flaky, hanging, heavy and side-effecting tests found by 5 full runs #9139 after this branch was cut. The Coverage Gate and PR Readiness reds were downstream of that shard.
  • Diff is byte-identical after the rebase (+123/−1 across the same 2 files, git diff origin/main...HEAD --stat verified). Leon's authorship is preserved; no fix commit was needed, so no co-authored commit exists on this head.
  • Verified locally before pushing: tests/test_followup.py 41 passed (the POSIX symlink arm runs here; the Windows junction arm is exercised by the Windows CI shards), test/test_approval_threading.py 14 passed on the rebased tree (confirming the base-drift diagnosis), isort / flake8 / mypy all clean.
  • Body tidy (no diff impact): dropped the leftover ## Contribution License Agreement placeholder and the generated-with footer; reshaped the ## Related Issues entry into an explicit no linked issue: … line so the intentional omission is machine-readable.
  • Filed mcp_gateway/spill.py: delete-sweep link guard misses a Windows directory junction #10492 to track the one repo-wide sibling of the same predicate gap (mcp_gateway/spill.py:61), which this PR's Pattern harvest already declared as deferred residual. Fixing it here would widen the diff beyond the PR's one-plant-site scope.

Next: waiting for CI + the fork review lanes to stamp the new head; the First Principles Watch items will get their disposition records once the fresh stamp lands.

@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 Sep 13, 2026
@NicholasRBowers

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: NicholasRBowers#a942f9ca]

  • accepted-and-deferred — span=fdc3afdc52c2 — third private copy of the junction-staging helper

self-added: yes

The mirror is deliberate and load-bearing for this PR: only the test/ testpath receives test/conftest.py, so an app-embedded test tree cannot import make_dir_link today, and platform_compat.symlink_or_junction is the wrong seam (it tries os.symlink first, so a Developer-Mode Windows runner would stage a symlink and never exercise the junction arm — the exact mistake this PR's first head shipped and its guard-the-guard test now prevents).
Consolidating the three spellings means creating a shared importable test-support home and editing two unrelated test suites — a cross-tree test-infrastructure refactor wider than this one-predicate security fix. Deferred to #10494 (deferred-finding label, assigned, Due 2026-09-27), which names all three copies and the import constraint. This ruling covers findings that require in-PR consolidation of the duplicated link-staging helper.

@NicholasRBowers

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: NicholasRBowers#a942f9ca]

  • accepted-and-deferred — span=27c73183db92 — repo-wide is_symlink() sibling at mcp_gateway/spill.py:61

The lane's own Clears when: names a filed issue as sufficient: "or a filed issue names the verified sibling sites for the deferred sweep." That issue exists — #10492 (deferred-finding label, assigned, Due 2026-09-27) names mcp_gateway/spill.py:61, the one verified repo-wide sibling, with the same shim-table fix (platform_compat.is_link_or_junction) and a junction-staging test requirement.
This PR deliberately fixes the one plant site the resolved-containment check cannot catch (the runs-root anchor) and declares the residual in its Pattern harvest; sweeping spill.py here would widen a one-plant-site fix into a repo-wide predicate sweep. This ruling covers findings that ask this PR to fix sibling is_symlink() sites outside code_review_sage.

@NicholasRBowers

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: NicholasRBowers#a942f9ca]

  • accepted-and-deferred — span=4909f5436015 — subtraction: collapse the three make_dir_link spellings to one importable helper

The subtraction is right and is tracked as #10494 (deferred-finding label, assigned, Due 2026-09-27), including the net-minus-two-copies goal and the reason a mirror exists at all: no importable home for the helper is reachable from an app-embedded test tree today, so the consolidation has to build that home first — a standalone test-infrastructure change touching test/conftest.py and auto_improvement/tests/test_pollute.py, both outside this PR's diff.
Performing the subtraction inside this PR would couple a one-predicate security fix to a cross-tree refactor and re-arm every lane on the widened diff. Deferral, not omission: the issue names all three copies and the import constraint.

@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 13, 2026
@NicholasRBowers
NicholasRBowers enabled auto-merge (squash) September 13, 2026 08:02
@NicholasRBowers

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: NicholasRBowers#a942f9ca]

REVIEW-READY at head d2341045f — all 82 checks green, PR Readiness passed, squash auto-merge armed.

Summary of the drive (rebase-only, zero fix commits):

Remaining: one maintainer approval — GitHub merges automatically once it lands.

@cixuuz cixuuz 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.

Reviewed exact head d234104. The junction-aware runs-root guard uses the audited shared detector, retains fallback safety, and has appropriate cross-platform regression coverage. CI is green.

@NicholasRBowers
NicholasRBowers merged commit c0307ef into kirodotdev:main Sep 13, 2026
83 checks passed
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Sep 13, 2026
@NicholasRBowers NicholasRBowers removed the drive-to-green PR claimed by drive-to-green pipeline label Sep 13, 2026
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
… guard (kirodotdev#8869)

followup_dir() refuses a linked ancestor before it resolves anything, and its
docstring says why the order matters: resolving first makes containment
attacker-relative, because a link planted at the runs root is followed by
resolve(), the anchor moves into the attacker's directory, and every child
underneath then compares as legitimately inside it.

That pre-resolve check asked Path.is_symlink(), which is False for a Windows
directory junction. A junction needs no privilege to create, and resolve()
follows it exactly like a symlink -- so on Windows the plant walks straight
through the guard. Measured on origin/main: with a junction at the runs root,
followup_dir("runJ", root) RETURNS a path whose resolve() lands inside the
attacker's directory.

Route the check through platform_compat.is_link_or_junction, the shim-table row
for exactly this question. The import is guarded like this module's other
kiro_crew imports; the fallback is symlink-only and never a local reparse-point
probe, and its signature matches the real routine exactly because mypy requires
every conditional variant of a name to agree.

Only the runs ROOT is affected. Measured per plant site on main: a junction at
the run directory or at chat/ is already refused, because the anchor stays
legitimate there and the resolved containment check catches it. The runs root is
the one case that check cannot catch -- it is measuring against the attacker's
own anchor -- which is precisely what the pre-resolve check exists for.

The two other link guards in this app are not siblings: learning.py's lock path
and results.py's record path both guard FILE paths, and a junction is
directory-only, so a junction there fails is_file() and the guard declines.

The test stages the plant with a local mirror of test/conftest.py::make_dir_link,
which calls _winapi.CreateJunction unconditionally on Windows. It is mirrored
rather than imported because only the test/ testpath gets that conftest. It is
NOT platform_compat.symlink_or_junction: that tries os.symlink first, so a
runner with Developer Mode gets a symlink and the junction arm is never
exercised -- silently, while still reporting green.

test_a_junctioned_runs_ROOT_is_refused fails on origin/main with
"FileNotFoundError not raised". The run/ and chat/ cases are pinned as
preservation tests, green on both sides.

The test file is in .github/black-baseline.txt, so it is deliberately not
black-formatted here: running black over it reformatted 56 pre-existing lines.

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.

3 participants