Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: enhance clip name sanitization and path handling in media handler #408

Merged
merged 2 commits into from
Jan 24, 2025

Conversation

tphakala
Copy link
Owner

  • Improved the sanitizeClipName function to handle path traversal attempts more robustly, including case-insensitive checks for Windows compatibility.
  • Added normalization of path separators and ensured the removal of the 'clips/' prefix is case-insensitive.
  • Enhanced the getFullPath and getSpectrogramPath functions for consistent path handling and validation.
  • Implemented checks for final path length to prevent exceeding system limits.
  • Added detailed debug logging for better traceability during path sanitization and file existence checks.

…andler

- Improved the `sanitizeClipName` function to handle path traversal attempts more robustly, including case-insensitive checks for Windows compatibility.
- Added normalization of path separators and ensured the removal of the 'clips/' prefix is case-insensitive.
- Enhanced the `getFullPath` and `getSpectrogramPath` functions for consistent path handling and validation.
- Implemented checks for final path length to prevent exceeding system limits.
- Added detailed debug logging for better traceability during path sanitization and file existence checks.
Copy link
Contributor

coderabbitai bot commented Jan 24, 2025

Walkthrough

The pull request enhances the security and robustness of media file handling in the internal/httpcontroller/handlers/media.go file. Key modifications include improvements to the sanitizeClipName function, which now incorporates additional checks against path traversal vulnerabilities. It also normalizes slashes and enforces a maximum path length of 250 characters. The handling of the 'clips/' prefix has been updated to be case-insensitive for Windows compatibility. Additionally, the ServeSpectrogram method now includes enhanced logging and checks for file existence.

Changes

File Change Summary
internal/httpcontroller/handlers/media.go - Enhanced sanitizeClipName function with improved path sanitization
- Updated path traversal prevention logic
- Added case-insensitive handling for 'clips/' prefix
- Implemented path length validation (max 250 characters)
- Refined getFullPath and getSpectrogramPath methods
- Improved error handling and debug logging

Possibly related PRs

Poem

🐰 A Rabbit's Path Security Ballad 🔒

Slashes forward, backslashes beware,
No traversal tricks shall slip past here!
Paths are cleaned with diligent care,
Windows or Unix, we're beyond compare.
Security hops with each file we share! 🚀

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@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 (8)
internal/httpcontroller/handlers/media.go (8)

64-67: Consider using a consolidated approach for normalizing path separators.
For instance, filepath.ToSlash() automatically converts all path separators to forward slashes, and repeated slashes can be collapsed in a single pass rather than performing multiple string replacements.

- cleanPath = strings.ReplaceAll(cleanPath, "\\", "/")
- cleanPath = strings.ReplaceAll(cleanPath, "//", "/")
+ cleanPath = filepath.ToSlash(cleanPath)
+ // Optionally handle multiple slashes if needed:
+ for strings.Contains(cleanPath, "//") {
+     cleanPath = strings.ReplaceAll(cleanPath, "//", "/")
+ }

76-80: Ensure ‘clips/’ removal only applies at path start.
If a path has “clips/” in the middle, it might be unintentionally removed. Currently, the code checks only the prefix, which is good, but be mindful of partial matches. This seems fine for your use case, just clarifying the behavior.


109-113: Confirm the chosen path length limit.
The limit of 250 might suffice on most systems, but some Windows setups allow 260 or even longer with extended paths. Consider making this configurable if needed.


131-134: Consider validating boundaries for the export path check here as well.
In the event that relativePath has a partial match, you may inadvertently treat it as starting with the export path.


210-214: Be mindful of logging PII or internal paths.
While these logs are helpful for debugging, ensure they don’t expose sensitive data in production logs.


248-262: Potential concurrency issues.
Multiple requests for the same spectrogram might cause duplicate generation attempts. You could handle concurrency with locks or a “spectrogram in-progress” marker.


277-284: Extra sanitization in getSpectrogramPath could unify with sanitizeClipName.
While this separate approach is valid, reusing the same sanitize logic can centralize path security checks.


285-294: Validate actual subdirectory membership for the base directory.
Similar to earlier checks, confirm that the path definitely resides under exportPath.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b60845e and 5092b32.

