Skip to content

Conversation

@gaby
Copy link
Member

@gaby gaby commented Dec 10, 2025

Summary

  • This pull request enhances the security of file upload operations by introducing configurable upload root directory management and comprehensive path validation. The changes prevent directory traversal, absolute path exploits, and symlink-based attacks by validating all upload paths against a configured root directory before allowing file writes.

Key Changes:

  • Added three new configuration options: RootDir (upload root directory), RootFS (filesystem implementation for validation), and RootPerms (permissions for root directory creation)
  • Implemented multi-layer path validation in SaveFile and SaveFileToStorage methods that rejects absolute paths, directory traversal attempts, and symlink escapes
    Added comprehensive test coverage for security scenarios including traversal prevention and absolute path rejection

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 10, 2025

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch add-path-normalization-and-validation-to-savefile

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.

@ReneWerner87 ReneWerner87 added this to v3 Dec 10, 2025
@ReneWerner87 ReneWerner87 added this to the v3 milestone Dec 10, 2025
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @gaby, 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 significantly enhances the security and configurability of the file upload mechanism. It introduces dedicated configuration options for defining the root directory, file system, and permissions for uploads, alongside implementing comprehensive path validation to prevent common security vulnerabilities such as directory traversal and symlink attacks. The changes ensure that all file uploads are strictly confined to the intended root directory, improving the overall robustness of the application's file handling.

Highlights

  • Upload Configuration Renamed and Enhanced: The upload configuration fields have been renamed to RootDir and RootFS, and a new RootPerms field has been added to allow configurable default permissions for the upload root directory.
  • Secure Upload Path Resolution: The logic for resolving upload paths has been centralized and updated to use the new configuration, shared path trimming helpers, and a set of new, specific error definitions. This includes robust validation against absolute paths, directory traversal, and symlink escapes.
  • Updated Tests and Documentation: Upload-related tests have been adjusted to reflect the new configuration names and path validation. The API documentation and 'What's New' guide have been updated to clearly document the new upload root requirements and security features.
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.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

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.

@codecov
Copy link

codecov bot commented Dec 10, 2025

Codecov Report

❌ Patch coverage is 60.57692% with 41 lines in your changes missing coverage. Please review.
✅ Project coverage is 91.34%. Comparing base (26e8e8a) to head (b550622).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
ctx.go 59.00% 22 Missing and 19 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3934      +/-   ##
==========================================
- Coverage   91.56%   91.34%   -0.23%     
==========================================
  Files         119      119              
  Lines       10165    10266     +101     
