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

Fix computeEndpoint method #97

Merged
merged 4 commits into from
Nov 27, 2024
Merged

Fix computeEndpoint method #97

merged 4 commits into from
Nov 27, 2024

Conversation

shak58
Copy link
Contributor

@shak58 shak58 commented Nov 22, 2024

Summary

This pull request fixes an issue in the computeEndpoint method where if baseURL contains a path and endpoint does not start with a leading slash, it was forming URLs incorrectly.

Changes

  • computeEndpoint method modified: Checks that when baseURL has a path (e.g., /api) and endpoint lacks a leading slash (e.g., users), the resulting URL correctly includes a slash between them.

Test Results

Before Fix:

  • Base URL https://example.com/api and endpoint users resulted in https://example.com/apiusers .

After Fix:

  • Now correctly results in https://example.com/api/users .

Explanation

  • What the bug was: When baseURL and endpoint were being combined, if neither had appropriate slashes and the baseURL had a path, the concatenation would not contain a slash, making incorrect URLs.
  • How the fix works: Now, the computeEndpoint method will add a forward slash if necessary.

Tests

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced URL construction in the APIRequester to ensure correct handling of endpoints without leading slashes.
  • Tests

    • Introduced a new test case to validate the APIRequester’s behavior with a base URL and an endpoint lacking a leading slash.

Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

The changes in this pull request enhance the functionality and test coverage of the APIRequester class. A new test case has been added to verify the correct behavior when the endpoint is provided without a leading slash. Additionally, the computeEndpoint method has been modified to improve URL construction by normalizing the endpoint and ensuring the base URL ends with a slash, thereby preventing potential issues with URL formation.

Changes

File Path Change Summary
src/client/rest/APIRequester.spec.ts Added a test case to verify handling of endpoints without leading slashes in the APIRequester test suite.
src/client/rest/APIRequester.ts Modified the computeEndpoint method to improve URL construction by normalizing the endpoint and ensuring proper formatting.

Poem

In the land of code where rabbits play,
New tests hop in to brighten the day.
With endpoints trimmed and URLs neat,
Our API's ready, oh what a treat!
So let’s celebrate with a joyful cheer,
For every change brings us closer, my dear! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3dde973 and 07e873c.

📒 Files selected for processing (1)
  • src/client/rest/APIRequester.spec.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/client/rest/APIRequester.spec.ts

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

@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 and nitpick comments (4)
src/client/rest/APIRequester.spec.ts (1)

58-71: Enhance test coverage for URL handling

Consider adding more test cases to verify:

  1. Multiple path segments in baseURL (e.g., /api/v1/base)
  2. Multiple path segments in endpoint
  3. Trailing slashes in baseURL
  4. Query parameters in both baseURL and endpoint

Would you like me to help generate these additional test cases?

src/client/rest/APIRequester.ts (3)

55-63: LGTM! Consider adding error handling for invalid URLs.

The implementation correctly fixes the URL formation issue using the URL API. The approach of normalizing the endpoint and ensuring a trailing slash in the base path is robust.

Consider adding error handling for invalid base URLs:

 private computeEndpoint(endpoint: string) {
   const relativeEndpoint = endpoint.replace(/^\/+/, '');
-  const baseURLObject = new URL(this.baseURL);
+  try {
+    const baseURLObject = new URL(this.baseURL);
 
-    if (!baseURLObject.pathname.endsWith('/')) {
-      baseURLObject.pathname += '/';
-    }
-    baseURLObject.pathname += relativeEndpoint;
+    if (!baseURLObject.pathname.endsWith('/')) {
+      baseURLObject.pathname += '/';
+    }
+    baseURLObject.pathname += relativeEndpoint;
 
-    return baseURLObject.toString();
+    return baseURLObject.toString();
+  } catch (error) {
+    throw new Error(`Invalid base URL: ${this.baseURL}`);
+  }
 }
🧰 Tools
🪛 eslint (1.23.1)

[error] 55-55: Delete ;

(prettier/prettier)


[error] 56-56: Delete ;

(prettier/prettier)


[error] 59-59: Delete ;

(prettier/prettier)


[error] 61-61: Delete ;

(prettier/prettier)


[error] 63-63: Delete ;

(prettier/prettier)


55-63: Consider adding test cases for URL edge cases.

To ensure robust URL handling, consider adding test cases for:

  • Base URLs with query parameters
  • Base URLs with hash fragments
  • Endpoints with encoded characters
  • Invalid base URLs

Would you like me to help generate these test cases?

🧰 Tools
🪛 eslint (1.23.1)

[error] 55-55: Delete ;

(prettier/prettier)


[error] 56-56: Delete ;

(prettier/prettier)


