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

feat(backend): improve path protection when writing file #128

Merged
merged 3 commits into from
Feb 26, 2025

Conversation

ZHallen122
Copy link
Collaborator

@ZHallen122 ZHallen122 commented Feb 24, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced file operation security with a unified validation process, ensuring robust handling of file actions.
  • Refactor

    • Streamlined file validation by consolidating multiple checks into one efficient routine for improved consistency.

@ZHallen122 ZHallen122 requested a review from Sma1lboy February 24, 2025 22:34
@ZHallen122 ZHallen122 marked this pull request as ready for review February 24, 2025 22:34
Copy link
Contributor

coderabbitai bot commented Feb 24, 2025

Walkthrough

This change refactors file path security validation in the backend. The previously used safetyChecks and isPathAllowed methods in the file operation manager have been removed. In their place, the new centralized function filePathSafetyChecks is now called in the methods handling file write, read, and rename operations, with an options object including projectRoot. A new utility file introduces the SecurityCheckOptions interface and implements the filePathSafetyChecks function to ensure file paths are safely validated against unauthorized access.

Changes

File(s) Change Summary
backend/.../FileOperationManager.ts Removed safetyChecks and isPathAllowed methods. Updated handleWrite, handleRead, and handleRename to build a securityOptions object and call filePathSafetyChecks.
backend/.../securityCheckUtil.ts Introduced new file with SecurityCheckOptions interface and filePathSafetyChecks function. Implements file path resolution and checks to prevent unauthorized access.

Sequence Diagram(s)

sequenceDiagram
    participant FOM as FileOperationManager
    participant FPS as filePathSafetyChecks
    participant FS as File System

    FOM->>FPS: Validate filePath with { projectRoot }
    alt Valid path
        FPS-->>FOM: Return success
        FOM->>FS: Execute file operation (write/read/rename)
    else Invalid path
        FPS-->>FOM: Throw error ("Unauthorized file access")
    end
Loading

Poem

I'm a clever rabbit, leaping with delight,
Hopping through code where security shines bright.
Safety checks are now one tune, unified and clear,
Guiding file paths safely, calming every fear.
With a hop and a skip, my code sings in the light!

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

backend/src/build-system/utils/security/path-check.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.

backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts

