Skip to content

fix(backend): prevent static file path traversal - #79

Merged
koitococobot[bot] merged 3 commits into
mainfrom
codex/fix-path-traversal-vulnerability-in-static-file-serving
Nov 24, 2026
Merged

koitococobot[bot] merged 3 commits into
mainfrom
codex/fix-path-traversal-vulnerability-in-static-file-serving

Conversation

@pescn

@pescn pescn commented Mar 21, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

  • A custom static file server was joining untrusted request paths to asset directories without normalization or a root-boundary check, allowing path traversal and arbitrary file reads from the filesystem.

Description

  • Add a bounded resolver resolveStaticPath(rootDir, requestPath) in backend/src/utils/staticFile.ts that normalizes the request path, resolves it against the static root, and returns null if the resolved path escapes the root.
  • Update serveStaticFile in backend/src/index.ts to accept a rootDir and requestPath, call resolveStaticPath, and only stat/readFile when the resolved path is inside the static root.
  • Replace unsafe join(dir, path) usages in the docs and SPA handlers so they call serveStaticFile(dir, path) and use resolveStaticPath for directory index.html lookups to enforce the same boundary.
  • Add focused regression tests in backend/src/utils/staticFile.test.ts to validate allowed in-root resolution and blocked traversal attempts.

Testing

  • Ran the focused unit tests with bun --cwd backend test src/utils/staticFile.test.ts, and all tests passed.
  • Attempted bun --cwd backend test src/utils/staticFile.test.ts src/utils/json.test.ts, which failed due to an unrelated missing runtime dependency (@loglayer/transport-simple-pretty-terminal) in the current environment, not due to these changes.
  • Ran bun --cwd backend check, which fails in the container because project dependencies/types are not installed, producing pre-existing type/module resolution errors unrelated to the fix.

Codex Task

Summary by CodeRabbit

发布说明

  • Bug 修复
    • 改进静态文件路径解析。文档和应用页面会按顺序尝试匹配文件、子目录索引页及主索引页;找不到主索引页时返回 404。
    • 根目录之外的路径不再回退到 HTML 页面;支持指向静态根目录内文件的符号链接。
  • 文档
    • 补充静态文件目录配置及符号链接的部署要求。
  • Tests
    • 增加静态文件路径和符号链接处理的测试覆盖。

@gemini-code-assist

Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request addresses a critical security vulnerability in the backend's static file server. Previously, the server was susceptible to path traversal, allowing unauthorized access to arbitrary files on the filesystem. The changes introduce a robust mechanism to confine static file requests strictly within their designated root directories, significantly enhancing the application's security posture by preventing malicious file access.

Highlights

  • New Bounded Path Resolver: Introduced resolveStaticPath in backend/src/utils/staticFile.ts to securely resolve request paths within a defined root directory, returning null if the path attempts to escape the root.
  • Enhanced Static File Serving: Modified serveStaticFile in backend/src/index.ts to utilize the new resolveStaticPath function, ensuring that files are only served if their resolved path remains within the specified rootDir.
  • Vulnerability Remediation: Replaced direct join(dir, path) usages in the docs and SPA handlers with calls to the updated serveStaticFile and resolveStaticPath for index.html lookups, preventing path traversal vulnerabilities.
  • Comprehensive Testing: Added dedicated regression tests in backend/src/utils/staticFile.test.ts to validate the correct behavior of resolveStaticPath, covering both allowed in-root resolutions and blocked traversal attempts.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@coderabbitai

coderabbitai Bot commented Mar 21, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

静态文件服务现在通过共享解析流程处理请求路径,并检查解析后的实际文件路径。文档与 SPA 插件使用该流程读取静态文件和索引。新增路径与符号链接测试,并补充静态目录配置说明。

Changes: 静态文件服务

Layer / File(s) Summary
路径解析与文件系统校验
backend/src/utils/staticFile.ts, backend/src/utils/staticFile.test.ts
新增 resolveStaticPath 和 resolveStaticFile。路径越出根目录时返回 null;缺失文件或非文件目标返回 undefined。测试覆盖路径规范化、符号链接和缺失目标。
文档与 SPA 路由接入
backend/src/index.ts
文档与 SPA 插件先解析静态根目录,再通过共享流程读取文件。文档路由依次尝试精确文件、子目录的 index.html 和主索引;主索引缺失时返回 404。MIME 类型根据请求路径的 basename 扩展名确定。
静态目录运行说明
backend/README.md
新增说明:FRONTEND_DIR 和 DOCS_DIR 应指向可信目录,运行期间应防止不可信用户写入。根目录外的请求返回 404,不回退到 HTML shell。

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: koitococo

Merge Risk: Minimal · up to 33727

This change hardens static file serving against path traversal and symlink escapes for the docs and SPA routes. The supplied evidence shows no remaining concrete defect, so it looks safe to merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed 标题“fix(backend): prevent static file path traversal”与变更集主要内容一致。变更新增 resolveStaticPath 和 resolveStaticFile,拒绝越出根目录的路径,并将文档、SPA 和静态文件服务统一到同一解析流程,修复路径穿越问题。标题简洁,指出了主要修复内容和影响范围。
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

