bugFix/TK-4065-handeled-invalid-urls#259
Conversation
📝 WalkthroughWalkthroughTwo 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
Estimated code review effort🎯 2 (Simple) | ⏱️ ~8 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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:
- Construct
baseURLand parse the URL- Find
routeConfigusingmatchPathsAndExtractParams- 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
📒 Files selected for processing (3)
src/app.jssrc/middlewares/routeConfigInjector.jssrc/middlewares/targetPackagesInjector.js
| 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' | ||
| }); | ||
| }); |
There was a problem hiding this comment.
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.
| 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.
VISHNUDAS-tunerlabs
left a comment
There was a problem hiding this comment.
Reviewed on 2 April
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/middlewares/routeConfigInjector.jssrc/utils/patternMatcher.js
✅ Files skipped from review due to trivial changes (1)
- src/middlewares/routeConfigInjector.js
| const removeTrailingSlash = (value) => { | ||
| if (typeof value !== 'string') return value | ||
| const normalizedValue = value.replace(/[^A-Za-z0-9._~-]+$/g, '') | ||
| return normalizedValue || '/' | ||
| } |
There was a problem hiding this comment.
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)).
Summary by CodeRabbit