Skip to content

fix(instances): make the gateway run dir owner-only on Windows - #8164

Merged
NicholasRBowers merged 1 commit into
kirodotdev:mainfrom
leonlaiyc:fix/run-marker-dir-owner-only
Sep 11, 2026
Merged

NicholasRBowers merged 1 commit into
kirodotdev:mainfrom
leonlaiyc:fix/run-marker-dir-owner-only

Conversation

@leonlaiyc

Copy link
Copy Markdown
Contributor

Problem / Motivation

<config_dir>/run is the gateway's private sidecar directory. It holds:

  • gateway-<port>.secret — the local API credential (cli_server reads it via
    run_marker.read_secret);
  • gateway-<port>.pid — per read_pid's own docstring, "the identity a client
    checks before trusting the port"
    ;
  • gateway-<port>.bin — the launcher path the SSH token mint execs.

run_marker._run_dir tightened it with os.chmod(d, 0o700). A POSIX mode is
meaningless on Windows, so the directory simply keeps the DACL it inherited.
Measured on Windows 11 with a data home on a non-profile volume:

# os.chmod(d, 0o700) — what _run_dir does today
run                        BUILTIN\Administrators:(I)(OI)(CI)(F)
                           NT AUTHORITY\SYSTEM:(I)(OI)(CI)(F)
                           BUILTIN\Users:(I)(OI)(CI)(RX)
                           NT AUTHORITY\Authenticated Users:(I)(M)
run\gateway-8080.pid       BUILTIN\Users:(I)(RX)
                           NT AUTHORITY\Authenticated Users:(I)(M)

# platform_compat.restrict_dir_to_owner(d)
run                        OWNER RIGHTS:(OI)(CI)(F)
                           <owner>:(OI)(CI)(F)
run\gateway-8080.pid       OWNER RIGHTS:(I)(F)
                           <owner>:(I)(F)

Any authenticated account holds Modify on the directory and on the sidecars
created inside it.