我是小兔,绕根目录巡查
规范路径,逐段核对
符号链接,确认目标
找不到文件,就如实返回
文档与页面,共用解析流程
新增测试,逐项验证

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI (base), Organization UI (inherited)
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 9a3e1461-f6a4-4bce-90ef-23f6a7cf78df
Commits

Reviewing files that changed from the base of the PR and between 03a7b9c and 3372794.

Files selected for processing: 4

  • backend/README.md
  • backend/src/index.ts
  • backend/src/utils/staticFile.test.ts
  • backend/src/utils/staticFile.ts

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request effectively addresses a critical path traversal vulnerability by introducing a new resolveStaticPath utility to safely resolve user-provided paths against a static root directory. The changes are well-structured, and the new utility is correctly integrated into the existing static file serving logic. The inclusion of focused unit tests is also a great practice. My feedback includes one suggestion to further enhance the robustness of the new utility function against malformed inputs, ensuring even more graceful error handling, aligning with best practices for handling external data.

Comment on lines +3 to +17
export function resolveStaticPath(
rootDir: string,
requestPath: string,
): string | null {
const resolvedRoot = resolve(rootDir);
const normalizedRequestPath = requestPath.replace(/^\/+/u, "");
const resolvedPath = resolve(resolvedRoot, normalizedRequestPath);
const relativePath = relative(resolvedRoot, resolvedPath);

if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
return null;
}

return resolvedPath;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

medium

For improved robustness against malformed input, consider wrapping the path resolution logic in a try...catch block. Functions from node:path like resolve can throw a TypeError if the path contains a null byte (\0), which is a common technique for probing for vulnerabilities. An unhandled exception would cause a 500 error. By catching this and returning null, you can treat it as just another invalid path and return a 404, which is a more graceful and secure way to handle it.

Suggested change
export function resolveStaticPath(
rootDir: string,
requestPath: string,
): string | null {
const resolvedRoot = resolve(rootDir);
const normalizedRequestPath = requestPath.replace(/^\/+/u, "");
const resolvedPath = resolve(resolvedRoot, normalizedRequestPath);
const relativePath = relative(resolvedRoot, resolvedPath);
if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
return null;
}
return resolvedPath;
}
export function resolveStaticPath(
rootDir: string,
requestPath: string,
): string | null {
try {
const resolvedRoot = resolve(rootDir);
const normalizedRequestPath = requestPath.replace(/^\/+/u, "");
const resolvedPath = resolve(resolvedRoot, normalizedRequestPath);
const relativePath = relative(resolvedRoot, resolvedPath);
if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
return null;
}
return resolvedPath;
} catch {
return null;
}
}
References
  1. This suggestion aligns with the principle of handling potentially malformed external input gracefully. Similar to how JSON.parse should be wrapped in a try...catch block to handle malformed JSON and prevent crashes, as per the rule: 'When parsing JSON from a data source, even a trusted one, wrap JSON.parse in a try...catch block to handle potential malformed data gracefully and prevent crashes.' Applying try...catch to node:path.resolve for user-provided paths ensures similar robustness against invalid or malicious input like null bytes.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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)
backend/src/utils/staticFile.test.ts (1)

4-27: 建议添加 URL 编码路径的测试用例。

当前测试覆盖了基本场景,但建议补充以下测试用例以确保安全性完整:

  1. URL 编码的遍历尝试:验证 %2e%2e%2f 是否被正确处理
  2. 空字符串输入:resolveStaticPath("/app/public", "") 的行为
  3. 包含空字节的路径:如 "/assets\x00.js"
🧪 建议添加的测试用例
+  test("handles URL-encoded traversal attempt as literal path", () => {
+    // If Elysia decodes before passing, this test documents expected behavior
+    // If not decoded, %2e%2e should be treated as literal filename
+    const result = resolveStaticPath("/app/public", "/%2e%2e/etc/passwd");
+    // Result depends on whether this is decoded upstream or not
+    expect(result).not.toBeNull(); // treated as literal "%2e%2e" directory
+  });
+
+  test("resolves empty request path to root", () => {
+    expect(resolveStaticPath("/app/public", "")).toBe("/app/public");
+  });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/utils/staticFile.test.ts` around lines 4 - 27, Add unit tests for
resolveStaticPath to cover URL-encoded traversal, empty-string request paths,
and paths containing a null byte: 1) add a test that passes an encoded traversal
like "%2e%2e%2fetc/passwd" (and variants) and assert resolveStaticPath(...)
returns null; 2) add a test for an empty request path "" and assert it resolves
to the static root (e.g., "/app/public"); 3) add a test for a request containing
a NUL character (e.g., "/assets\\x00.js" or the literal NUL) and assert
resolveStaticPath(...) returns null to ensure such inputs are rejected. Ensure
tests call the existing resolveStaticPath function so they fail if
encoding/validation is not handled.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@backend/src/utils/staticFile.ts`:
- Around line 3-17: The resolveStaticPath function does not URL-decode the
incoming requestPath, allowing encoded traversal sequences like %2e%2e%2f to
bypass the ../ check; fix by decoding requestPath (use decodeURIComponent)
before computing normalizedRequestPath so the subsequent
resolve/resolvedPath/relativePath checks catch encoded traversal, and ensure you
handle/deal with potential decode errors (e.g., wrap decodeURIComponent in
try/catch and return null on failure) while keeping the rest of
resolveStaticPath logic unchanged.