📒 Files selected for processing (1)
  • internal/httpcontroller/handlers/media.go (4 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (14)
internal/httpcontroller/handlers/media.go (14)

100-105: Apply similar boundary checks for non-Windows systems.
Ensure strings.HasPrefix(cleanPath, exportPath) is validated with a slash boundary to avoid matching siblings.


125-126: Good practice: cleaning the relative path proactively.
This step helps remove any unexpected ./ or ../ segments.


137-138: Joining and cleaning the final path is correct.
This ensures the resulting path is canonical and helps avoid path traversal pitfalls.


219-222: Error logging is appropriate.
It provides visibility into sanitization failures, aiding in debugging.


224-227: Full path debug log might be sensitive.
Consider your logging level or whether to redact part of the path if necessary in production.


229-238: Properly handling missing audio files.
Returning a placeholder image is a neat fallback.


264-271: Verifying spectrogram creation post-attempt is sensible.
This final check reduces confusion if generation silently fails.


296-299: Use of filepath.Dir is appropriate.
These lines correctly derive the directory path.


301-302: Debug lines look fine.
They won’t affect production flow.


304-304: Spectrogram path computation is straightforward and clean.
Ensures consistent naming.

Also applies to: 306-308


311-320: Checking for existing spectrogram is good for performance.
Avoids regenerating spectrograms unnecessarily.


323-332: Ensuring the source audio file’s existence is crucial.
Graceful failure here helps avoid wasted processing.


334-334: Return statement looks correct.
Nothing else to address here.


89-98: Validate in Windows mode that the path boundary is respected.
Using strings.HasPrefix(cleanPathLower, exportPathLower) might incorrectly match if exportPath is “C:\export” and cleanPath is “C:\exportxyz”. Consider ensuring a trailing slash boundary when checking.

 if strings.HasPrefix(cleanPathLower, exportPathLower) {
     cleanPath = cleanPath[len(exportPath):]
     cleanPath = strings.TrimPrefix(cleanPath, string(os.PathSeparator))
 } else {
     return "", fmt.Errorf("invalid path: absolute path not under export directory")
 }
+// Optionally confirm boundary:
+if len(cleanPathLower) > len(exportPathLower) {
+    nextChar := cleanPathLower[len(exportPathLower)]
+    if nextChar != '/' && nextChar != '\\' {
+        return "", fmt.Errorf("invalid path: not a proper subdirectory")
+    }
+}

Comment on lines 70 to 71
// Check for path traversal attempts
if strings.Contains(cleanPath, "../") || strings.Contains(cleanPath, "..\\") {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Strengthen path traversal detection.
Relying solely on checking for '../' or '..\\' can be bypassed if encoded differently or if path segments are re-encoded. Consider comparing the absolute cleaned path against the base export directory to confirm it’s a valid subpath.

 if strings.Contains(cleanPath, "../") || strings.Contains(cleanPath, "..\\") {
   h.Debug("sanitizeClipName: Path traversal attempt detected: %s", cleanPath)
   return "", ErrPathTraversal
 }
+// Alternative approach
+absPath, err := filepath.Abs(filepath.Join(conf.Setting().Realtime.Audio.Export.Path, cleanPath))
+if err != nil {
+    return "", err
+}
+exportAbs, _ := filepath.Abs(conf.Setting().Realtime.Audio.Export.Path)
+if !strings.HasPrefix(absPath, exportAbs) {
+    return "", ErrPathTraversal
+}

Committable suggestion skipped: line range outside the PR's diff.

- Improved the `sanitizeClipName` function to include absolute path resolution for better security against path traversal attacks.
- Added checks to ensure the resolved path remains within the designated export directory.
- Enhanced debug logging for clearer traceability of path sanitization processes.
Copy link
Contributor

@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: 0

🧹 Nitpick comments (1)
internal/httpcontroller/handlers/media.go (1)

124-127: Consider making the path length limit configurable.

The hard-coded path length limit of 250 characters could be made configurable to accommodate different system requirements.

 // MaxClipNameLength is the maximum allowed length for a clip name
 const MaxClipNameLength = 255
+// MaxPathLength is the maximum allowed length for the full file path
+const MaxPathLength = 250
 
 // AllowedCharacters is a regex pattern for allowed characters in clip names
 const AllowedCharacters = `^[a-zA-Z0-9_/.-]+$`

 // In the sanitizeClipName function:
-	if len(fullPath) > 250 { // Safe limit for most OS
+	if len(fullPath) > MaxPathLength {
 		return "", fmt.Errorf("final path length exceeds system limits")
 	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5092b32 and a81b132.

📒 Files selected for processing (1)
  • internal/httpcontroller/handlers/media.go (4 hunks)
🔇 Additional comments (5)
internal/httpcontroller/handlers/media.go (5)

64-89: LGTM! Robust path traversal prevention implemented.

The implementation correctly resolves and compares absolute paths to prevent path traversal attacks.


90-94: LGTM! Case-insensitive prefix handling added.

The implementation properly handles the 'clips/' prefix removal with case-insensitivity for better cross-platform compatibility.


139-152: LGTM! Improved path handling with proper sanitization.

The function now properly handles paths by:

  • Cleaning paths before processing
  • Using case-insensitive comparison for Windows compatibility
  • Correctly handling paths that already include the export path

291-348: LGTM! Robust path handling and validation in getSpectrogramPath.

The function implementation includes:

  • Proper path cleaning and normalization
  • Case-insensitive path comparison
  • Comprehensive debug logging
  • Thorough existence checks for both audio and spectrogram files

224-287: Consider atomic file operations to prevent race conditions.

The file existence checks and subsequent operations are not atomic, which could lead to race conditions in a concurrent environment. Consider using atomic operations or file locks where possible.

@tphakala tphakala merged commit 82217cf into main Jan 24, 2025
14 checks passed
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