Skip to content

Conversation

@matzew
Copy link
Collaborator

@matzew matzew commented Oct 1, 2025

using standard library for error write

Summary by CodeRabbit

  • Refactor
    • Streamlined unauthorized (401) response handling in OAuth middleware for consistency and maintainability.
    • Reduced custom logic by using standardized HTTP error responses, removing redundant logging.
    • No changes to user-facing behavior; authentication flows remain the same.

@matzew matzew requested a review from a team as a code owner October 1, 2025 17:21
@coderabbitai
Copy link

coderabbitai bot commented Oct 1, 2025

Walkthrough

Replaced manual 401 response handling in pkg/oauth/middleware.go with http.Error. Removed the log import and logging on write failure. No exported APIs changed.

Changes

Cohort / File(s) Summary
OAuth middleware error handling
pkg/oauth/middleware.go
Replaced custom write401 (setting headers, WriteHeader, Write, and logging on failure) with http.Error(body, 401). Removed log import; middleware behavior otherwise unchanged.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

I nibble code like clover leaves,
Swap writes for http.Error ease.
No logs to chase, no headers fuss—
A tidy 401 for us.
With twitching whiskers, merge I bless,
Cleaner paths, and fewer mess.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title clearly and concisely describes the primary change, which is replacing manual error handling with a call to http.Error(), making it easy for reviewers to understand the main modification at a glance.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@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

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ee46935 and d7593ed.

📒 Files selected for processing (1)
  • pkg/oauth/middleware.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Unit Tests

if err != nil {
log.Printf("failed to write response: %v", err)
}
http.Error(w, body, http.StatusUnauthorized)
Copy link

@coderabbitai coderabbitai bot Oct 1, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Content-Type mismatch for JSON error responses.

http.Error() sets Content-Type: text/plain; charset=utf-8, but the body contains JSON. RFC 6750 (OAuth 2.0 Bearer Token Usage) specifies that error responses should use application/json when including error details in the response body.

Apply this diff to set the correct Content-Type:

 	w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer resource_metadata=%q", fullWellKnownPath))
-	http.Error(w, body, http.StatusUnauthorized)
+	w.Header().Set("Content-Type", "application/json")
+	w.WriteHeader(http.StatusUnauthorized)
+	w.Write([]byte(body))

Alternatively, if you prefer to keep using http.Error() for simplicity and don't mind the text/plain Content-Type:

 	w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer resource_metadata=%q", fullWellKnownPath))
+	w.Header().Set("Content-Type", "application/json")
 	http.Error(w, body, http.StatusUnauthorized)

Note: Setting Content-Type before calling http.Error() will preserve your custom header.

📝 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
http.Error(w, body, http.StatusUnauthorized)
// preserve the WWW-Authenticate header for OAuth 2.0 Bearer error responses
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer resource_metadata=%q", fullWellKnownPath))
// explicitly set JSON content type and write the status + JSON body without the newline
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(body))
🤖 Prompt for AI Agents
In pkg/oauth/middleware.go around line 76, the handler calls http.Error(w, body,
http.StatusUnauthorized) which sets Content-Type to text/plain while body
contains JSON; change it to send a proper application/json response by setting
the Content-Type header to "application/json" and writing the status and JSON
body explicitly (i.e., set w.Header().Set("Content-Type", "application/json"),
call w.WriteHeader(http.StatusUnauthorized), then write the JSON body to the
response writer) — alternatively, if you must keep http.Error(), set the
Content-Type header to "application/json" before calling http.Error() so the
custom header is preserved.

Copy link
Member

Choose a reason for hiding this comment

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

IIRC the application/json type was required by the mcp clients, so I think we need to keep w.Header().Set("Content-Type", "application/json")

Copy link

Choose a reason for hiding this comment

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

@creydr, you're absolutely right! The application/json Content-Type is important for proper client parsing.

The good news is that the committable suggestion I provided already includes setting Content-Type to "application/json" explicitly:

w.Header().Set("WWW-Authenticate", fmt.Sprintf("Bearer resource_metadata=%q", fullWellKnownPath))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(body))

This approach ensures MCP clients receive the correct application/json Content-Type while properly handling the OAuth 2.0 Bearer error response format. The fix reverts to explicit header setting and response writing, which gives you full control over the Content-Type header (unlike http.Error() which would override it with text/plain).

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

@creydr the .Error does a .Del on content-type

Is application/json really required?

Copy link

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Copy link
Collaborator

Choose a reason for hiding this comment

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

@matzew I think the application/json required is normally true, because MCP is a JSON RPC protocol a lot of clients assume all the http bits are json iirc

@matzew
Copy link
Collaborator Author

matzew commented Oct 2, 2025 via email

@matzew matzew closed this Oct 6, 2025
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.

3 participants