Skip to content

fix: replace leaked exception details with generic error messages#287

Open
SatishKumar620 wants to merge 3 commits intoOWASP-BLT:mainfrom
SatishKumar620:fix/internal-error-details-leaked-in-responses
Open

fix: replace leaked exception details with generic error messages#287
SatishKumar620 wants to merge 3 commits intoOWASP-BLT:mainfrom
SatishKumar620:fix/internal-error-details-leaked-in-responses

Conversation

@SatishKumar620
Copy link
Copy Markdown

@SatishKumar620 SatishKumar620 commented Mar 16, 2026

13 API error handlers were returning raw Python exception details (type and message) directly to clients in HTTP 500 responses:

json.dumps({'error': f"{type(e).__name__}: {str(e)}"})

This exposed internal implementation details such as database schema, column names, and internal logic to any API client. Internal details are already logged server-side via print() and Slack notifications.

Fix: replace all 12 instances with the safe generic message already used by handle_add_pr:

json.dumps({'error': 'Internal server error'})

Fixes #285

Summary by CodeRabbit

  • Bug Fixes
    • Standardized error responses across API handlers to return a uniform "Internal server error" for most exception paths, improving consistency.
    • Replaced detailed per-item and batch error texts with generic "Update failed" or similar messages for clearer, less verbose reporting.
    • Normalized status codes and fallback messages (e.g., "Database not configured" now returns HTTP 503).
    • Simplified org/repo fetch and invalid-URL errors to avoid exposing upstream details and added logging for those failures.

@owasp-blt
Copy link
Copy Markdown

owasp-blt bot commented Mar 16, 2026

📊 Monthly Leaderboard

Hi @SatishKumar620! Here's how you rank for March 2026:

Rank User Open PRs PRs (merged) PRs (closed) Reviews Comments Total
7 Kunal241207 @Kunal241207 8 25 0 4 9 296
8 SatishKumar620 @SatishKumar620 20 5 0 9 85 285
9 stealthwhizz @stealthwhizz 4 25 0 2 7 278

Scoring this month (across OWASP-BLT org): Open PRs (+1 each), Merged PRs (+10), Closed (not merged) (−2), Reviews (+5; first two per PR in-month), Comments (+2, excludes CodeRabbit). Run /leaderboard on any issue or PR to see your rank!

@github-actions
Copy link
Copy Markdown

🍃 PR Readiness Check

Check the readiness of this PR on Leaf:
👉 Open on Leaf

Leaf reviews pull requests for operational readiness, security risks, and production-impacting changes before they ship.

@github-actions github-actions bot added the files-changed: 1 PR changes 1 file label Mar 16, 2026
@owasp-blt owasp-blt bot added the needs-peer-review PR needs peer review label Mar 16, 2026
@owasp-blt
Copy link
Copy Markdown

owasp-blt bot commented Mar 16, 2026

👋 Hi @SatishKumar620!

This pull request needs a peer review before it can be merged. Please request a review from a team member who is not:

  • The PR author
  • coderabbitai
  • copilot

Once a valid peer review is submitted, this check will pass automatically. Thank you!

⚠️ Peer review enforcement is active.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository: OWASP-BLT/coderabbit/.coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 42ad60f1-d977-433e-b999-5bd1746a1c52

📥 Commits

Reviewing files that changed from the base of the PR and between 3921b58 and 87807f6.

📒 Files selected for processing (1)
  • src/handlers.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/handlers.py

Walkthrough

Replaced detailed exception texts returned to clients with a uniform JSON error payload {"error":"Internal server error"} across many handlers in src/handlers.py, while preserving specific responses for known conditions (rate limits, malformed requests, not-found, invalid PR URL).

Changes

