Skip to content

bugFix/TK-4065-handeled-invalid-urls#259

Open
Prajwal17Tunerlabs wants to merge 4 commits into
ELEVATE-Project:mainfrom
Prajwal17Tunerlabs:bugFix/TK-4065-handle-invalid-url
Open

bugFix/TK-4065-handeled-invalid-urls#259
Prajwal17Tunerlabs wants to merge 4 commits into
ELEVATE-Project:mainfrom
Prajwal17Tunerlabs:bugFix/TK-4065-handle-invalid-url

Conversation

@Prajwal17Tunerlabs
Copy link
Copy Markdown
Collaborator

@Prajwal17Tunerlabs Prajwal17Tunerlabs commented Apr 1, 2026

Summary by CodeRabbit

  • Bug Fixes
    • Improved URL pattern matching to normalize URLs and handle trailing slashes consistently, ensuring patterns match correctly across different URL formats.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 1, 2026

📝 Walkthrough

Walkthrough

Two middleware and utility adjustments enhance path handling and code formatting. A blank line improves spacing in the route config injector, while the pattern matcher adds URL normalization via a trailing slash removal helper to standardize pattern matching behavior.

Changes

Cohort / File(s) Summary
Middleware Formatting
src/middlewares/routeConfigInjector.js
Added blank line between routeConfig lookup and conditional block for improved code readability. No logic changes.
URL Normalization
src/utils/patternMatcher.js
Introduced removeTrailingSlash helper function to normalize URL input before pattern matching, affecting regex evaluation against standardized paths instead of raw URLs.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Poem

🐰 A slash trimmed away with care so fine,
Makes patterns match, in paths align,
With spacing neat, the code runs clean,
The tidiest injector ever seen!
hippity-hop through normalized ground! 🌿

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'bugFix/TK-4065-handeled-invalid-urls' is directly related to the main changes in the PR: handling invalid URLs through a normalization step in patternMatcher.js and a formatting change in routeConfigInjector.js.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

Copy link
Copy Markdown

@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 (1)
src/middlewares/targetPackagesInjector.js (1)

5-20: Consider extracting duplicated route validation logic.

The route lookup and error creation logic (lines 7-19) is nearly identical to routeConfigInjector.js (lines 6-18). Both middlewares:

  1. Construct baseURL and parse the URL
  2. Find routeConfig using matchPathsAndExtractParams
  3. Create the same error object when not found

Extracting this into a shared utility would reduce duplication and ensure consistent behavior.

♻️ Example shared utility
// src/utils/routeConfigLookup.js
const { routesConfigs } = require('@root/configs/routesConfigs')
const { matchPathsAndExtractParams } = require('@utils/patternMatcher')

exports.findRouteConfig = (req) => {
    const baseURL = req.protocol + '://' + req.headers.host + '/'
    const parsedUrl = new URL(req.originalUrl, baseURL)
    const urlWithoutQuery = parsedUrl.pathname
    return routesConfigs.routes.find((route) =>
        matchPathsAndExtractParams(route.sourceRoute, urlWithoutQuery)
    )
}