==========================================
+ Hits         9308     9377      +69     
- Misses        544      560      +16     
- Partials      313      329      +16     
Flag Coverage Δ
unittests 91.34% <60.57%> (-0.23%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.

Copy link
Contributor

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

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 introduces significant security enhancements to file uploads by adding robust path validation and sanitization. The changes are well-structured, centralizing path resolution logic and adding comprehensive tests. I have a couple of suggestions for refactoring and test cleanup to further improve the code.

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This pull request enhances the security of file upload operations by introducing configurable upload root directory management and comprehensive path validation. The changes prevent directory traversal, absolute path exploits, and symlink-based attacks by validating all upload paths against a configured root directory before allowing file writes.

Key Changes:

  • Added three new configuration options: RootDir (upload root directory), RootFS (filesystem implementation for validation), and RootPerms (permissions for root directory creation)
  • Implemented multi-layer path validation in SaveFile and SaveFileToStorage methods that rejects absolute paths, directory traversal attempts, and symlink escapes
  • Added comprehensive test coverage for security scenarios including traversal prevention and absolute path rejection

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
error.go Adds four new error variables for upload path validation failures
app.go Introduces RootDir, RootFS, and RootPerms configuration fields with appropriate defaults
ctx.go Implements path validation logic through resolveUploadPath, sanitizeUploadPath, rejectSymlinkTraversal, and helper functions; updates SaveFile and SaveFileToStorage to use validation
ctx_test.go Adds security-focused tests for path traversal prevention, absolute path rejection, and validates storage upload path validation
docs/whats_new.md Documents the new upload security features in the "What's New" section
docs/api/ctx.md Updates SaveFile and SaveFileToStorage documentation to describe the new path validation behavior and configuration options

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

⚠️ Performance Alert ⚠️

Possible performance regression was detected for benchmark.
Benchmark result of this commit is worse than the previous benchmark result exceeding threshold 1.50.

Benchmark suite Current: b550622 Previous: dd0b041 Ratio
Benchmark_Compress/Zstd - B/op 1 B/op 0 B/op +∞
Benchmark_Compress_Levels/Zstd_LevelDefault - B/op 1 B/op 0 B/op +∞
Benchmark_Compress_Levels/Zstd_LevelBestCompression - B/op 1 B/op 0 B/op +∞

This comment was automatically generated by workflow using github-action-benchmark.

@gaby
Copy link
Member Author

gaby commented Dec 10, 2025

/gemini review

@gaby
Copy link
Member Author

gaby commented Dec 10, 2025

@codex review

Copy link
Contributor

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

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 significantly enhances the security of file uploads by introducing new configuration options (RootDir, RootFS, RootPerms) and robust path validation for the SaveFile and SaveFileToStorage methods. The changes include comprehensive path sanitization to reject absolute paths, prevent directory traversal attempts (e.g., using ..), and ensure files are saved strictly within the configured RootDir. A critical rejectSymlinkTraversal function was added to prevent symlink-based attacks by validating each path segment against the RootFS, while filepath.EvalSymlinks is used on the RootDir itself to prevent root directory manipulation. The isWithinRoot function provides a final containment check. New tests were added to verify these security measures, and review comments emphasized the importance and effectiveness of these layered validations against common path manipulation vulnerabilities.

Copy link

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 3 comments.

ctx.go Outdated
Comment on lines 468 to 470
if err := os.MkdirAll(filepath.Dir(absolutePath), c.app.config.RootPerms); err != nil {
return fmt.Errorf("failed to prepare upload path: %w", err)
}
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

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

The directory creation in SaveFile uses RootPerms for intermediate directories, but this may not be the intended behavior. Typically, intermediate directories should have different permissions than the root directory (often 0o755 for intermediate paths vs 0o750 for the root). This could lead to overly restrictive permissions on nested upload directories, potentially causing permission issues when other processes need to access these paths.

Suggested change
if err := os.MkdirAll(filepath.Dir(absolutePath), c.app.config.RootPerms); err != nil {
return fmt.Errorf("failed to prepare upload path: %w", err)
}
dirPath := filepath.Dir(absolutePath)
// Create intermediate directories with 0o755
if err := os.MkdirAll(dirPath, 0o755); err != nil {
return fmt.Errorf("failed to prepare upload path: %w", err)
}
// Set the final directory's permissions to RootPerms
if err := os.Chmod(dirPath, c.app.config.RootPerms); err != nil {
return fmt.Errorf("failed to set upload directory permissions: %w", err)
}

Copilot uses AI. Check for mistakes.
Comment on lines 548 to 585
func getRootDir(app *App) (string, error) {
root := app.config.RootDir
if root == "" {
root = "."
}

perms := app.config.RootPerms
if perms == 0 {
perms = 0o750
}

absoluteRoot, err := filepath.Abs(root)
if err != nil {
return "", fmt.Errorf("invalid upload root: %w", err)
}

if err = os.MkdirAll(absoluteRoot, perms); err != nil {
return "", fmt.Errorf("invalid upload root: %w", err)
}

resolvedRoot, err := filepath.EvalSymlinks(absoluteRoot)
if err == nil {
absoluteRoot = resolvedRoot
} else if !errors.Is(err, fs.ErrNotExist) {
return "", fmt.Errorf("invalid upload root: %w", err)
}

info, err := os.Stat(absoluteRoot)
if err != nil {
return "", fmt.Errorf("invalid upload root: %w", err)
}

if !info.IsDir() {
return "", fmt.Errorf("invalid upload root: %s is not a directory", absoluteRoot)
}

return absoluteRoot, nil
}
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

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

The getRootDir function is called on every file upload to validate and create the root directory. This creates unnecessary filesystem overhead for repeated uploads. Consider caching the validated root directory path after the first successful resolution, as the root configuration doesn't change during the application's lifetime. This would eliminate redundant filepath.Abs, os.MkdirAll, filepath.EvalSymlinks, and os.Stat calls on every upload.

Copilot uses AI. Check for mistakes.
Comment on lines +614 to +668
func rejectSymlinkTraversal(uploadFS fs.FS, normalized string) error {
if uploadFS == nil {
return nil
}

parts := strings.Split(normalized, "/")
parent := "."

for i, part := range parts {
entries, err := fs.ReadDir(uploadFS, parent)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return fmt.Errorf("invalid upload path: %w", err)
}

var entry fs.DirEntry

for _, e := range entries {
if e.Name() == part {
entry = e
break
}
}

if entry == nil {
return nil
}

if entry.Type()&fs.ModeSymlink != 0 {
return errUploadSymlinkPath
}

info, err := entry.Info()
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return nil
}
return fmt.Errorf("invalid upload path: %w", err)
}

if i < len(parts)-1 && !info.IsDir() {
return errUploadTraversal
}

if parent == "." {
parent = part
} else {
parent = pathpkg.Join(parent, part)
}
}

return nil
}
Copy link

Copilot AI Dec 12, 2025

Choose a reason for hiding this comment

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

The rejectSymlinkTraversal function performs directory traversal on every upload, which can cause significant performance degradation especially for deeply nested paths or directories with many entries. Each directory is read fully using fs.ReadDir, and this happens for every path component. For frequent uploads, this overhead can be substantial. Consider caching directory metadata or implementing a more efficient validation approach.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

3 participants