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.

Comment on lines 610 to 657
func rejectSymlinkTraversal(uploadFS fs.FS, normalized string) error {
if uploadFS == nil {
return nil
}

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

var entry fs.DirEntry
var found bool
for _, e := range entries {
if e.Name() == part {
entry = e
found = true
break
}
}

if !found {
return nil
}

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

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

if current == "." {
current = part
continue
}

current = pathpkg.Join(current, part)
}

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The rejectSymlinkTraversal function can be refactored for better readability and performance. The current implementation iterates through directory entries for each path segment, which can be inefficient for directories with many files. Additionally, the logic for updating the current path is more complex than necessary.

Using fs.Stat for each path component is more direct and avoids reading entire directories. This also simplifies the path traversal logic, making the function easier to understand and maintain.

func rejectSymlinkTraversal(uploadFS fs.FS, normalized string) error {
	if uploadFS == nil {
		return nil
	}

	currentPath := ""
	parts := strings.Split(normalized, "/")
	for i, part := range parts {
		currentPath = pathpkg.Join(currentPath, part)

		entryInfo, err := fs.Stat(uploadFS, currentPath)
		if err != nil {
			if errors.Is(err, fs.ErrNotExist) {
				// If a path component doesn't exist, it can't be a symlink.
				// The path will be created later, so this is fine.
				return nil
			}
			return fmt.Errorf("invalid upload path: %w", err)
		}

		// Check for symlinks. For os.DirFS, fs.Stat uses os.Lstat, which does not follow symlinks.
		if entryInfo.Mode()&fs.ModeSymlink != 0 {
			return errUploadSymlinkRoute
		}

		// All but the last part of the path must be directories
		if i < len(parts)-1 && !entryInfo.IsDir() {
			return errUploadTraversal
		}
	}

	return nil
}

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.

Comment on lines +614 to +647
func rejectSymlinkTraversal(uploadFS fs.FS, normalized string) error {
if uploadFS == nil {
return nil
}

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

for i, part := range parts {
next := part
if current != "." {
next = pathpkg.Join(current, part)
}

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

if info.Mode()&fs.ModeSymlink != 0 {
return errUploadSymlinkPath
}

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

current = next
}

return nil
Copy link
Contributor

Choose a reason for hiding this comment

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

security-critical critical

The rejectSymlinkTraversal function is a crucial security component. By iterating through each part of the normalized path and checking for symlinks using fs.Stat against the uploadFS (which is rooted at RootDir), it effectively prevents symlink traversal attacks where an attacker might try to create or overwrite files outside the designated upload root by exploiting symlinks within the provided path. The check !info.IsDir() for intermediate parts also prevents writing into a file disguised as a directory.

Comment on lines +568 to +573
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)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

security-high high

The use of filepath.EvalSymlinks on the absoluteRoot is a critical security measure. It resolves any symbolic links in the root path itself, preventing an attacker from configuring the upload root to point to a sensitive directory via a symlink. The error handling for fs.ErrNotExist is also correct, allowing the root to be a non-existent path that will be created.

Comment on lines +588 to +590
if filepath.IsAbs(path) {
return "", errUploadAbsolute
}
Copy link
Contributor

Choose a reason for hiding this comment

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

security-high high

Rejecting absolute paths (filepath.IsAbs) and directory traversal segments (containsParentDir) early in sanitizeUploadPath is a robust first line of defense against common path manipulation attacks. This ensures that user-provided paths are always relative and do not attempt to escape the intended directory structure.

Comment on lines +654 to +661
func isWithinRoot(root, target string) bool {
rel, err := filepath.Rel(root, target)
if err != nil {
return false
}

return rel != ".." && !strings.HasPrefix(rel, "../") && rel != "..\\" && !strings.HasPrefix(rel, "..\\")
}
Copy link
Contributor

Choose a reason for hiding this comment

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

security-high high

The isWithinRoot function provides an excellent final check to ensure that the target path, after all normalization and resolution, truly remains within the root directory. Using filepath.Rel and checking for .. or ../ prefixes is a robust way to confirm this containment, especially important for cross-platform compatibility with both Unix-like and Windows paths.

Comment on lines +169 to +171
// RootFS provides an fs.FS implementation rooted at RootDir used to validate upload targets.
//
// Default: os.DirFS(RootDir)
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The comment for RootFS suggests a default of os.DirFS(RootDir). While this is indeed the fallback logic in resolveUploadPath, the New function itself doesn't explicitly set this default. It might be clearer to either set app.config.RootFS = os.DirFS(app.config.RootDir) in the New function (after RootDir is initialized) or adjust the comment to reflect that it's a runtime default if not explicitly configured.

Comment on lines +597 to +600
normalized := pathpkg.Clean(rawNormalized)
normalized = utils.TrimLeft(normalized, '/')
if normalized == "" || normalized == "." {
return "", errUploadTraversal
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The combination of pathpkg.Clean and utils.TrimLeft followed by checks for empty or . paths is effective for normalizing and validating the path. This helps catch edge cases where cleaning might result in an unexpected path, further preventing traversal or writing to the root itself when a specific file is expected.

Comment on lines +603 to +605
if !fs.ValidPath(normalized) {
return "", errUploadTraversal
}
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

Using fs.ValidPath(normalized) is a good standard check for ensuring the path conforms to io/fs requirements, which can help prevent issues with invalid characters or structures that might bypass other checks.

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

Comment on lines +628 to +629
info, err := fs.Stat(uploadFS, next)
if err != nil {

Choose a reason for hiding this comment

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

P1 Badge Detect symlink traversal when validating upload paths

Upload validation walks path components with fs.Stat, but Stat follows symlinks, so the subsequent ModeSymlink check in rejectSymlinkTraversal never triggers. If the configured upload root already contains a symlinked directory (e.g., uploads/link -> /tmp/outside), a caller can save a file under that link and the write will escape the configured root despite the new validation. Use an lstat-style check (e.g., fs.ReadDir/DirEntry.Type or os.Lstat) to detect symlink components before writing.

Useful? React with 👍 / 👎.

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