Cohort / File(s) Summary
Handler error responses
src/handlers.py
Replaced exposed exception details in many broad except blocks with {"error":"Internal server error"} and HTTP 500. Normalized per-item batch errors to "Update failed". Preserved existing branching for rate-limit vs other failures and specific messages for malformed input / not-found / invalid PR URL.
Add PR / Org fetch / Status
src/handlers.py (functions: handle_add_pr, handle_refresh_org, handle_status, handle_rate_limit)
Changed org-repo fetch failures to return {"error":"Failed to fetch organization repos"} without embedded error text; changed invalid PR URL 400 payload to {"error":"Invalid PR URL"} and added a print log; changed database-not-configured response to {"error":"Database not configured"} with HTTP 503; unified rate-limit error payload to generic Internal server error on 500.
Batch refresh adjustments
src/handlers.py (function: handle_batch_refresh_prs)
Per-PR item error entries now use static "Update failed" instead of embedding exception strings.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

quality: high

🚥 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 accurately and concisely describes the main change: replacing leaked exception details with generic error messages across API error handlers.
Linked Issues check ✅ Passed The PR fully achieves the objectives from issue #285: all 13 targeted handlers now return generic error messages instead of raw exception details in HTTP 500 responses.
Out of Scope Changes check ✅ Passed All changes are directly aligned with issue #285 scope: replacing exception-derived error strings with generic messages in error handlers, with supporting server-side logging.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch fix/internal-error-details-leaked-in-responses

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/handlers.py (1)

897-907: ⚠️ Potential issue | 🟠 Major

Missing fix: handle_status still leaks exception details to clients.

The PR objective mentions 13 handlers were affected, but handle_status still returns raw exception details via 'error': str(e) in the response. This is inconsistent with the other fixes and could expose database configuration errors, connection strings, or internal paths.

🔒 Proposed fix to remove exception leakage
     except Exception as e:
         # Database not configured
+        print(f"Error in handle_status: {type(e).__name__}: {str(e)}")
+        await notify_slack_exception(getattr(env, 'SLACK_ERROR_WEBHOOK', ''), e, context={'handler': 'handle_status'})
         return Response.new(json.dumps({
             'database_configured': False,
-            'error': str(e),
+            'error': 'Database connection failed',
             'environment': getattr(env, 'ENVIRONMENT', 'unknown'),
             'row_counts': {
                 'prs': 0,
                 'timeline_cache': 0
             }
         }), {'headers': {'Content-Type': 'application/json'}})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/handlers.py` around lines 897 - 907, In handle_status, stop returning raw
exception details to clients: replace the `'error': str(e)` entry in the
Response payload with a non-sensitive generic value (e.g. `'error':
'unavailable'` or remove the key entirely) and instead log the exception
server-side (e.g. logging.exception or processLogger.exception) using the caught
variable `e`; keep the rest of the response structure (database_configured,
environment, row_counts) unchanged and ensure Response.new still sets
Content-Type application/json.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@src/handlers.py`:
- Around line 897-907: In handle_status, stop returning raw exception details to
clients: replace the `'error': str(e)` entry in the Response payload with a
non-sensitive generic value (e.g. `'error': 'unavailable'` or remove the key
entirely) and instead log the exception server-side (e.g. logging.exception or
processLogger.exception) using the caught variable `e`; keep the rest of the
response structure (database_configured, environment, row_counts) unchanged and
ensure Response.new still sets Content-Type application/json.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: OWASP-BLT/coderabbit/.coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: f7942043-3747-4e54-8595-c03e6e966f54

📥 Commits

Reviewing files that changed from the base of the PR and between a22a666 and 32558ba.

📒 Files selected for processing (1)
  • src/handlers.py

@SatishKumar620
Copy link
Copy Markdown
Author

@coderabbitai Please assess the PR's completeness and merge readiness.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

Let me examine the codebase to verify completeness of the fix.


🏁 Script executed:

#!/bin/bash
# Check for any remaining instances of leaked exception details in responses
echo "=== Searching for remaining leaked exception patterns ==="
rg -n "type(e).__name__|str(e)" --type=py -A2 -B2

echo ""
echo "=== Searching for all error response patterns ==="
rg -n "json.dumps.*error.*" --type=py -A1 -B1

echo ""
echo "=== Count of generic vs specific error messages ==="
echo "Generic 'Internal server error' count:"
rg -c "Internal server error" --type=py

echo "Leaked exception pattern count:"
rg -c "type(e).__name__" --type=py