The gap is not uniform even within this one directory: dashboard/server.py's
_write_secret_file deliberately calls platform_compat.restrict_to_owner on
the .secret file ("on Windows an owner-only DACL … a raw fchmod would be a
silent no-op"), while write_marker writes the .pid and .bin with
atomic_write(..., mode=0o600), whose mode is exactly that silent no-op. So the
credential is protected and the two files that decide which gateway a client
trusts are not.

Why it matters

On Windows the run directory and its .pid / .bin sidecars are writable by
any authenticated local account. read_pid is the ownership proof cli_server
checks before trusting a port, and prune_markers uses the same recorded pid to
decide which sibling gateway's marker and credential it must not reap. A
tampered sidecar therefore steers a client's port trust and can direct the live
gateway's prune at a sibling's files.

The exposure is bounded by where the data home sits: under the default
%USERPROFILE%\.kiro, the profile's own ACL still keeps other users out. It is
real wherever KIROCREW_HOME points outside the profile — a data drive, a
shared volume, a service account's working area — which the measurement above
reproduces. restrict_dir_to_owner exists precisely so this does not depend on
where the data home was placed.

What changed (motivation → approach → change)

Symptom: an "owner-only" directory that is not owner-only on Windows. Root
cause: the wrong half of AGENTS.md's cross-platform pair —

Need Use (platform_compat) NOT
Owner-only secret directory (fail-loud, inheritable) restrict_dir_to_owner(path) restrict_to_owner(path) on a directory (its Windows grants carry no (OI)(CI)…)

Change: _run_dir calls platform_compat.restrict_dir_to_owner(d). On POSIX
that helper is os.chmod(path, 0o700), so nothing about Linux or macOS
behaviour moves — including the nosemgrep suppression, which now lives inside
the helper where it belongs. On Windows it applies the owner-only DACL.

The (OI)(CI) inheritance is what makes this one call sufficient: files created
in the directory from then on inherit owner-only, so the .pid and .bin
sidecars are covered without touching write_marker or widening
atomic_write's contract. It is not a retrofit — as the helper's docstring
notes, a file that already exists keeps its own DACL — so an existing install
tightens on the next file write, not on the next _run_dir call.

The one deliberate difference from the helper's own contract is failure
handling. restrict_dir_to_owner is fail-loud by design, but _run_dir is
reached through secret_path() from dashboard/server.py's startup path, which
does not guard it; a directory that cannot be tightened (owned by another uid,
an unresolvable SID) must not take the gateway down. The pre-existing
best-effort contract is kept, with the swallowed error now logged rather than
silently passed.

Tests

Two tests in test/test_instances.py::TestRunMarker:

  • test_run_dir_lockdown_is_the_directory_helper — _run_dir() routes its
    tightening through platform_compat.restrict_dir_to_owner for that exact
    path. Red on 997d59421: assert [] == ['…\\run']. It re-patches the symbol
    over conftest's session-wide Windows stub, so the assertion is not vacuous
    on the Windows matrix.
  • test_run_dir_lockdown_failure_is_best_effort — a raising lockdown still
    returns a usable directory, pinning the contract secret_path()'s caller
    depends on. This one passes before and after by construction; it exists so a
    later change to the fail-loud helper cannot silently start taking the gateway
    down at startup.

Green: test_instances.py 298 passed, 5 skipped (the single failure,
test_no_anchored_pattern_uses_a_dollar_anchor, is a pre-existing cp950
decode failure on this Windows box and reproduces identically on 997d59421).
Siblings that consume the run marker — test_cli_restart_marker_fallback.py,
test_instance_credential_pairing.py, test_mcp_api_port_resolution.py,
test_governance_self_protection.py — 215 passed, 1 skipped.

Manual verification

The icacls table under Problem / Motivation is the manual verification:
both directories created on the same Windows 11 host on a non-profile volume,
one tightened the old way and one through the helper, each with a
gateway-8080.pid created afterwards so the (OI)(CI) inheritance is shown
rather than asserted. Unit coverage pins the call routing; only a real DACL read
can show what the call is worth.

Related Issues

None — found by auditing AGENTS.md's platform_compat "use this / NOT that"
table against current main.

Pattern harvest

Rule candidate: semgrep

Pattern: os.chmod(dir, 0o700) (or os.chmod(file, 0o600)) used as a security
control on a path that also exists on Windows, where the mode is a silent no-op.
The greppable shape is a raw os.chmod with an owner-only mode outside
platform_compat, on a path under the data home; the fix is
restrict_dir_to_owner for directories and restrict_to_owner for files. The
tell that it is worth a rule rather than a one-off: this repository already
carries the correct call in mcp_gateway/apps.py, in
dashboard/server.py::_write_secret_file, and in the AGENTS.md table — the
knowledge was present and the site still drifted.

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

@leonlaiyc
leonlaiyc requested review from a team and buluoray September 3, 2026 13:10
@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 readiness: checking Automated validation is still running labels Sep 3, 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 #8218 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 #8218: KEEP. Complementary hardening of the same sidecar directory with no conflict; each is independently correct. Files: src/kiro_crew/instances/run_marker.py.

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

@NicholasRBowers NicholasRBowers added the needs-pr-triage PR scanner: awaiting automated triage label Sep 11, 2026
@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 11, 2026
@NicholasRBowers NicholasRBowers added drive-to-green PR claimed by drive-to-green pipeline and removed needs-pr-triage PR scanner: awaiting automated triage labels Sep 11, 2026
@NicholasRBowers

Copy link
Copy Markdown
Contributor

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

Assessment: All CI is green on head a167be8f9, but the five fork Stage-2 review lanes skipped and never stamped this head, so PR Readiness sits pending indefinitely. A rebase-only push onto current main mints a new head and re-fires CI plus the review lanes (same shape as #7265/#7267/#7615).

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

`_run_dir` tightened `<config_dir>/run` with `os.chmod(d, 0o700)`. A mode is
meaningless on Windows, so the directory keeps the inherited DACL — measured
with `icacls`, that is `BUILTIN\Users:(RX)` plus `NT AUTHORITY\Authenticated
Users:(M)`. The directory holds the gateway credential, the pid a client checks
before trusting a port, and the marker naming an executable mint execs.

Route it through `platform_compat.restrict_dir_to_owner`, which is the same
`chmod(0o700)` on POSIX and an owner-only DACL on Windows. Its grants carry
`(OI)(CI)`, so the `.pid` and `.bin` sidecars written by
`atomic_write(mode=0o600)` — a no-op mode on Windows — inherit owner-only too.

The helper is fail-loud, but `_run_dir` is reached through `secret_path()` on
the dashboard's startup path, so the raise is absorbed and logged: the existing
tighten-if-possible contract is what callers depend on.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@NicholasRBowers
NicholasRBowers force-pushed the fix/run-marker-dir-owner-only branch from a167be8 to e12135a Compare September 11, 2026 11:10
@NicholasRBowers

Copy link
Copy Markdown
Contributor

🤖 Kiro Crew [operator: NicholasRBowers#a942f9ca]

Rebase-only push: a167be8f9 → e12135a0d. The code diff is unchanged.

Why: all CI was green on the old head, but the five Stage-2 fork review lanes (GPT/Opus/Design/First Principles/UX) completed as skipped for a167be8f9 and never stamped it, leaving PR Readiness pending indefinitely. A gh run rerun cannot re-fire them (reruns emit no workflow_run event), so the sanctioned fix is a rebase onto current main minting a new head SHA — that fires pull_request synchronize → fresh CI → workflow_run → all five lanes stamp. Same recovery as #7265, #7267, #7615.

The rebase applied cleanly (no conflicts). Local gates on the rebased head: isort ✅ flake8 ✅ mypy ✅ (1413 files) test/test_instances.py 321 passed ✅. Leon's authorship is preserved on the commit.

@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 11, 2026
@github-actions

Copy link
Copy Markdown
Contributor

GPT 5.6 Review (fork) — ✅ no blocking findings

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

Review details

No findings.
[GPT-REVIEWED] e12135a

@github-actions

Copy link
Copy Markdown
Contributor

Opus 4.8 Review (fork) — ✅ no blocking findings

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

Review details

No findings.

[OPUS-REVIEWED] e12135a

@github-actions

Copy link
Copy Markdown
Contributor

Design Review (Fable 5, fork) — ✅ PASS

Design-level review of e12135a0d6e17092df59831cc075e142a804cdac 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 DACL gap, fixed with the exact helper the repo's own platform-compat table prescribes; POSIX behavior and the best-effort contract are preserved and pinned by tests.

Suggestions

  • sandbox._ensure_run_dir chmods the same <config_dir>/run directory with the same Windows-no-op os.chmod(0o700) (sandbox.py:5448) and holds exec'd launcher scripts; today its protection depends on run_marker._run_dir having run first in the same process. Route it through restrict_dir_to_owner too (here or as an immediate follow-up) — the kept "mirrors sandbox._ensure_run_dir" docstring line is now inaccurate until that lands.
  • _run_dir() runs on every marker_path/pid_path/secret_path computation, including _wait_gateway_ready's poll loop, so on Windows each call now does a DACL write — the helper's own docstring flags this as an unbounded SMB round-trip on exactly the non-profile/shared-volume home this PR targets. A once-per-process tighten (module flag) keeps the guarantee without the per-poll cost.

[DESIGN-REVIEWED] e12135a

@github-actions

Copy link
Copy Markdown
Contributor

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

Premise-level review of e12135a0d6e17092df59831cc075e142a804cdac 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 lenses complete. The fix is real (measured DACL reproduction, mandated by the platform-compat doc table), the failure premise checks out in-repo (restrict_dir_to_owner raises OSError by documented contract, POSIX branch is byte-identical chmod), and the ecosystem's other Windows-capable chmod sites are already gated or branched. Two things survive self-critique: the diff hand-rolls the 43-consumer helper make_owner_only_dir, and one ungated sibling remains in diagnostics.py.

First-Principles-Verdict: CONCERNS

The mkdir + try/except body hand-rolls make_owner_only_dir — the helper the quoted doc row names — and already diverges from it (debug vs. warning).

Not justified as shipped

  1. duplicate of src/kiro_crew/platform_compat.py:4563 — make_owner_only_dir already does create + best-effort restrict_dir_to_owner + logged failure (43 consumers, grep make_owner_only_dir\( in src/). The doc row the description quotes, docs/system-specs/common/platform-compat.md:46, names it for exactly this shape, but the PR's quoted table truncates that clause out. The hand-rolled copy logs at debug where the helper warns — the two spellings diverged at birth.

What this change ships

Inventory (3 items) — 2 justified

Intent: make the gateway's run/ directory (credential, pid, launcher marker) actually owner-only on Windows, where os.chmod(0o700) is a DACL no-op — a FIX.

  1. On Windows, run/ and sidecars created in it become owner-only instead of writable by any authenticated account — justified
  2. A refused lockdown is now debug-logged inside a hand-rolled mkdir+tighten body — duplicate of platform_compat.make_owner_only_dir
  3. Two tests pin the helper routing and the best-effort startup contract — justified

Watch

One counted unfixed sibling: src/kiro_crew/diagnostics.py:1008 runs the same ungated os.chmod(out_dir, 0o700) on <home>/diagnostics with no Windows branch (grep os\.chmod\([^,]+, 0o700\) → 13 hits; the rest are POSIX-gated, Windows-branched, or on POSIX-only surfaces). The description's "Pattern harvest" acknowledges the class but fixes one site.
Clears when: diagnostics.py:1008 routes through restrict_dir_to_owner/make_owner_only_dir, or the proposed semgrep rule lands with that site suppressed knowingly.

Subtractions

  • Replace _run_dir's d.mkdir(...) + try: platform_compat.restrict_dir_to_owner(d) / except OSError: logger.debug(...) with the one call platform_compat.make_owner_only_dir(d) — both new tests still pass (the helper routes through the patched restrict_dir_to_owner and absorbs the raise), and the "Best-effort by contract, unlike the fail-loud helper" docstring paragraph deletes with it.

[FIRST-PRINCIPLES-REVIEWED] e12135a

@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 readiness: action required A blocking check or review needs attention labels Sep 11, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: passed Eligible automated validation passed for the current revision and removed readiness: checking Automated validation is still running labels Sep 11, 2026
@NicholasRBowers
NicholasRBowers enabled auto-merge (squash) September 11, 2026 12:35

@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 at e12135a. The change replaces a Windows-no-op POSIX mode with the established owner-only DACL helper while preserving POSIX behavior and the existing best-effort startup contract. The inherited sidecar protection is demonstrated on Windows, focused regression coverage is present, and required checks are green.

@NicholasRBowers
NicholasRBowers merged commit 4764481 into kirodotdev:main Sep 11, 2026
97 of 98 checks passed
@github-actions github-actions Bot removed the readiness: passed Eligible automated validation passed for the current revision label Sep 11, 2026
@NicholasRBowers NicholasRBowers removed the drive-to-green PR claimed by drive-to-green pipeline label Sep 11, 2026
amadsalmon pushed a commit to amadsalmon/KiroCrew that referenced this pull request Sep 22, 2026
…otdev#8164)

`_run_dir` tightened `<config_dir>/run` with `os.chmod(d, 0o700)`. A mode is
meaningless on Windows, so the directory keeps the inherited DACL — measured
with `icacls`, that is `BUILTIN\Users:(RX)` plus `NT AUTHORITY\Authenticated
Users:(M)`. The directory holds the gateway credential, the pid a client checks
before trusting a port, and the marker naming an executable mint execs.

Route it through `platform_compat.restrict_dir_to_owner`, which is the same
`chmod(0o700)` on POSIX and an owner-only DACL on Windows. Its grants carry
`(OI)(CI)`, so the `.pid` and `.bin` sidecars written by
`atomic_write(mode=0o600)` — a no-op mode on Windows — inherit owner-only too.

The helper is fail-loud, but `_run_dir` is reached through `secret_path()` on
the dashboard's startup path, so the raise is absorbed and logged: the existing
tighten-if-possible contract is what callers depend on.

Co-authored-by: Leon Lai <laputaca@gmail.com>
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.

5 participants