exports.createInvalidUrlError = () => {
    const error = new Error('Invalid URL')
    error.status = 400
    error.code = 'INVALID_URL'
    return error
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/middlewares/targetPackagesInjector.js` around lines 5 - 20, Extract the
duplicated route lookup and error creation into a shared utility (e.g.,
findRouteConfig and createInvalidUrlError) and replace the logic inside
targetPackagesInjector with calls to that utility; specifically, move the
baseURL/URL parsing + routesConfigs.routes.find(...) usage that uses
matchPathsAndExtractParams into findRouteConfig(req) and move the Error('Invalid
URL') with status/code into createInvalidUrlError(), then update
targetPackagesInjector to call findRouteConfig(req) to get routeConfig and, if
falsy, return next(createInvalidUrlError()); do the same refactor for
routeConfigInjector so both middlewares share the new utility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/app.js`:
- Around line 63-72: The global error handler (the app.use((err, req, res, next)
=> { ... }) block) currently returns err.message directly which may leak
internal info from library errors (see jsonBodyParserWithErrors.js); change the
handler to distinguish controlled/operational errors from unknown errors (e.g.,
check a flag like err.isOperational or a safeMessage property set by
jsonBodyParserWithErrors) and only return the original message for controlled
errors; for all other/untrusted errors return a generic message such as
"Internal Server Error" while still logging the full err (console.error or
processLogger) for diagnostics, and update jsonBodyParserWithErrors to mark
parse errors as controlled (set err.isOperational or err.safeMessage) if needed.

---

Nitpick comments:
In `@src/middlewares/targetPackagesInjector.js`:
- Around line 5-20: Extract the duplicated route lookup and error creation into
a shared utility (e.g., findRouteConfig and createInvalidUrlError) and replace
the logic inside targetPackagesInjector with calls to that utility;
specifically, move the baseURL/URL parsing + routesConfigs.routes.find(...)
usage that uses matchPathsAndExtractParams into findRouteConfig(req) and move
the Error('Invalid URL') with status/code into createInvalidUrlError(), then
update targetPackagesInjector to call findRouteConfig(req) to get routeConfig
and, if falsy, return next(createInvalidUrlError()); do the same refactor for
routeConfigInjector so both middlewares share the new utility.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c87c7cbc-4df3-4605-877c-0e66fd3a3c61

📥 Commits

Reviewing files that changed from the base of the PR and between 8624ee6 and d095b7a.

📒 Files selected for processing (3)
  • src/app.js
  • src/middlewares/routeConfigInjector.js
  • src/middlewares/targetPackagesInjector.js

Comment thread src/app.js Outdated
Comment on lines +63 to +72
app.use((err, req, res, next) => {
console.error('Global Error Handler:', err);

const status = err.status || err.statusCode || 500;

res.status(status).json({
success: false,
message: err.message || 'Internal Server Error'
});
});
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Potential information disclosure via err.message for uncontrolled errors.

While this handler works well for controlled errors like 'Invalid URL', it exposes err.message directly in the response. From src/middlewares/jsonBodyParserWithErrors.js (lines 8-12), non-JSON parsing errors are passed through next(err) and will reach this handler. Body-parser and other library errors can contain internal details (stack traces, file paths, or implementation specifics) that should not be exposed to clients.

Consider sanitizing the message for non-controlled errors:

🛡️ Proposed fix to prevent information leakage
         app.use((err, req, res, next) => {
             console.error('Global Error Handler:', err);

             const status = err.status || err.statusCode || 500;
+            
+            // Only expose message for known/controlled errors
+            const safeMessage = err.code === 'INVALID_URL' 
+                ? err.message 
+                : (status < 500 ? err.message : 'Internal Server Error');

             res.status(status).json({
                 success: false,
-                message: err.message || 'Internal Server Error'
+                message: safeMessage
             });
         });
📝 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
app.use((err, req, res, next) => {
console.error('Global Error Handler:', err);
const status = err.status || err.statusCode || 500;
res.status(status).json({
success: false,
message: err.message || 'Internal Server Error'
});
});
app.use((err, req, res, next) => {
console.error('Global Error Handler:', err);
const status = err.status || err.statusCode || 500;
// Only expose message for known/controlled errors
const safeMessage = err.code === 'INVALID_URL'
? err.message
: (status < 500 ? err.message : 'Internal Server Error');
res.status(status).json({
success: false,
message: safeMessage
});
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/app.js` around lines 63 - 72, The global error handler (the app.use((err,
req, res, next) => { ... }) block) currently returns err.message directly which
may leak internal info from library errors (see jsonBodyParserWithErrors.js);
change the handler to distinguish controlled/operational errors from unknown
errors (e.g., check a flag like err.isOperational or a safeMessage property set
by jsonBodyParserWithErrors) and only return the original message for controlled
errors; for all other/untrusted errors return a generic message such as
"Internal Server Error" while still logging the full err (console.error or
processLogger) for diagnostics, and update jsonBodyParserWithErrors to mark
parse errors as controlled (set err.isOperational or err.safeMessage) if needed.

Copy link
Copy Markdown
Collaborator

@VISHNUDAS-tunerlabs VISHNUDAS-tunerlabs left a comment

Choose a reason for hiding this comment

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

Reviewed on 2 April

Comment thread src/middlewares/routeConfigInjector.js Outdated
Copy link
Copy Markdown

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/utils/patternMatcher.js`:
- Around line 3-7: The helper removeTrailingSlash currently strips any trailing
non-[A-Za-z0-9._~-] chars; change it to only remove trailing slashes by using
value.replace(/\/+$/,'') and keep the fallback to '/' when result is empty; also
ensure you call this normalization on both the incoming pattern and the url
before you build the RegExp (i.e., normalize the variable named pattern the same
way you normalize url where the regex is constructed) so middleware lookup uses
the same route form as router registration (update all call sites that build the
regex from the raw pattern to use removeTrailingSlash(pattern)).
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 32fd76e5-fe1a-43b3-a49f-4333da0e20fe

📥 Commits

Reviewing files that changed from the base of the PR and between be5b438 and a731df3.

📒 Files selected for processing (2)
  • src/middlewares/routeConfigInjector.js
  • src/utils/patternMatcher.js
✅ Files skipped from review due to trivial changes (1)
  • src/middlewares/routeConfigInjector.js

Comment on lines +3 to +7
const removeTrailingSlash = (value) => {
if (typeof value !== 'string') return value
const normalizedValue = value.replace(/[^A-Za-z0-9._~-]+$/g, '')
return normalizedValue || '/'
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Normalize pattern and url consistently, and only strip trailing slashes.

At Line 10 only url is normalized, while Line 13 still builds regex from raw pattern. This can miss matches when a configured sourceRoute ends with / (middleware lookup fails even though router registration still uses sourceRoute). Also, Line 5 currently removes any trailing non-[A-Za-z0-9._~-] chars, not just /, which can alter valid path semantics.

Proposed fix
 const removeTrailingSlash = (value) => {
-	if (typeof value !== 'string') return value
-	const normalizedValue = value.replace(/[^A-Za-z0-9._~-]+$/g, '')
+	if (typeof value !== 'string') return '/'
+	const normalizedValue = value.replace(/\/+$/g, '')
 	return normalizedValue || '/'
 }

 exports.matchPathsAndExtractParams = (pattern, url) => {
+	const normalizedPattern = removeTrailingSlash(pattern)
 	const normalizedUrl = removeTrailingSlash(url)
 	const paramNames = []
 	const regexPattern = new RegExp(
-		pattern.replace(/\/:(\w+)/g, (_, paramName) => {
+		normalizedPattern.replace(/\/:(\w+)/g, (_, paramName) => {
 			paramNames.push(paramName)
 			return '/([^/]+)'
 		}) + '$'
 	)
 	const matchResult = normalizedUrl.match(regexPattern)

Also applies to: 10-10, 18-18

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/utils/patternMatcher.js` around lines 3 - 7, The helper
removeTrailingSlash currently strips any trailing non-[A-Za-z0-9._~-] chars;
change it to only remove trailing slashes by using value.replace(/\/+$/,'') and
keep the fallback to '/' when result is empty; also ensure you call this
normalization on both the incoming pattern and the url before you build the
RegExp (i.e., normalize the variable named pattern the same way you normalize
url where the regex is constructed) so middleware lookup uses the same route
form as router registration (update all call sites that build the regex from the
raw pattern to use removeTrailingSlash(pattern)).

@Prajwal17Tunerlabs Prajwal17Tunerlabs changed the base branch from main to develop April 28, 2026 11:19
@Prajwal17Tunerlabs Prajwal17Tunerlabs changed the base branch from develop to main April 28, 2026 11:20
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