fix: prevent path traversal in file tree and preview APIs #16
+221
−15
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
The file tree API (
/api/files) and file preview API (/api/files/preview) have ineffective path safety checks that could allow reading arbitrary files on the host system.Problem
/api/files(file tree)/api/files/preview(file preview)This means requests like
GET /api/files/preview?path=/etc/passwdwill succeed and return the file contents.Fix
baseDirquery parameter to both APIs. The frontend can pass the session'sworkingDirectoryas the trust boundary.baseDiris provided, the requested path is validated to be within it using the existingisPathSafe()function./api/files/previewwithoutbaseDir, falls back to restricting access to the user's home directory (prevents reading system files like/etc/passwd).baseDircontinue to work, with the home directory fallback providing a reasonable safety net.Security Note
CodePilot runs locally so the attack surface is limited, but proper validation prevents accidental exposure when the dev server is bound to non-localhost interfaces or accessed via browser extensions.
Tests
Added 13 unit tests (
src/__tests__/unit/files-security.test.ts) covering:../(blocked)/projectvs/project-evil) (blocked)/etc/passwd) (blocked)All 13 tests pass:
Run with:
npx tsx --test src/__tests__/unit/files-security.test.ts