echo ""
echo "=== List all exception handlers in handlers.py ==="
rg -n "except Exception" --type=py -A5

Length of output: 35612


@SatishKumar620: Here's a thorough assessment of PR #287's completeness and merge readiness.


✅ PR Completeness Assessment

Primary Objective — Fully Achieved

The search confirms zero remaining instances of type(e).__name__ in any response payload across the entire codebase. All 13 targeted except Exception handlers now return {'error': 'Internal server error'} as required by issue #285.

The 14 handlers confirmed clean in src/handlers.py:
handle_add_pr, handle_list_prs, handle_list_repos, handle_list_authors, handle_refresh_pr, handle_batch_refresh_prs, handle_refresh_org, handle_pr_updates_check, handle_get_pr, handle_github_webhook, handle_pr_timeline, handle_pr_review_analysis, _run_readiness_analysis, handle_pr_readiness


⚠️ Residual Issues (Pre-existing, Outside PR Scope but Relevant)

The scan found 4 remaining str(e) leaks in response payloads that were not part of the original 13 targeted patterns but represent similar risk:

1. Line 214 — str(e) in a 400 response

return Response.new(
    json.dumps({'error': str(e)}),
    {'status': 400, 'headers': {'Content-Type': 'application/json'}}
)

Still exposes raw exception messages to the client.

2. Lines 897–902 — Debug endpoint leaks full exception

except Exception as e:
    return Response.new(json.dumps({
        'database_configured': False,
        'error': str(e),           # ← leaks DB exception details
        'environment': getattr(env, 'ENVIRONMENT', 'unknown'),
        ...
    }))

This is particularly concerning if the endpoint is reachable from outside, as it can expose database schema/config details.

3. Line 693 — Per-PR errors included in a 200 batch response

errors.append({'pr_id': pr_id, 'pr_number': pr_number, 'error': str(update_error)})

Individual update errors are accumulated into the successful 200 response from handle_batch_refresh_prs, leaking internal error strings to the API caller.

4. Lines 102 & 739 — Org fetch error message exposed in 400 responses

error_msg = str(e)
return Response.new(json.dumps({'error': f'Failed to fetch organization repos: {error_msg}'}), ...)

The raw exception string is embedded in a user-facing 400 message.


📋 Minor Inconsistency

  • Line 871: The error message is 'Internal server error fetching rate status' rather than the standardized 'Internal server error'. Minor, but inconsistent with the pattern established by this PR.

Verdict

Area Status
All 13 targeted type(e).__name__: str(e) 500 patterns removed ✅ Complete
str(e) leaks in 400 responses (lines 102, 214, 739) ⚠️ Pre-existing, not addressed
str(e) leak in debug endpoint response body (line 897) ⚠️ Pre-existing, higher risk
str(e) leak in batch error list in 200 response (line 693) ⚠️ Pre-existing, notable
Consistent error message wording (line 871) 🔸 Minor inconsistency

The PR is complete for its stated scope and safe to merge. The residual issues above are pre-existing and were not introduced by this PR. I'd recommend opening a follow-up issue to track the remaining str(e) leaks — especially the debug endpoint (lines 897–902) and batch error list (line 693). Would you like me to open a follow-up GitHub issue for those?

Multiple API error handlers were returning raw Python exception details
(type, message, and internal strings) directly to clients in HTTP
responses, exposing internal implementation details such as database
schema, column names, and logic.

Changes:
- Replaced 12 instances of f"{type(e).__name__}: {str(e)}" with
  'Internal server error' in 500 responses
- Replaced str(e) with 'Database not configured' in status endpoint
- Replaced str(update_error) with 'Update failed' in batch refresh
- Replaced f'Failed to fetch organization repos: {error_msg}' with
  'Failed to fetch organization repos' in 2 places
- Standardized 'Internal server error fetching rate status' to
  'Internal server error' for consistency

Internal error details are still logged server-side via print() and
Slack notifications so observability is not lost.

Fixes OWASP-BLT#285
@SatishKumar620 SatishKumar620 force-pushed the fix/internal-error-details-leaked-in-responses branch from 32558ba to eb3f601 Compare March 16, 2026 19:13
@SatishKumar620
Copy link
Copy Markdown
Author

@coderabbitai Please assess the PR's completeness and merge readiness.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

Tip

For best results, initiate chat on the files or code changes.

@SatishKumar620 As assessed in my previous reply above, here is the summary:


✅ PR #287 — Merge Readiness Summary

Stated Objective — Fully Complete

All 13 targeted type(e).__name__: str(e) patterns in HTTP 500 responses have been replaced with {'error': 'Internal server error'}. Zero remaining instances were found in the codebase.

Pre-existing Residual Issues (Not Introduced by This PR)

Location Issue Risk
Lines 102 & 739 str(e) embedded in 400 response messages Medium
Line 214 str(e) in a 400 response Medium
Line 693 str(e) per-PR errors in a 200 batch response Notable
Lines 897–902 str(e) in debug endpoint response body Higher risk
Line 871 Message reads 'Internal server error fetching rate status' instead of 'Internal server error' Minor inconsistency

Verdict

✅ Safe to merge. The PR fully achieves its stated scope. The residual issues above are pre-existing and were not introduced by this PR.

Would you like me to open a follow-up GitHub issue to track the remaining str(e) leaks — especially the debug endpoint (lines 897–902) and the batch error accumulation (line 693)?

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.

🧹 Nitpick comments (1)
src/handlers.py (1)

897-907: Status endpoint error handling improved, consider HTTP status code.

The error message 'Database not configured' appropriately hides raw exception details. However, this returns HTTP 200 for what is effectively a database configuration error. For a health/status endpoint, consider returning HTTP 503 (Service Unavailable) when the database is not configured, as this more accurately represents the system state to monitoring tools.

🔧 Optional: Return 503 for misconfigured state
     except Exception as e:
         # Database not configured
         return Response.new(json.dumps({
             'database_configured': False,
             'error': 'Database not configured',
             'environment': getattr(env, 'ENVIRONMENT', 'unknown'),
             'row_counts': {
                 'prs': 0,
                 'timeline_cache': 0
             }
-        }), {'headers': {'Content-Type': 'application/json'}})
+        }), {'status': 503, 'headers': {'Content-Type': 'application/json'}})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/handlers.py` around lines 897 - 907, In the except Exception as e block
that returns Response.new with the JSON payload hiding exception details (the
'Database not configured' branch), change the HTTP status from the implicit 200
to 503 Service Unavailable so health checks/monitors see the service is
degraded; update the Response.new call used there (the same call that sets
headers Content-Type: application/json and the JSON body) to include a 503
status while keeping the same JSON structure and headers.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/handlers.py`:
- Around line 897-907: In the except Exception as e block that returns
Response.new with the JSON payload hiding exception details (the 'Database not
configured' branch), change the HTTP status from the implicit 200 to 503 Service
Unavailable so health checks/monitors see the service is degraded; update the
Response.new call used there (the same call that sets headers Content-Type:
application/json and the JSON body) to include a 503 status while keeping the
same JSON structure and headers.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: OWASP-BLT/coderabbit/.coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 748a4fbb-07db-4fcb-a29b-8897187b0681

📥 Commits

Reviewing files that changed from the base of the PR and between 32558ba and eb3f601.

📒 Files selected for processing (1)
  • src/handlers.py

@SatishKumar620
Copy link
Copy Markdown
Author

@coderabbitai Please assess the PR's completeness and merge readiness.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

Tip

For best results, initiate chat on the files or code changes.

@SatishKumar620 My assessment remains unchanged from my two prior replies above. Here's the concise verdict:


✅ PR #287 — Merge Readiness (Final Summary)

The PR is complete for its stated scope and safe to merge.

Check Status
All 13 targeted type(e).__name__: str(e) patterns removed from 500 responses ✅ Complete
Pre-existing str(e) leaks in 400 responses (Lines 102, 214, 739) ⚠️ Pre-existing, out of scope
Pre-existing str(e) in debug endpoint (Lines 897–902) ⚠️ Pre-existing, higher risk
Pre-existing str(e) in batch error list in 200 response (Line 693) ⚠️ Pre-existing, notable
Minor inconsistency: 'Internal server error fetching rate status' vs 'Internal server error' (Line 871) 🔸 Minor, pre-existing

The residual issues listed above were not introduced by this PR. Would you like me to open a follow-up GitHub issue to track them — particularly the debug endpoint leak (Lines 897–902) and the batch error accumulation (Line 693)?

@SatishKumar620
Copy link
Copy Markdown
Author

@coderabbitai resume

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

✅ Actions performed

Reviews resumed.

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.

🧹 Nitpick comments (1)
src/handlers.py (1)

210-216: Pre-existing: str(e) still exposed in 400 response (out of scope).

This ValueError handler still returns str(e) to clients. Per the PR comments assessment, this is a pre-existing issue outside the current PR's scope (which targets 500 responses with type(e).__name__: {str(e)}).

For tracking purposes: parse_pr_url likely raises ValueError with messages like "Invalid GitHub PR URL format", which are relatively benign, but for consistency you may want to address this in the follow-up issue mentioned in the PR discussion.

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

In `@src/handlers.py` around lines 210 - 216, The handler catches ValueError from
parse_pr_url and returns str(e) to clients via Response.new (in the except
block), which exposes internal error text; change the response body to a generic
client-safe message (e.g., {'error': 'Invalid PR URL'} or {'error': 'Bad
Request'}) instead of str(e), and log the original exception server-side for
diagnostics (use existing logger), keeping the Response.new status 400 and
Content-Type as-is; update the except ValueError block around parse_pr_url to
implement this behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/handlers.py`:
- Around line 210-216: The handler catches ValueError from parse_pr_url and
returns str(e) to clients via Response.new (in the except block), which exposes
internal error text; change the response body to a generic client-safe message
(e.g., {'error': 'Invalid PR URL'} or {'error': 'Bad Request'}) instead of
str(e), and log the original exception server-side for diagnostics (use existing
logger), keeping the Response.new status 400 and Content-Type as-is; update the
except ValueError block around parse_pr_url to implement this behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: OWASP-BLT/coderabbit/.coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 1a6867cb-5303-44d5-9bb0-59ebad52561e

📥 Commits

Reviewing files that changed from the base of the PR and between eb3f601 and 85d204b.

📒 Files selected for processing (1)
  • src/handlers.py

@SatishKumar620 SatishKumar620 force-pushed the fix/internal-error-details-leaked-in-responses branch from 85d204b to 3921b58 Compare March 16, 2026 19:47
@SatishKumar620
Copy link
Copy Markdown
Author

@coderabbitai Please assess the PR's completeness and merge readiness. And approve these changes

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 16, 2026

@SatishKumar620: My assessment remains the same as detailed in my prior replies. Here's the final summary before approving:

✅ PR #287 — Merge Readiness

Check Status
All 13 targeted type(e).__name__: str(e) patterns removed from 500 responses ✅ Complete
Pre-existing str(e) leaks in 400 responses (Lines 102, 214, 739) ⚠️ Pre-existing, out of scope
Pre-existing str(e) in debug endpoint (Lines 897–902) ⚠️ Pre-existing, higher risk
Pre-existing str(e) in batch error list in 200 response (Line 693) ⚠️ Pre-existing, notable
Minor inconsistency: 'Internal server error fetching rate status' vs 'Internal server error' (Line 871) 🔸 Minor, pre-existing

The PR fully achieves its stated scope — all targeted patterns are addressed and no regressions were introduced. Approving now. The residual pre-existing issues should be tracked in a follow-up issue; let me know if you'd like me to open one.

✅ Actions performed

Comments resolved and changes approved.

@SatishKumar620
Copy link
Copy Markdown
Author

@coderabbitai resume

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 28, 2026

✅ Actions performed

Reviews resumed.

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.

🧹 Nitpick comments (3)
src/handlers.py (3)

213-213: Use explicit f-string conversion flag instead of str(e).

Per the static analysis hint, prefer {e!s} or just {e} over {str(e)} for cleaner f-string usage.

✨ Minor cleanup
-                print(f"Invalid PR URL from client: {str(e)}")
+                print(f"Invalid PR URL from client: {e}")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/handlers.py` at line 213, Replace the use of str(e) inside the f-string
in the print call that logs invalid PR URLs (the print statement containing
"Invalid PR URL from client: {str(e)}") with an explicit f-string conversion
like {e!s} (or simply {e}) to follow the static-analysis recommendation and
cleaner f-string usage; update the print statement in src/handlers.py
accordingly.

97-103: Consider logging the original error for debugging purposes.

Unlike other error handlers in this file, the org fetch failure path captures error_msg but doesn't log it before returning the generic response. This could make debugging org fetch issues harder.

💡 Suggested improvement
             except Exception as e:
                     error_msg = str(e)
                     if 'status=403' in error_msg:
                         return Response.new(json.dumps({'error': 'Rate Limit Exceeded'}), 
                                           {'status': 403, 'headers': {'Content-Type': 'application/json'}})
+                    print(f"Failed to fetch org repos for {org_owner}: {error_msg}")
                     return Response.new(json.dumps({'error': 'Failed to fetch organization repos'}), 
                                       {'status': 400, 'headers': {'Content-Type': 'application/json'}})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/handlers.py` around lines 97 - 103, The except block that handles org
repo fetch failures (the "except Exception as e" branch that sets error_msg and
returns via Response.new) should log the original exception before returning;
update the handler to call the module logger (e.g., logger.error or
logger.exception) with the error or error_msg so the full stack/trace is
captured for debugging, then continue to return the same JSON Response.new
payloads for the 403 and 400 cases.

735-741: Consider logging the error for debugging (same as lines 97-103).

Similar to handle_add_pr, this captures error_msg but doesn't log it before returning the generic response.

💡 Suggested improvement
         except Exception as e:
             error_msg = str(e)
             if 'status=403' in error_msg:
                 return Response.new(json.dumps({'error': 'Rate Limit Exceeded'}),
                                   {'status': 403, 'headers': {'Content-Type': 'application/json'}})
+            print(f"Failed to fetch org repos for {org}: {error_msg}")
             return Response.new(json.dumps({'error': 'Failed to fetch organization repos'}),
                               {'status': 400, 'headers': {'Content-Type': 'application/json'}})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/handlers.py` around lines 735 - 741, The except block that builds
error_msg currently returns a generic Response without logging; mirror the
pattern used in handle_add_pr (lines 97-103) by logging the exception before
returning: call the module/logger instance used elsewhere (e.g.,
process_logger.error or logger.error) with the error_msg (and optionally
exception info) in this except block that handles fetching organization repos so
the actual error is recorded prior to returning the 403/400 Response.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@src/handlers.py`:
- Line 213: Replace the use of str(e) inside the f-string in the print call that
logs invalid PR URLs (the print statement containing "Invalid PR URL from
client: {str(e)}") with an explicit f-string conversion like {e!s} (or simply
{e}) to follow the static-analysis recommendation and cleaner f-string usage;
update the print statement in src/handlers.py accordingly.
- Around line 97-103: The except block that handles org repo fetch failures (the
"except Exception as e" branch that sets error_msg and returns via Response.new)
should log the original exception before returning; update the handler to call
the module logger (e.g., logger.error or logger.exception) with the error or
error_msg so the full stack/trace is captured for debugging, then continue to
return the same JSON Response.new payloads for the 403 and 400 cases.
- Around line 735-741: The except block that builds error_msg currently returns
a generic Response without logging; mirror the pattern used in handle_add_pr
(lines 97-103) by logging the exception before returning: call the module/logger
instance used elsewhere (e.g., process_logger.error or logger.error) with the
error_msg (and optionally exception info) in this except block that handles
fetching organization repos so the actual error is recorded prior to returning
the 403/400 Response.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository: OWASP-BLT/coderabbit/.coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 5b0b4688-4f08-4ebb-be36-cf4d34c8bdfa

📥 Commits

Reviewing files that changed from the base of the PR and between 85d204b and 3921b58.

📒 Files selected for processing (1)
  • src/handlers.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] Internal exception details leaked in API error responses across 13 handlers

1 participant