[error] 59-59: Delete ;

(prettier/prettier)


[error] 61-61: Delete ;

(prettier/prettier)


[error] 63-63: Delete ;

(prettier/prettier)


55-63: Address formatting inconsistencies.

The static analysis tool indicates semicolon-related formatting issues. These should be automatically fixed by running the project's formatter.

Run your formatter to automatically fix these issues:

-    const relativeEndpoint = endpoint.replace(/^\/+/, '');
-    const baseURLObject = new URL(this.baseURL);
+    const relativeEndpoint = endpoint.replace(/^\/+/, '')
+    const baseURLObject = new URL(this.baseURL)

-    if (!baseURLObject.pathname.endsWith('/')) {
-      baseURLObject.pathname += '/';
+    if (!baseURLObject.pathname.endsWith('/')) {
+      baseURLObject.pathname += '/'
     }
-    baseURLObject.pathname += relativeEndpoint;
+    baseURLObject.pathname += relativeEndpoint

-    return baseURLObject.toString();
+    return baseURLObject.toString()
🧰 Tools
🪛 eslint (1.23.1)

[error] 55-55: Delete ;

(prettier/prettier)


[error] 56-56: Delete ;

(prettier/prettier)


[error] 59-59: Delete ;

(prettier/prettier)


[error] 61-61: Delete ;

(prettier/prettier)


[error] 63-63: Delete ;

(prettier/prettier)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 86d0d19 and 3dde973.

📒 Files selected for processing (2)
  • src/client/rest/APIRequester.spec.ts (1 hunks)
  • src/client/rest/APIRequester.ts (1 hunks)
🧰 Additional context used
🪛 eslint (1.23.1)
src/client/rest/APIRequester.ts

[error] 55-55: Delete ;

(prettier/prettier)


[error] 56-56: Delete ;

(prettier/prettier)


[error] 59-59: Delete ;

(prettier/prettier)


[error] 61-61: Delete ;

(prettier/prettier)


[error] 63-63: Delete ;

(prettier/prettier)

🔇 Additional comments (1)
src/client/rest/APIRequester.ts (1)

55-63: Verify security implications of URL manipulation.

Let's verify that the path traversal protection in validateEndpoint is comprehensive.

✅ Verification successful

URL validation is comprehensive and secure

The implementation provides robust protection against path traversal attacks through multiple layers:

  1. Explicit validation in validateEndpoint:

    • Blocks directory traversal attempts (../, ..\\)
    • Blocks URL-encoded traversal attempts (%2E%2E%2F, %2E%2E%5C)
    • Prevents query string injection
  2. Safe URL construction in computeEndpoint:

    • Strips leading slashes to prevent path manipulation
    • Uses URL constructor for proper URL parsing and encoding
    • Ensures consistent path separator handling

The combination of explicit blocklist validation and proper URL construction using the built-in URL API provides adequate protection against path traversal attacks.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential security issues in URL handling
# Test 1: Look for other URL manipulation methods that might need similar protection
rg -t typescript -t javascript "new URL\(" -A 5

# Test 2: Check for other path traversal protections in the codebase
rg -t typescript -t javascript "\.\./" -A 5

Length of output: 165


Script:

#!/bin/bash
# Let's try without file type filters since typescript is not recognized
# Check for URL manipulations and path traversal patterns

# Look for URL constructor usage
rg "new URL\(" -A 5

# Check for path traversal protections
rg "\.\./" -A 5

# Let's also check for validateEndpoint implementation
rg "validateEndpoint" -A 10

Length of output: 100261


Script:

#!/bin/bash
# Let's search for validateEndpoint implementation and its usage
ast-grep --pattern 'validateEndpoint($$$) {
  $$$
}'

# Also search for any URL validation related code
rg -l "validateEndpoint|URL|endpoint" src/client/rest/APIRequester.ts

Length of output: 158


Script:

#!/bin/bash
# Let's examine the full content of APIRequester.ts to understand the URL validation
cat src/client/rest/APIRequester.ts

Length of output: 2665

🧰 Tools
🪛 eslint (1.23.1)

[error] 55-55: Delete ;

(prettier/prettier)


[error] 56-56: Delete ;

(prettier/prettier)


[error] 59-59: Delete ;

(prettier/prettier)


[error] 61-61: Delete ;

(prettier/prettier)


[error] 63-63: Delete ;

(prettier/prettier)

src/client/rest/APIRequester.spec.ts Outdated Show resolved Hide resolved
Copy link
Collaborator

@joon9823 joon9823 left a comment

Choose a reason for hiding this comment

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

LGTM

@joon9823 joon9823 merged commit f247aee into initia-labs:main Nov 27, 2024
2 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.

2 participants