Skip to content

Conversation

j-mcnally
Copy link

Summary

This PR implements a complete OAuth 2.1 Authorization Server with Claude Desktop integration support:

OAuth 2.1 Server: Full authorization server with Dynamic Client Registration (RFC 7591)
PKCE Support: Enhanced security with Proof Key for Code Exchange
Username/Password Auth: Secure login form with configurable user credentials
Token Management: Access tokens, refresh tokens with persistence across restarts
IP Allowlisting: Security feature to restrict client registration to Claude's official IPs
Enhanced Documentation: Comprehensive README updates with OAuth configuration examples
Configuration Migration: Added OAuth2Config struct with backward compatibility

Key Features Added

  • Complete OAuth 2.1 authorization server in oauth.go (1200+ lines)
  • Enhanced HTTP middleware for OAuth token validation
  • Persistent client and token storage with JSON serialization
  • Dynamic client registration endpoint for automatic Claude Desktop setup
  • IP-based access control with proxy header detection
  • Configuration examples for development and production setups
  • Improved routing with exact path matching to prevent redirect issues

Configuration Changes

New oauth2 configuration section for streamable-http transport:

{
  "mcpProxy": {
    "type": "streamable-http", 
    "options": {
      "oauth2": {
        "enabled": true,
        "users": {
          "admin": "password123"
        },
        "persistenceDir": "/custom/path",
        "allowedIPs": ["34.162.46.92", "34.162.102.82"],
        "tokenExpirationMinutes": 60
      }
    }
  }
}

Security Features

  • Username/password authentication required for all OAuth flows
  • Bearer token validation for all MCP endpoints
  • Client secret cryptographic validation
  • Secure file persistence with 0700 permissions
  • Optional IP allowlisting for Claude's official addresses
  • Callback URL validation for security
  • Configurable token expiration (default: 1 hour)
  • Refresh token rotation per OAuth 2.1 best practices

Files Changed

  • oauth.go: New OAuth 2.1 authorization server implementation
  • http.go: Enhanced with OAuth middleware and improved routing
  • config.go: Added OAuth2Config struct with migration support
  • README.md: Comprehensive OAuth documentation and examples
  • .gitignore: Added config.json and *.log to prevent accidental commits
  • CLAUDE.md: Added for Claude Code development guidance
  • config.example.json: Updated with OAuth configuration examples
  • docs/index.html: Added OAuth feature to documentation site

Test Plan

  • OAuth server starts correctly with configuration
  • Dynamic client registration works via /oauth/register
  • Authorization flow works with username/password form at /oauth/authorize
  • Token exchange works at /oauth/token with PKCE validation
  • Access tokens properly protect MCP endpoints
  • Client and token persistence survives server restarts
  • IP allowlisting correctly blocks/allows client registration
  • Configuration migration maintains backward compatibility
  • Example configuration files updated
  • Documentation comprehensively covers OAuth setup and usage

This implementation provides a production-ready OAuth 2.1 authorization server specifically designed for Claude Desktop integration while maintaining full backward compatibility with existing configurations.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Summary of Changes

Hello @j-mcnally, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a comprehensive OAuth 2.1 Authorization Server into the MCP Proxy, primarily to support secure and seamless integration with Claude Desktop. The new server provides robust authentication and authorization capabilities, including dynamic client registration, Proof Key for Code Exchange (PKCE), user-based authentication, and persistent token management. This enhancement significantly bolsters the proxy's security posture and simplifies its use with external applications requiring standardized access control.

Highlights

  • OAuth 2.1 Authorization Server Implementation: A full OAuth 2.1 Authorization Server has been added, supporting dynamic client registration (RFC 7591), PKCE, username/password authentication, and robust token management (access and refresh tokens with persistence).
  • Claude Desktop Integration: The server is specifically designed to integrate with Claude Desktop, including features like IP allowlisting for Claude's official IPs and strict callback URL validation to enhance security.
  • Enhanced Security Features: Implemented secure authentication flows, cryptographic validation of client secrets, secure file persistence with strict 0700 permissions, and refresh token rotation per OAuth 2.1 best practices.
  • Configuration and Documentation Updates: A new 'oauth2' configuration section has been added to 'config.go' and 'config.example.json', along with extensive updates to 'README.md' and a new 'CLAUDE.md' for development guidance.
  • Improved HTTP Routing: The 'http.go' file has been updated to include OAuth middleware for token validation and refined routing logic to prevent automatic redirects by registering exact paths.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a comprehensive OAuth 2.1 Authorization Server to support Claude Desktop integration. The implementation is extensive, covering dynamic client registration, PKCE, token management with persistence, and IP allowlisting. The changes also include necessary updates to configuration, HTTP middleware, and documentation.

My review focuses on improving security, maintainability, and adherence to Go best practices. I've identified a high-severity security vulnerability in the password comparison logic that should be addressed. Additionally, there are several medium-severity suggestions to improve maintainability, such as using html/template instead of string-based HTML generation, replacing deprecated ioutil functions, and using request context for passing data in middleware.

Overall, this is a significant and well-executed feature addition. Addressing the feedback will enhance the security and long-term maintainability of the new OAuth server.

- Use crypto/subtle.ConstantTimeCompare for password comparison to prevent timing attacks
- Replace deprecated ioutil.ReadFile/WriteFile with os.ReadFile/WriteFile
- Use request context instead of headers for OAuth middleware data passing
- Replace HTML string concatenation with html/template package for better security and maintainability
- Improve template separation with proper data structures
- Add null checks for DOM elements before accessing them
- Use DOMContentLoaded event to ensure DOM is ready before executing JavaScript
- Fix countdown functionality and manual redirect fallback
- Resolves 'Cannot set properties of null' error
- Add oauth_templates.go with embedded default templates as constants
- Implement template override system: external templates take precedence over built-in
- Add --eject-templates CLI flag to export built-in templates for customization
- Update template loading logic with fallback mechanism
- Remove go:embed dependency - templates now work without external files
- Update documentation with new template system and ejection workflow
- Templates work out-of-the-box but can be customized when needed

Benefits:
- Zero external dependencies - OAuth works immediately after build
- Easy customization via template ejection
- Graceful fallback from external to built-in templates
- Clear upgrade path for template customization
- Add templateDir field to OAuth2Config for custom template locations
- Update template loading to use configured directory with fallback
- Add --eject-templates-to flag for CLI override of template ejection path
- Enhance ejectOAuthTemplates to support custom base directories
- Update template loading priority: configured dir > built-in templates
- Improve documentation with templateDir configuration examples
- Update CLI usage documentation and config examples

Template directory behavior:
- Configuration: Set oauth2.templateDir in config (default: 'templates')
- Ejection: --eject-templates uses config dir, --eject-templates-to overrides
- Loading: Server loads from {templateDir}/oauth/ with built-in fallback

This enables flexible deployment scenarios while maintaining zero-config defaults.
- Implement file modification time tracking for external templates
- Add reloadTemplatesIfChanged() method to check and reload templates automatically
- Hot reload triggers on every OAuth request when using external templates
- Zero-config hot reloading - always enabled for external templates
- Graceful fallback if template reload fails (keeps using previous templates)
- Update documentation with hot reload feature explanation

Benefits:
- Live development: Edit templates and see changes immediately
- No server restart required for template updates
- Seamless template customization workflow
- Only applies to external templates - built-in templates remain static for performance

Hot reload detection:
- Checks authorize.html and success.html modification times
- Reloads entire template set if any file changed
- Logs template reload events for debugging
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.

1 participant