Skip to content

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

Open
Prajwal17Tunerlabs wants to merge 2 commits intoELEVATE-Project:mainfrom
Prajwal17Tunerlabs:bugFix/TK-4065-handle-invalid-url
Open

bugFix/TK-4065-handeled-invalid-urls#259
Prajwal17Tunerlabs wants to merge 2 commits intoELEVATE-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

    • Global error handler now returns structured JSON with correct HTTP status codes.
    • Middlewares validate request URLs and short-circuit with a 400 error for invalid/malformed paths to prevent downstream failures.
  • New Features

    • Clearer, consistent error responses for invalid requests including an error code and message.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Apr 1, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7d33d8cc-d1d7-4c6c-9fc2-39cd41b9cea1

📥 Commits

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

📒 Files selected for processing (2)
  • src/middlewares/routeConfigInjector.js
  • src/middlewares/targetPackagesInjector.js
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/middlewares/targetPackagesInjector.js
  • src/middlewares/routeConfigInjector.js

📝 Walkthrough

Walkthrough

Adds URL-validation to two middlewares that short-circuit with a 400 INVALID_URL error when no route matches, and registers a global Express error handler that logs errors and responds with JSON { success: false, message }.

Changes

Cohort / File(s) Summary
Global Error Handler
src/app.js
Registers an Express error-handling middleware that logs errors, derives status from err.status/err.statusCode (fallback 500), and responds with JSON { success: false, message: ... }.
URL Validation Middlewares
src/middlewares/routeConfigInjector.js, src/middlewares/targetPackagesInjector.js
Each middleware now checks for a found routeConfig; when absent they create an Error with status = 400 and code = 'INVALID_URL' and call next(error) to stop normal processing.

Sequence Diagram

sequenceDiagram
    participant Client
    participant RouteConfigInjector as routeConfigInjector
    participant TargetPackagesInjector as targetPackagesInjector
    participant GlobalErrorHandler as errorHandler
    participant Response

    Client->>RouteConfigInjector: HTTP Request
    alt routeConfig found
        RouteConfigInjector->>TargetPackagesInjector: next()
        TargetPackagesInjector->>Response: normal handling -> response
    else no routeConfig
        RouteConfigInjector->>RouteConfigInjector: create Error(status:400, code:INVALID_URL)
        RouteConfigInjector->>errorHandler: next(error)
        errorHandler->>errorHandler: console.error(err)
        errorHandler->>Response: { success: false, message: err.message }
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through routes both near and far,
Found a gap where no pattern did spar.
I raise a small flag, four hundred and true,
Logged and returned, with a message for you.
Hooray for clear errors — a tidy new view! ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title closely matches the main objective: handling invalid URLs (TK-4065). It accurately reflects the primary changes across three files that add validation and error handling for invalid URL paths.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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