Oops! Something went wrong! :(

ESLint: 8.57.1

ESLint couldn't find the plugin "eslint-plugin-prettier".

(The package "eslint-plugin-prettier" was not found when loaded as a Node module from the directory "/backend".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

npm install eslint-plugin-prettier@latest --save-dev

The plugin "eslint-plugin-prettier" was referenced from the config file in "backend/.eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 54c77a1 and 5ba71d5.

📒 Files selected for processing (2)
  • backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts (4 hunks)
  • backend/src/build-system/utils/security/path-check.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts
🔇 Additional comments (5)
backend/src/build-system/utils/security/path-check.ts (5)

4-7: Well-defined interface for security options.

The interface clearly specifies the required and optional parameters for path security checks, providing good type safety.


9-16: Comprehensive JSDoc documentation.

The function documentation clearly describes the purpose, parameters, and potential errors, making it easy for other developers to understand and use.


23-28: Effective path traversal prevention.

The implementation correctly resolves paths and checks for path traversal attempts, throwing an appropriate error when unauthorized access is detected.


30-31: Implement the whitelist check.

The TODO comment indicates a whitelist check is planned but not implemented. This check would presumably use the allowedPaths parameter that's defined in the interface.

  // To do white list check
+  if (allowedPaths && allowedPaths.length > 0) {
+    const isAllowed = allowedPaths.some(allowedPath => {
+      const normalizedAllowedPath = path.normalize(allowedPath);
+      return targetPath.startsWith(normalizedAllowedPath);
+    });
+    
+    if (!isAllowed) {
+      throw new Error('File path not in allowed paths list');
+    }
+  }

17-31: Consider adding tests for the security check function.

This security function is critical for preventing unauthorized file access. Consider adding comprehensive unit tests that cover various edge cases, including different types of path traversal attempts and whitelist scenarios.

✨ 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: 5

🧹 Nitpick comments (2)
backend/src/build-system/utils/security/Path_protect.ts (1)

1-1: Rename file to follow TypeScript naming conventions.

The file name should use kebab-case instead of snake_case with underscores.

Rename Path_protect.ts to path-protect.ts.

backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts (1)

95-103: Add error handling for FilePathSafetyChecks.

The file operation methods should catch and handle errors from FilePathSafetyChecks separately from file operation errors.

Example for handleWrite (apply similar pattern to handleRead and handleRename):

   private async handleWrite(op: FileOperation): Promise<void> {
     const originalPath = path.resolve(this.projectRoot, op.originalPath);
     const securityOptions = { 
       projectRoot: this.projectRoot,
       allowedPaths: this.allowedPaths
     };
-    FilePathSafetyChecks(originalPath, securityOptions);
+    try {
+      FilePathSafetyChecks(originalPath, securityOptions);
+    } catch (error) {
+      this.logger.error(`Security check failed for ${op.originalPath}: ${error}`);
+      throw new Error(`Security violation: ${error.message}`);
+    }

     this.logger.debug('start update file to: ' + originalPath);
     const parseCode = removeCodeBlockFences(op.code);
     await writeFile(originalPath, parseCode, 'utf-8');
   }

Also applies to: 111-131, 138-150

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 13d0b76 and 2dea632.

📒 Files selected for processing (2)
  • backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts (4 hunks)
  • backend/src/build-system/utils/security/Path_protect.ts (1 hunks)

Comment on lines 4 to 7
export interface SecurityCheckOptions {
projectRoot: string;
allowedPaths?: string[];
}
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

Consider adding validation requirements to SecurityCheckOptions.

The interface should enforce that projectRoot is an absolute, normalized path and that allowedPaths contains valid paths.

 export interface SecurityCheckOptions {
-  projectRoot: string;
+  projectRoot: string & { __brand: 'AbsolutePath' }; // Type brand to ensure absolute path
   allowedPaths?: string[];
+  // Consider adding:
+  // allowSymlinks?: boolean; // Whether to follow symbolic links
+  // maxDepth?: number; // Maximum directory depth allowed
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export interface SecurityCheckOptions {
projectRoot: string;
allowedPaths?: string[];
}
export interface SecurityCheckOptions {
projectRoot: string & { __brand: 'AbsolutePath' }; // Type brand to ensure absolute path
allowedPaths?: string[];
// Consider adding:
// allowSymlinks?: boolean; // Whether to follow symbolic links
// maxDepth?: number; // Maximum directory depth allowed
}

Comment on lines 17 to 31
export function FilePathSafetyChecks(
filePath: string,
options: SecurityCheckOptions,
) {
const { projectRoot, allowedPaths } = options;

const targetPath = path.resolve(projectRoot, filePath);
const relativePath = path.relative(projectRoot, targetPath);
// Prevent path traversal attacks
if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
throw new Error('Unauthorized file access detected');
}

// To do white list check
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical security improvements needed in FilePathSafetyChecks.

Several security concerns need to be addressed:

  1. The whitelist check is incomplete (TODO comment)
  2. No validation of projectRoot
  3. No handling of symbolic links
  4. No sanitization of input paths

Apply this diff to enhance security:

 export function FilePathSafetyChecks(
   filePath: string,
   options: SecurityCheckOptions,
 ) {
   const { projectRoot, allowedPaths } = options;
+  
+  // Validate projectRoot
+  if (!path.isAbsolute(projectRoot)) {
+    throw new Error('Project root must be an absolute path');
+  }
+  
+  // Sanitize input path
+  const sanitizedPath = path.normalize(filePath).replace(/\0/g, '');
 
-  const targetPath = path.resolve(projectRoot, filePath);
+  const targetPath = path.resolve(projectRoot, sanitizedPath);
   const relativePath = path.relative(projectRoot, targetPath);
+  
   // Prevent path traversal attacks
   if (relativePath.startsWith('..') || path.isAbsolute(relativePath)) {
     throw new Error('Unauthorized file access detected');
   }
 
-  // To do white list check
+  // Implement whitelist check
+  if (allowedPaths?.length) {
+    const isAllowed = allowedPaths.some(allowedPath => {
+      const normalizedAllowedPath = path.normalize(allowedPath);
+      return relativePath.startsWith(normalizedAllowedPath);
+    });
+    if (!isAllowed) {
+      throw new Error('Path not in allowed paths list');
+    }
+  }
+  
+  // Handle symbolic links
+  try {
+    const realPath = await fs.realpath(targetPath);
+    const realRelativePath = path.relative(projectRoot, realPath);
+    if (realRelativePath.startsWith('..') || path.isAbsolute(realRelativePath)) {
+      throw new Error('Symbolic link points outside project root');
+    }
+  } catch (error) {
+    if (error.code !== 'ENOENT') {
+      throw new Error(`Failed to resolve symbolic link: ${error.message}`);
+    }
+  }
 }

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

Comment on lines 97 to 98
const securityOptions = { projectRoot: this.projectRoot };
FilePathSafetyChecks(originalPath, securityOptions);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Pass allowedPaths to security checks.

The security options object should include the allowedPaths array that's initialized in the constructor.

-    const securityOptions = { projectRoot: this.projectRoot };
+    const securityOptions = { 
+      projectRoot: this.projectRoot,
+      allowedPaths: this.allowedPaths
+    };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const securityOptions = { projectRoot: this.projectRoot };
FilePathSafetyChecks(originalPath, securityOptions);
const securityOptions = {
projectRoot: this.projectRoot,
allowedPaths: this.allowedPaths
};
FilePathSafetyChecks(originalPath, securityOptions);

Comment on lines 114 to 115
const securityOptions = { projectRoot: this.projectRoot };
FilePathSafetyChecks(originalPath, securityOptions);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Pass allowedPaths to security checks in handleRead.

Same issue as in handleWrite - the security options should include allowedPaths.

-      const securityOptions = { projectRoot: this.projectRoot };
+      const securityOptions = { 
+        projectRoot: this.projectRoot,
+        allowedPaths: this.allowedPaths
+      };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const securityOptions = { projectRoot: this.projectRoot };
FilePathSafetyChecks(originalPath, securityOptions);
const securityOptions = {
projectRoot: this.projectRoot,
allowedPaths: this.allowedPaths
};
FilePathSafetyChecks(originalPath, securityOptions);

Comment on lines 140 to 144
const RenamePath = path.resolve(this.projectRoot, op.renamePath);
const securityOptions = { projectRoot: this.projectRoot };

this.safetyChecks(originalPath);
this.safetyChecks(RenamePath);
FilePathSafetyChecks(originalPath, securityOptions);
FilePathSafetyChecks(RenamePath, securityOptions);
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

Fix variable naming and security options in handleRename.

Issues to address:

  1. Inconsistent variable naming (RenamePath vs renamePath)
  2. Security options missing allowedPaths
  3. Reusing same options object for both paths
-    const RenamePath = path.resolve(this.projectRoot, op.renamePath);
-    const securityOptions = { projectRoot: this.projectRoot };
+    const renamePath = path.resolve(this.projectRoot, op.renamePath);
+    const securityOptions = { 
+      projectRoot: this.projectRoot,
+      allowedPaths: this.allowedPaths
+    };

     FilePathSafetyChecks(originalPath, securityOptions);
-    FilePathSafetyChecks(RenamePath, securityOptions);
+    FilePathSafetyChecks(renamePath, securityOptions);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const RenamePath = path.resolve(this.projectRoot, op.renamePath);
const securityOptions = { projectRoot: this.projectRoot };
this.safetyChecks(originalPath);
this.safetyChecks(RenamePath);
FilePathSafetyChecks(originalPath, securityOptions);
FilePathSafetyChecks(RenamePath, securityOptions);
const renamePath = path.resolve(this.projectRoot, op.renamePath);
const securityOptions = {
projectRoot: this.projectRoot,
allowedPaths: this.allowedPaths
};
FilePathSafetyChecks(originalPath, securityOptions);
FilePathSafetyChecks(renamePath, securityOptions);

Copy link
Collaborator

@Sma1lboy Sma1lboy left a comment

Choose a reason for hiding this comment

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

Otherwise, LGTM

@Sma1lboy Sma1lboy changed the title improve Path protection feat(backend): improve path protection when writing file Feb 25, 2025
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

🔭 Outside diff range comments (1)
backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts (1)

149-149: ⚠️ Potential issue

Update variable name in rename function call.

Ensure you're using the renamed variable here as well.

-    await rename(originalPath, RenamePath);
+    await rename(originalPath, renamePath);
🧹 Nitpick comments (2)
backend/src/build-system/utils/security/path-check.ts (1)

17-20: Consider using camelCase for function name.

TypeScript/JavaScript conventions typically use camelCase for functions and PascalCase for classes/interfaces.

-export function FilePathSafetyChecks(
+export function filePathSafetyChecks(
  filePath: string,
  options: SecurityCheckOptions,
)
backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts (1)

146-148: Update variable name in debug logs.

For consistency, update the debug logs to use the same variable name.

     this.logger.debug('start rename: ' + originalPath);
-    this.logger.debug('change to name: ' + RenamePath);
+    this.logger.debug('change to name: ' + renamePath);
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2dea632 and 54c77a1.

📒 Files selected for processing (2)
  • backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts (4 hunks)
  • backend/src/build-system/utils/security/path-check.ts (1 hunks)
🔇 Additional comments (7)
backend/src/build-system/utils/security/path-check.ts (3)

4-7: Interface looks good!

The SecurityCheckOptions interface is well-defined with clear parameters for the security checks.


9-16: Well-documented function!

The JSDoc comments are thorough and clearly explain the purpose, parameters, and potential errors.


21-28: Security check implementation looks solid.

The path traversal protection logic is correctly implemented to prevent directory traversal attacks.

backend/src/build-system/handlers/frontend-code-generate/FileOperationManager.ts (4)

16-17: Import looks good!

The import statement for the new security utility function is correctly implemented.


97-98: Pass allowedPaths to security checks.

The security options object should include the allowedPaths array that's initialized in the constructor.

-    const securityOptions = { projectRoot: this.projectRoot };
+    const securityOptions = { 
+      projectRoot: this.projectRoot,
+      allowedPaths: this.allowedPaths
+    };

114-115: Pass allowedPaths to security checks in handleRead.

Same issue as in handleWrite - the security options should include allowedPaths.

-      const securityOptions = { projectRoot: this.projectRoot };
+      const securityOptions = { 
+        projectRoot: this.projectRoot,
+        allowedPaths: this.allowedPaths
+      };

139-144: Fix variable naming and security options in handleRename.

Issues to address:

  1. Inconsistent variable naming (RenamePath vs renamePath)
  2. Security options missing allowedPaths
  3. Reusing same options object for both paths
-    const RenamePath = path.resolve(this.projectRoot, op.renamePath);
-    const securityOptions = { projectRoot: this.projectRoot };
+    const renamePath = path.resolve(this.projectRoot, op.renamePath);
+    const securityOptions = { 
+      projectRoot: this.projectRoot,
+      allowedPaths: this.allowedPaths
+    };

     FilePathSafetyChecks(originalPath, securityOptions);
-    FilePathSafetyChecks(RenamePath, securityOptions);
+    FilePathSafetyChecks(renamePath, securityOptions);

@Sma1lboy Sma1lboy merged commit 21ae986 into main Feb 26, 2025
2 of 3 checks passed
Sma1lboy pushed a commit that referenced this pull request Feb 26, 2025
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

- **New Features**
- Enhanced file operation security with a unified validation process,
ensuring robust handling of file actions.

- **Refactor**
- Streamlined file validation by consolidating multiple checks into one
efficient routine for improved consistency.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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.

2 participants