---

Nitpick comments:
In `@backend/src/utils/staticFile.test.ts`:
- Around line 4-27: Add unit tests for resolveStaticPath to cover URL-encoded
traversal, empty-string request paths, and paths containing a null byte: 1) add
a test that passes an encoded traversal like "%2e%2e%2fetc/passwd" (and
variants) and assert resolveStaticPath(...) returns null; 2) add a test for an
empty request path "" and assert it resolves to the static root (e.g.,
"/app/public"); 3) add a test for a request containing a NUL character (e.g.,
"/assets\\x00.js" or the literal NUL) and assert resolveStaticPath(...) returns
null to ensure such inputs are rejected. Ensure tests call the existing
resolveStaticPath function so they fail if encoding/validation is not handled.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI (base), Organization UI (inherited)

Review profile: CHILL

Plan: Pro

Run ID: 6f0fd16f-d756-4bd9-a80c-0ce7dea1e59e

📥 Commits

Reviewing files that changed from the base of the PR and between a394871 and 03a7b9c.

📒 Files selected for processing (3)
  • backend/src/index.ts
  • backend/src/utils/staticFile.test.ts
  • backend/src/utils/staticFile.ts

Comment on lines +3 to +17
export function resolveStaticPath(
rootDir: string,
requestPath: string,
): string | null {
const resolvedRoot = resolve(rootDir);
const normalizedRequestPath = requestPath.replace(/^\/+/u, "");
const resolvedPath = resolve(resolvedRoot, normalizedRequestPath);
const relativePath = relative(resolvedRoot, resolvedPath);

if (relativePath.startsWith("..") || isAbsolute(relativePath)) {
return null;
}

return resolvedPath;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check Elysia's path handling behavior and whether it URL-decodes paths

# Search for Elysia documentation or tests about path parameter behavior
rg -n -C3 'path.*decode' --type=ts

# Check if there's any URL decoding in the codebase for request paths
rg -n 'decodeURI' --type=ts

Repository: EM-GeekLab/NexusGate

Length of output: 355


🌐 Web query:

Does Elysia framework URL decode the path parameter before passing to route handlers?

💡 Result:

No, the Elysia framework does not automatically URL decode path parameters before passing them to route handlers. Path parameters are extracted from the raw pathname segments as received by the server (after browser/server encoding), without additional decoding by Elysia. Developers must manually decode if needed, e.g., using decodeURI in a transform hook.

Citations:


对 requestPath 进行 URL 解码以防止编码形式的路径遍历攻击。

该函数未对 requestPath 执行 URL 解码。根据 Elysia 框架的行为,路径参数在传入路由处理程序前不会自动进行 URL 解码,需要开发者手动处理。这意味着攻击者可使用百分号编码的遍历序列(如 %2e%2e%2f 代表 ../)绕过当前防护:

  • path.resolve() 不会将 %2e 解释为 .,导致编码形式的路径遍历序列被当作字面路径名处理
  • relativePath.startsWith("..") 检查无法捕获编码形式的遍历前缀
  • 函数可能返回根目录外的路径

修复方案: 在路径规范化前添加 URL 解码:

const decodedPath = decodeURIComponent(requestPath);
const normalizedRequestPath = decodedPath.replace(/^\/+/u, "");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@backend/src/utils/staticFile.ts` around lines 3 - 17, The resolveStaticPath
function does not URL-decode the incoming requestPath, allowing encoded
traversal sequences like %2e%2e%2f to bypass the ../ check; fix by decoding
requestPath (use decodeURIComponent) before computing normalizedRequestPath so
the subsequent resolve/resolvedPath/relativePath checks catch encoded traversal,
and ensure you handle/deal with potential decode errors (e.g., wrap
decodeURIComponent in try/catch and return null on failure) while keeping the
rest of resolveStaticPath logic unchanged.

Use one file boundary for docs, TanStack assets, startup indexes, and the SPA.
Keep in-root names and legitimate SPA misses working; reject invalid targets without falling back.
@koitococobot
koitococobot Bot merged commit 49d62aa into main Nov 24, 2026
2 checks passed
@koitococobot
koitococobot Bot deleted the codex/fix-path-traversal-vulnerability-in-static-file-serving branch November 24, 2026 01:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants