Skip to content

Fix: tmpdir traversal bypass#31

Merged
kenryu42 merged 12 commits intomainfrom
fix/tmpdir-traversal-bypass
Mar 12, 2026
Merged

Fix: tmpdir traversal bypass#31
kenryu42 merged 12 commits intomainfrom
fix/tmpdir-traversal-bypass

Conversation

@kenryu42
Copy link
Owner

@kenryu42 kenryu42 commented Mar 12, 2026

Summary

  • Fix path traversal bypass in TMPDIR validation (e.g., TMPDIR=/tmp/../root was incorrectly allowed)
  • Refactor CI/publish workflows — merge separate quality/test jobs into single full-check job
  • Add comprehensive tests for traversal detection, shell parsing edge cases, and CI workflow validation

Changes

  • src/core/analyze/tmpdir.ts — Normalize paths with node:path before comparison; use platform sep instead of hardcoded /
  • src/core/shell.ts — Remove unreachable undefined check, use proper type assertion, remove unused parseEnvAssignment()
  • .github/workflows/ci.yml — Merge quality + test into full-check job using check:ci; add trigger path filters for push/pull_request; use --frozen-lockfile
  • .github/workflows/publish.yml — Merge test + typecheck into full-check job using check:ci; use --frozen-lockfile
  • package.json — Add check:ci (non-write lint + typecheck + knip + ast-grep + tests w/ lcov) and lint:ci scripts
  • tests/core/analyze/tmpdir.test.ts [NEW] — Unit tests for traversal detection across /tmp, /var/tmp, and system tmpdir
  • tests/scripts/ci-workflow.test.ts [NEW] — Validates CI trigger path filters stay in sync
  • tests/core/rules-rm.test.ts — Integration tests for rm -rf with traversal-based TMPDIR
  • tests/core/analyze/analyze-coverage.test.ts, parsing-helpers.test.ts — Edge-case coverage for env assignment parsing

Testing

bun run check

Related Issue

PR Checklist

  • I have read the CONTRIBUTING.md
  • Code follows project conventions (type hints, naming, etc.)
  • bun run check passes (lint, types, dead code, rules, tests)
  • Tests added for new rules (minimum 90% coverage required)
  • Tested locally with Claude Code, OpenCode, Gemini CLI or GitHub Copilot CLI
  • No version changes in package.json

Summary by CodeRabbit

  • Bug Fixes

    • Improved TMPDIR override detection and normalization to block path-traversal and rm -rf escape cases.
    • Hardened shell parsing to handle edge-case tokens and environment assignments.
  • Tests

    • Added tests covering TMPDIR traversal scenarios, rm -rf protections, and shell-parsing edge cases.
    • Added CI workflow validation tests.
  • Chores

    • Consolidated CI into a single full-check flow, tightened installs with frozen lockfile, expanded workflow path triggers, and added combined CI/lint scripts.

@coderabbitai
Copy link

coderabbitai bot commented Mar 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 6097e5d7-e759-4ab9-a185-8d4c4649c340

📥 Commits

Reviewing files that changed from the base of the PR and between f479d86 and 3e7df7f.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml

📝 Walkthrough

Walkthrough

Consolidates CI checks into a single full-check job running bun run check:ci, tightens installs with --frozen-lockfile, normalizes TMPDIR handling and path separators, simplifies shell parsing guards, and adds tests for TMPDIR traversal, parsing edge cases, and CI workflow path filters.

Changes

Cohort / File(s) Summary
Workflow Consolidation
.github/workflows/.../ci.yml, .github/workflows/.../publish.yml
Replaced granular quality/test/typecheck jobs with a single full-check job that runs bun run check:ci; switched bun installbun install --frozen-lockfile; updated job dependencies so build/publish depend on full-check; added publish preparatory steps.
NPM Scripts
package.json
Added check:ci (runs lint:ci, typecheck, knip, sg:scan, tests with coverage) and lint:ci scripts.
TMPDIR Normalization
src/core/analyze/tmpdir.ts
Normalize TMPDIR via node:path (normalize, sep); compare normalized TMPDIR against /tmp and /var/tmp; use platform sep for prefix checks.
Shell Parsing
src/core/shell.ts
Removed guards that skipped undefined tokens and dropped an explicit '=' guard in env parsing; simplified token handling relying on regex validation.
TMPDIR Traversal Tests
tests/core/analyze/tmpdir.test.ts, tests/bin/explain/command.test.ts, tests/core/analyze/analyze-coverage.test.ts, tests/core/rules-rm.test.ts
Added tests asserting TMPDIR values that traverse out of /tmp or /var/tmp (e.g., /tmp/../root) are detected/blocked.
Parsing & Edge-case Tests
tests/core/analyze/parsing-helpers.test.ts, tests/bin/doctor/system-info.test.ts
Added tests for trailing shell comments, capturing empty env var values, and handling synchronous spawn failures.
Workflow Validation Tests
tests/scripts/ci-workflow.test.ts
New test suite parsing .github/workflows/ci.yml to assert required path filters for push/pull_request triggers (including assets/**, package.json).

Sequence Diagram(s)

mermaid
sequenceDiagram
participant Dev as Developer (push/pr)
participant GH as GitHub Actions
participant Runner as Runner (setup-bun)
participant Checker as bun run check:ci
participant Build as Build job
participant Publish as Publish job
Dev->>GH: push / pull_request (path filters)
GH->>Runner: start full-check
Runner->>Checker: bun install --frozen-lockfile\nbun run check:ci
Checker->>GH: report status (checks, coverage)
GH->>Build: trigger build (needs: full-check)
GH->>Publish: trigger publish (needs: full-check)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I hopped through CI with one tidy trick,

One full-check to run every lint and pick.
TMPDIR now normalized, no sneaky escape,
Parsers made simpler — fewer guards to scrape.
Tests hop in step, keeping pipelines slick. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix: tmpdir traversal bypass' clearly and specifically summarizes the main security fix in the changeset, which is preventing path traversal bypass in TMPDIR validation.
Description check ✅ Passed The PR description is comprehensive, following the template structure with Summary, Changes, Testing, and a completed PR Checklist. All major changes are documented with specifics about file modifications and new tests.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/tmpdir-traversal-bypass
📝 Coding Plan for PR comments
  • Generate coding plan

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Mar 12, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.53%. Comparing base (d302eef) to head (3e7df7f).
⚠️ Report is 17 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main      #31      +/-   ##
==========================================
+ Coverage   99.44%   99.53%   +0.08%     
==========================================
  Files          50       50              
  Lines        4533     4528       -5     
==========================================
- Hits         4508     4507       -1     
+ Misses         25       21       -4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@greptile-apps
Copy link

greptile-apps bot commented Mar 12, 2026

Greptile Summary

This PR closes a security gap where a crafted TMPDIR value containing .. segments (e.g., TMPDIR=/tmp/../root) could bypass the temp-directory allowlist and let a rm -rf $TMPDIR/... command operate outside safe directories. It also performs clean-up of dead code in the shell parser and consolidates the CI pipeline.

Changes:

  • Security fixisTmpdirOverriddenToNonTemp now calls path.normalize() on the user-supplied value and all base paths before comparison, resolving traversal sequences before the allowlist check.
  • Dead code removal — Removed the unreachable undefined guard in splitShellCommands (the while (i < tokens.length) bound already prevents out-of-range access) and the unreachable eqIdx < 0 guard in parseEnvAssignment (the regex pre-condition guarantees = is always present).
  • CI consolidationquality + test jobs merged into a single full-check job; --frozen-lockfile added for reproducible installs; path filters broadened to include config files and assets.
  • Test coverage — New dedicated unit tests for traversal-based bypass, edge-case shell parsing (empty env assignments, trailing comments), and a YAML-parsing test that asserts CI path-filter parity.

Confidence Score: 5/5

  • This PR is safe to merge — the security fix is correct, the dead code removed is genuinely unreachable, and all changes are backed by new tests.
  • The core fix (normalize before allowlist comparison) is logically sound and directly addresses the traversal bypass. The dead-code removals are provably safe by inspection. CI changes are additive and non-breaking. No regressions are expected.
  • No files require special attention.

Important Files Changed

Filename Overview
src/core/analyze/tmpdir.ts Fixes path traversal bypass by calling normalize() on both the user-supplied TMPDIR value and the allowed base paths before comparison; replaces hardcoded / with platform sep.
src/core/shell.ts Removes two pieces of dead code: the unreachable undefined guard in splitShellCommands (loop condition already guarantees in-bounds access) and the unreachable eqIdx < 0 guard in parseEnvAssignment (the regex pre-condition guarantees = is present).
tests/core/analyze/tmpdir.test.ts New test file covering traversal escapes from /tmp, /var/tmp, and the system tmpdir; confirms allowed subpaths still pass.
tests/scripts/ci-workflow.test.ts New test that parses the CI YAML file to assert required path-filter entries are present for both push and pull_request triggers, preventing accidental omission of trigger paths.
.github/workflows/ci.yml Merges quality and test jobs into a single full-check job using the new check:ci script; adds --frozen-lockfile and expands path filters to cover config and asset files.
.github/workflows/publish.yml Merges test and typecheck jobs into full-check; adds --frozen-lockfile for reproducible dependency installs during publish.
package.json Adds check:ci (non-write lint + all checks + lcov coverage) and lint:ci (biome ci) scripts for use in CI pipelines where file mutation is undesirable.
dist/index.js Bundled output consistent with source changes in shell.ts and tmpdir.ts.
dist/bin/cc-safety-net.js Bundled binary output consistent with source changes in shell.ts and tmpdir.ts.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["TMPDIR env assignment detected"] --> B{"tmpdirValue == ''?"}
    B -- Yes --> BLOCK["🚫 Block (empty TMPDIR)"]
    B -- No --> C["normalize(tmpdirValue)"]
    C --> D{"isPathOrSubpath(normalized, /tmp)\nor /var/tmp\nor sysTmpdir?"}
    D -- Yes --> ALLOW["✅ Allow"]
    D -- No --> BLOCK2["🚫 Block (non-temp path)"]

    subgraph "Before fix"
        E["/tmp/../root"] -- "raw string" --> F{"startsWith /tmp/?"}
        F -- "Yes ❌ (bypassed!)" --> ALLOW2["✅ Allow (incorrect)"]
    end

    subgraph "After fix"
        G["/tmp/../root"] -- "normalize()" --> H["/root"]
        H --> I{"startsWith /tmp/?"}
        I -- "No ✅" --> BLOCK3["🚫 Block (correct)"]
    end
Loading

Last reviewed commit: 3e7df7f

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
.github/workflows/publish.yml (1)

69-72: Use --frozen-lockfile in the publish job too.

The publish job is gated by full-check, which validates the lockfile with --frozen-lockfile. Reinstalling dependencies in publish with the same strict mode ensures consistency and makes the release path deterministic and fail-closed.

Suggested fix
       - name: Install dependencies
-        run: bun install
+        run: bun install --frozen-lockfile
         env:
           BUN_INSTALL_ALLOW_SCRIPTS: "@ast-grep/cli"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/publish.yml around lines 69 - 72, In the publish job's
"Install dependencies" step replace the plain bun install invocation with bun
install --frozen-lockfile to enforce the same lockfile validation as full-check;
update the command where "Install dependencies" is defined (the step that
currently runs "bun install" and sets BUN_INSTALL_ALLOW_SCRIPTS) so the install
runs with the --frozen-lockfile flag to make the publish path deterministic and
fail if the lockfile is out of date.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/ci.yml:
- Around line 7-18: The CI push trigger currently excludes package.json from the
push.paths list, so updates to dependencies or scripts skip post-merge jobs;
update the paths block in .github/workflows/ci.yml (the paths: entries) to
include "package.json" (or remove the exclusion logic) so that changes to
package.json will trigger the push workflow and run the build/draft-release
steps after merge.

---

Nitpick comments:
In @.github/workflows/publish.yml:
- Around line 69-72: In the publish job's "Install dependencies" step replace
the plain bun install invocation with bun install --frozen-lockfile to enforce
the same lockfile validation as full-check; update the command where "Install
dependencies" is defined (the step that currently runs "bun install" and sets
BUN_INSTALL_ALLOW_SCRIPTS) so the install runs with the --frozen-lockfile flag
to make the publish path deterministic and fail if the lockfile is out of date.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 54673cf6-f4ec-43c0-b833-b01ca5f15184

📥 Commits

Reviewing files that changed from the base of the PR and between 82f676b and 417277a.

⛔ Files ignored due to path filters (2)
  • dist/bin/cc-safety-net.js is excluded by !**/dist/**
  • dist/index.js is excluded by !**/dist/**
📒 Files selected for processing (12)
  • .github/workflows/ci.yml
  • .github/workflows/publish.yml
  • package.json
  • src/core/analyze/tmpdir.ts
  • src/core/shell.ts
  • tests/bin/doctor/system-info.test.ts
  • tests/bin/explain/command.test.ts
  • tests/core/analyze/analyze-coverage.test.ts
  • tests/core/analyze/parsing-helpers.test.ts
  • tests/core/analyze/tmpdir.test.ts
  • tests/core/rules-rm.test.ts
  • tests/scripts/ci-workflow.test.ts

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/ci.yml:
- Around line 7-19: The workflow's push.paths filter omits assets/** so the
auto-commit that pushes assets/cc-safety-net.schema.json (the auto-commit step
that updates the schema) can bypass CI; update the push.paths section to include
"assets/**" (or change the auto-commit to create a PR instead of pushing
directly) so that changes to assets/cc-safety-net.schema.json always retrigger
the ci.yml workflow; specifically modify the push.paths block to add the
"assets/**" entry (or alter the auto-commit logic that pushes
assets/cc-safety-net.schema.json).

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b4ef16f4-be3e-46d4-a4c9-60085a6d5370

📥 Commits

Reviewing files that changed from the base of the PR and between 417277a and 93d3f5a.

📒 Files selected for processing (2)
  • .github/workflows/ci.yml
  • tests/scripts/ci-workflow.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/scripts/ci-workflow.test.ts

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
.github/workflows/ci.yml (1)

68-84: ⚠️ Potential issue | 🟠 Major

Freeze the lockfile in build too.

The build job depends on full-check but uses plain bun install instead of --frozen-lockfile. This allows the artifact-producing job to resolve a different dependency graph than the one validated in full-check, making release artifacts less reproducible and potentially inconsistent with the validated state.

       - name: Install dependencies
-        run: bun install
+        run: bun install --frozen-lockfile
         env:
           BUN_INSTALL_ALLOW_SCRIPTS: "@ast-grep/cli"
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/ci.yml around lines 68 - 84, The build job currently runs
a non-frozen install ("bun install" in the Install dependencies step), which can
produce a different dependency graph than full-check; update that step in the
build job to run bun install --frozen-lockfile (preserving the existing env
BUN_INSTALL_ALLOW_SCRIPTS) so the lockfile is enforced and the
artifact-producing job uses the exact, validated dependency graph from
full-check.
🧹 Nitpick comments (1)
.github/workflows/ci.yml (1)

49-51: Pin Bun to a specific version in all workflows.

Using bun-version: latest makes CI behavior change whenever Bun ships a new release. This affects 6 workflow locations across 4 files (.github/workflows/ci.yml, publish.yml, test-windows.yml). Since package.json does not declare a Bun version, pin a specific version directly in the workflows or add version declaration to package.json and reference it consistently.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In @.github/workflows/ci.yml around lines 49 - 51, CI workflows currently use
"uses: oven-sh/setup-bun@v2" with the input key "bun-version: latest", which
causes nondeterministic CI when Bun releases new versions; update each workflow
location (where oven-sh/setup-bun@v2 is used and bun-version is set) to pin a
concrete Bun version string (e.g., "bun-version: 1.0.0" or whatever your project
requires) or alternatively add a Bun version field to package.json and read that
in the workflows, ensuring all occurrences of the bun-version input across
.github/workflows/ci.yml, publish.yml, and test-windows.yml are changed to
reference the fixed version variable/value.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In @.github/workflows/ci.yml:
- Around line 68-84: The build job currently runs a non-frozen install ("bun
install" in the Install dependencies step), which can produce a different
dependency graph than full-check; update that step in the build job to run bun
install --frozen-lockfile (preserving the existing env
BUN_INSTALL_ALLOW_SCRIPTS) so the lockfile is enforced and the
artifact-producing job uses the exact, validated dependency graph from
full-check.

---

Nitpick comments:
In @.github/workflows/ci.yml:
- Around line 49-51: CI workflows currently use "uses: oven-sh/setup-bun@v2"
with the input key "bun-version: latest", which causes nondeterministic CI when
Bun releases new versions; update each workflow location (where
oven-sh/setup-bun@v2 is used and bun-version is set) to pin a concrete Bun
version string (e.g., "bun-version: 1.0.0" or whatever your project requires) or
alternatively add a Bun version field to package.json and read that in the
workflows, ensuring all occurrences of the bun-version input across
.github/workflows/ci.yml, publish.yml, and test-windows.yml are changed to
reference the fixed version variable/value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ba09b154-42f5-42db-94aa-139d3495a434

📥 Commits

Reviewing files that changed from the base of the PR and between 93d3f5a and f479d86.

📒 Files selected for processing (2)
  • .github/workflows/ci.yml
  • tests/scripts/ci-workflow.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/scripts/ci-workflow.test.ts

@kenryu42
Copy link
Owner Author

@greptileai review the PR

@kenryu42 kenryu42 merged commit 63e4b7f into main Mar 12, 2026
10 checks passed
@kenryu42 kenryu42 deleted the fix/tmpdir-traversal-bypass branch March 12, 2026 15:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant