Skip to content

fix(auth): return 405 Method Not Allowed instead of 404 for wrong HTTP methods#38

Open
ojaswa072 wants to merge 6 commits intoOWASP-BLT:mainfrom
ojaswa072:fix/auth-method-not-allowed-status-code
Open

fix(auth): return 405 Method Not Allowed instead of 404 for wrong HTTP methods#38
ojaswa072 wants to merge 6 commits intoOWASP-BLT:mainfrom
ojaswa072:fix/auth-method-not-allowed-status-code

Conversation

@ojaswa072
Copy link
Copy Markdown
Contributor

@ojaswa072 ojaswa072 commented Mar 7, 2026

Summary

Fixes auth endpoint method handling so unsupported methods return 405 Method Not Allowed (with Allow) instead of 404, and adds focused regression tests.

Problem

Auth endpoints returned 404 Not Found for non-allowed methods, which is semantically incorrect and inconsistent with HTTP method handling.

Fix

  • Ensured wrong-method requests return 405 Method Not Allowed with Allow header.
  • Kept early method validation flow for auth handlers.
  • Added dedicated tests to verify early method-guard behavior:
    • handle_signup returns 405 before DB setup.
    • handle_signin returns 405 before JWT checks.
    • handle_verify_email returns 405 before DB/JWT setup.
  • Resolved merge conflicts with upstream while preserving the above behavior.

Files Changed

  • auth.py — auth method-guard flow updates
  • test_auth.py — focused regression tests
  • utils.py — conflict-resolution docstring formatting alignment

Testing

  • Ran: test_auth.py
  • Result: 3 passed
  • Verified wrong-method requests return 405 with correct Allow header and fail fast before deeper setup

@owasp-blt
Copy link
Copy Markdown

owasp-blt bot commented Mar 7, 2026

👋 Thanks for opening this pull request, @ojaswa072!

Before your PR is reviewed, please ensure:

  • Your code follows the project's coding style and guidelines.
  • You have written or updated tests for your changes.
  • The commit messages are clear and descriptive.
  • You have linked any relevant issues (e.g., Closes #123).

🔍 Our team will review your PR shortly. If you have questions, feel free to ask in the comments.

🚀 Keep up the great work! — OWASP BLT

@owasp-blt
Copy link
Copy Markdown

owasp-blt bot commented Mar 7, 2026

📊 Monthly Leaderboard

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

Rank User Open PRs PRs (merged) PRs (closed) Reviews Comments Total
🥇 #1 @Nachiket-Roy 8 44 13 5 4 455
🥈 #2 @ojaswa072 9 29 0 0 1 301
#3 @Kunal241207 4 24 0 1 3 255

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!

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 7, 2026

Walkthrough

Auth handlers now validate HTTP method early (returning 405 + Allow) and reorder secret/DB access to occur after method checks where applicable; src/utils.py docstring whitespace adjusted; new async tests assert method-guard behavior and that DB/JWT paths are not reached on wrong methods.

Changes

Cohort / File(s) Summary
Auth handlers
src/handlers/auth.py
Moved HTTP-method validation earlier in handle_signup, handle_signin, and handle_verify_email so disallowed methods return 405 with an Allow header before reading JWT secret or opening DB connections; minor string whitespace normalization in one error message.
Utilities (docstring)
src/utils.py
Adjusted error_response docstring whitespace/formatting only; function signature and behavior unchanged.
Tests (new)
tests/test_auth.py
Added async tests that call auth handlers with wrong HTTP methods and assert handlers return 405 and correct Allow header; monkeypatches ensure DB/JWT code paths are not executed on wrong-method cases.

Sequence Diagram(s)

sequenceDiagram
    participant Client as Client
    participant Handler as AuthHandler
    participant JWT as JWT (env.JWT_SECRET)
    participant DB as Database

    Client->>Handler: HTTP request (method + payload)
    Handler->>Handler: validate HTTP method
    alt method not allowed
        Handler-->>Client: 405 Method Not Allowed\nHeader: Allow
    else method allowed
        Handler->>JWT: read/validate JWT secret (if required)
        JWT-->>Handler: secret present / error
        Handler->>DB: get_db_safe / queries (if required)
        DB-->>Handler: data / error
        Handler-->>Client: 200 / appropriate response or error
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

quality: medium

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: returning 405 Method Not Allowed instead of 404 for incorrect HTTP methods in auth handlers, which is the core objective reflected in the code changes across auth.py and the new tests.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

Caution

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

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

159-164: ⚠️ Potential issue | 🟠 Major

Move the method guard ahead of JWT/DB setup.

handle_signin and handle_verify_email still do config/DB work before rejecting unsupported verbs. If JWT_SECRET is missing or the DB is unavailable, a wrong-method request can still return 500 instead of 405, so this PR does not fully guarantee the behavior it intends to fix.

💡 Suggested change
 async def handle_signin(request: Any, env: Any, path_params: Dict[str, str], query_params: Dict[str, str], path: str) -> Any:
     logger = logging.getLogger(__name__)
     try:
+        method = str(request.method).upper()
+        if method != "POST":
+            return error_response("Method Not Allowed", 405)
+
         jwt_secret = env.JWT_SECRET
         if not jwt_secret:
             return error_response("JWT secret not configured, please configure it using `wrangler secret put JWT_SECRET`", 500)
-        method = str(request.method).upper()
-        if method != "POST":
-            return error_response("Method Not Allowed", 405)
         body = await parse_json_body(request)

 async def handle_verify_email(request: Any, env: Any, path_params: Dict[str, str], query_params: Dict[str, str], path: str) -> Any:
     logger = logging.getLogger(__name__)   
     try:
-        db= await  get_db_safe(env)
-        jwt_secret = env.JWT_SECRET
+        method = str(request.method).upper()
+        if method != "GET":
+            return error_response("Method Not Allowed", 405)
+
+        db = await get_db_safe(env)
+        jwt_secret = env.JWT_SECRET

         if not jwt_secret:
             return error_response("JWT secret not configured, please configure it using `wrangler secret put JWT_SECRET`", 500)
-
-        method = str(request.method).upper()
-        if method != "GET":
-            return error_response("Method Not Allowed", 405)

Also applies to: 231-240

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

In `@src/handlers/auth.py` around lines 159 - 164, The method guard must run
before any config/DB initialization in handlers so wrong-method requests return
405 not 500; move the HTTP verb checks to the top of handle_signin and
handle_verify_email (and the other handler block referenced around lines
231-240) so that the method is validated before reading env.JWT_SECRET or
opening DB connections, i.e., check request.method and return
error_response("Method Not Allowed", 405) immediately in each handler before
accessing jwt_secret, DB clients, or other setup.
🤖 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/handlers/auth.py`:
- Around line 71-72: The 405 responses created by the handlers use
error_response(...) without an Allow header; update each handler to return a 405
with the appropriate Allow header by passing headers={"Allow": "<METHOD>"}
through the response helper. Specifically, in the signup handler (where it
currently checks if method != "POST"), change the error return to include
headers={"Allow":"POST"}; do the same in the signin handler (use "POST") and in
the verify_email handler (use "GET"). Use the json_response-compatible headers
parameter (i.e., have error_response forward headers to json_response) or add
the headers at each call site so the returned response includes Allow.

---

Outside diff comments:
In `@src/handlers/auth.py`:
- Around line 159-164: The method guard must run before any config/DB
initialization in handlers so wrong-method requests return 405 not 500; move the
HTTP verb checks to the top of handle_signin and handle_verify_email (and the
other handler block referenced around lines 231-240) so that the method is
validated before reading env.JWT_SECRET or opening DB connections, i.e., check
request.method and return error_response("Method Not Allowed", 405) immediately
in each handler before accessing jwt_secret, DB clients, or other setup.

ℹ️ Review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Pro

Run ID: 3f0f0bf4-b243-4cef-9a61-28012d65ca3c

📥 Commits

Reviewing files that changed from the base of the PR and between efc926c and 54ef9ca.

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

Comment thread src/handlers/auth.py Outdated
@ojaswa072
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 7, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@owasp-blt owasp-blt bot added the needs-peer-review PR needs peer review label Mar 14, 2026
@owasp-blt
Copy link
Copy Markdown

owasp-blt bot commented Mar 14, 2026

👋 Hi @ojaswa072!

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.

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 (2)
tests/test_auth.py (2)

10-13: Remove duplicate sys.path setup; rely on shared conftest.py configuration.

tests/conftest.py already inserts src into sys.path (line 10). Adding it again here is redundant. Additionally, inserting handlers_path with insert(0, ...) elevates it above src, which can shadow imports and make resolution fragile.

Instead, import auth directly after ensuring conftest.py is loaded. If handlers/auth.py requires special module stubs (like workers), add those stubs to conftest.py or a shared fixture rather than per-test-file imports.

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

In `@tests/test_auth.py` around lines 10 - 13, Remove the duplicate sys.path
manipulation in tests/test_auth.py: delete the sys.path.insert calls that add
src_path and handlers_path, and instead rely on tests/conftest.py to set up
sys.path; then import the auth module directly (e.g., from handlers import auth
or import auth) in tests/test_auth.py. If handlers/auth.py needs module stubs
(like workers), add those stubs centrally in tests/conftest.py rather than
inserting handlers_path per test file, and ensure no insertion elevates handlers
above src to avoid import shadowing.

23-25: sys.modules patching at import time can leak across test files.

Stubbing workers globally during module import is brittle for test isolation. Prefer a fixture (monkeypatch.setitem(sys.modules, ...)) plus controlled import/reload so cleanup is automatic.

#!/bin/bash
set -euo pipefail

# Check whether other tests/modules rely on `workers` and may be affected by global stubs
rg -n -C2 'from workers import|import workers|sys\.modules\.setdefault\("workers"|sys\.modules\["workers"\]' tests src
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/test_auth.py` around lines 23 - 25, The test currently patches
sys.modules at import time via sys.modules.setdefault("workers",
types.SimpleNamespace(Response=_MockWorkersResponse)) which can leak across
tests; change to use a fixture that calls monkeypatch.setitem(sys.modules,
"workers", types.SimpleNamespace(Response=_MockWorkersResponse)) before
importing the module under test and then import/reload auth (e.g., use
importlib.import_module or importlib.reload on auth_handler) so the stub is only
present during the test and is automatically cleaned up; update references to
the current import statement (import auth as auth_handler) to happen after the
monkeypatch is applied.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@tests/test_auth.py`:
- Around line 41-63: Add a new test in tests/test_auth.py that mirrors the
signin wrong-method test: call auth_handler.handle_signup with a
MockRequest(method="GET") (URL "/auth/signup"), pass EmptyEnv() and the same
empty dicts, and assert the response.status is 405 and
response.headers.get("Allow") == "POST"; to ensure the method-guard runs before
DB/JWT work, monkeypatch auth_handler.get_db_safe to a coroutine that raises
(e.g., AssertionError) so the test fails if get_db_safe is invoked. Reference:
handle_signup, get_db_safe, MockRequest, EmptyEnv, auth_handler.

---

Nitpick comments:
In `@tests/test_auth.py`:
- Around line 10-13: Remove the duplicate sys.path manipulation in
tests/test_auth.py: delete the sys.path.insert calls that add src_path and
handlers_path, and instead rely on tests/conftest.py to set up sys.path; then
import the auth module directly (e.g., from handlers import auth or import auth)
in tests/test_auth.py. If handlers/auth.py needs module stubs (like workers),
add those stubs centrally in tests/conftest.py rather than inserting
handlers_path per test file, and ensure no insertion elevates handlers above src
to avoid import shadowing.
- Around line 23-25: The test currently patches sys.modules at import time via
sys.modules.setdefault("workers",
types.SimpleNamespace(Response=_MockWorkersResponse)) which can leak across
tests; change to use a fixture that calls monkeypatch.setitem(sys.modules,
"workers", types.SimpleNamespace(Response=_MockWorkersResponse)) before
importing the module under test and then import/reload auth (e.g., use
importlib.import_module or importlib.reload on auth_handler) so the stub is only
present during the test and is automatically cleaned up; update references to
the current import statement (import auth as auth_handler) to happen after the
monkeypatch is applied.
🪄 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: Repository: OWASP-BLT/coderabbit/.coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: b871a6a6-3f30-4359-a5f6-69b1c555d69f

📥 Commits

Reviewing files that changed from the base of the PR and between 74b44dc and 1b10cfb.

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

Comment thread tests/test_auth.py
@ojaswa072
Copy link
Copy Markdown
Contributor Author

@coderabbitai resume

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 20, 2026

✅ Actions performed

Reviews resumed.

@ojaswa072
Copy link
Copy Markdown
Contributor Author

@coderabbitai Can this PR be merged?

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 20, 2026

Tip

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

🧩 Analysis chain

Let me pull the full PR details before giving you an assessment.


🏁 Script executed:

#!/bin/bash
echo "=== PR status and checks ==="
gh pr view 38 --repo OWASP-BLT/BLT-API --json state,mergeable,mergeStateStatus,reviewDecision,statusCheckRollup,labels,reviews

echo ""
echo "=== PR review comments ==="
gh pr view 38 --repo OWASP-BLT/BLT-API --json comments,reviews

echo ""
echo "=== PR diff ==="
gh pr diff 38 --repo OWASP-BLT/BLT-API

Length of output: 50787


@ojaswa072 Here's a full rundown of the PR's current status:

✅ What's in good shape

Check Status
Merge state MERGEABLE / CLEAN
CodeRabbit review Approved (latest commit 30d9153)
CI (CodeRabbit check) SUCCESS
Method guard ordering (handle_signin) ✅ Fixed — method check runs before JWT read
Method guard ordering (handle_verify_email) ✅ Fixed — method check runs before DB/JWT
Allow headers on all 405 responses ✅ Present
Test isolation (monkeypatch fixture) ✅ Refactored — no global sys.modules leakage, no duplicate sys.path manipulation

All actionable issues from previous reviews have been resolved. The code is technically sound.


❌ Blocking item — Human peer review required

The repository enforces peer review via the owasp-blt bot. The needs-peer-review label is still active, and the bot explicitly requires:

A team member who is not the PR author, CodeRabbit, or Copilot must approve before merging.

You'll need to request a review from a human maintainer or team member to satisfy this requirement.


⚠️ Non-blocking warning

  • Docstring coverage: currently at 40%, below the 80% threshold. This is flagged as a warning (not a hard block), but it would be worth adding docstrings to the missing functions eventually.

Summary: The code is ready from a quality standpoint — please request a human peer review to unblock the merge. 🐇

Copy link
Copy Markdown

@Jayant2908 Jayant2908 left a comment

Choose a reason for hiding this comment

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

Looks good! Thank you!

@owasp-blt owasp-blt bot added has-peer-review PR has received peer review and removed needs-peer-review PR needs peer review labels Mar 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

has-peer-review PR has received peer review quality: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants