Skip to content

Add OAuth2 SSO endpoint for external application integration #13227

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from

Conversation

colesmcintosh
Copy link
Collaborator

@colesmcintosh colesmcintosh commented Aug 2, 2025

Title

Add OAuth2 SSO endpoint for external application integration

Relevant issues

Implements OAuth2 SSO flow to allow external applications (like RooCode) to authenticate users and obtain API tokens via a simple GET request.

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have Added testing in the tests/litellm/ directory, Adding at least 1 test is a hard requirement - see details
  • I have added a screenshot of my new test passing locally
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible, it only solves 1 specific problem

Type

🆕 New Feature

Changes

OAuth2 SSO Integration for External Applications

This PR adds OAuth2-compatible SSO endpoints that allow external applications to authenticate users and obtain API tokens through a streamlined flow.

Key Features:

  • Simple Integration: External apps can redirect users to https://your-proxy.com/sso/key/generate?response_type=oauth_token
  • Standard OAuth2 Response: Returns JSON with access_token, token_type, and expires_in fields per RFC 6749
  • Secure State Management: Uses timestamped, nonce-protected state parameters for flow validation
  • CORS Support: Configurable cross-origin headers via OAUTH_ALLOWED_ORIGINS environment variable

Implementation Details:

  • Modified /sso/key/generate endpoint to detect OAuth token requests via response_type=oauth_token parameter
  • Enhanced SSO callback handler to return JSON responses for OAuth flows instead of HTML redirects
  • Added create_oauth_token_response() helper function for standardized token formatting
  • Maintains full backward compatibility with existing CLI and UI SSO flows

Security Features:

  • State parameter validation with 5-minute expiry
  • Secure nonce generation using secrets.token_urlsafe()
  • URL parsing security to prevent injection attacks
  • Standard OAuth2 cache-control headers (no-store, no-cache)

Testing:

  • Comprehensive unit test suite with 16 test cases covering:
    • OAuth2 token response formatting and RFC compliance
    • State parameter generation and validation
    • Error handling scenarios
    • CORS header configuration
    • Security edge cases and malformed input handling
Screenshot 2025-08-02 at 10 18 08 AM

Usage Example for RooCode:

<a href="https://your-litellm-proxy.com/sso/key/generate?response_type=oauth_token">
  <button>Connect to LiteLLM</button>
</a>

Response Format:

{
  "access_token": "sk-litellm-xxxxxxxxxx",
  "token_type": "Bearer", 
  "expires_in": 86400
}

This implementation enables seamless integration with external applications while maintaining LiteLLM's existing security and authentication standards.

- Add response_type=oauth_token parameter to /sso/key/generate
- Return JSON token response for OAuth2 flows instead of HTML redirect
- Support CORS headers for cross-origin requests from external apps
- Add oauth_token_flow state handling in SSO callback
- Maintain backward compatibility with existing CLI and UI flows
- Add comprehensive unit tests for OAuth2 functionality

Enables external applications like RooCode to authenticate users via SSO
and receive RFC 6749 compliant OAuth2 token responses.
Copy link

vercel bot commented Aug 2, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
litellm ✅ Ready (Inspect) Visit Preview 💬 Add feedback Aug 2, 2025 9:46pm

- Change return type from Union[RedirectResponse, Dict] to Union[RedirectResponse, JSONResponse]
- Resolves MyPy type checking error for OAuth2 JSON response handling
This refactoring consolidates OAuth2-related functionality into reusable
utility classes, eliminating code duplication and improving maintainability.

**New OAuth2 Utility Classes:**
- OAuth2TokenManager: Centralized token response creation per RFC 6749
- OAuth2StateManager: Secure state parameter generation with timestamp/nonce validation
- OAuth2URLManager: Unified URL parsing and redirect handling
- OAuth2CORSHandler: Standardized CORS headers for OAuth2 responses

**Refactored Implementation:**
- Replace manual URL parsing with OAuth2URLManager.modify_url_for_oauth_flow()
- Enhanced state management with 5-minute expiry and secure nonce generation
- Consolidated token responses using OAuth2TokenManager.create_token_response()
- Unified CORS handling with OAuth2CORSHandler.get_oauth_cors_headers()

**Benefits:**
- Eliminated duplicate code across 4+ locations
- Enhanced security with proper state validation
- Improved maintainability with centralized utilities
- Better type safety with proper annotations

**Testing:**
- All 16 OAuth2 tests pass
- Updated tests to use new utility classes
- MyPy type checking clean (1022 files)
- Ruff linting clean

**Files Modified:**
- litellm/proxy/management_endpoints/sso_helper_utils.py: +149 lines (new utilities)
- litellm/proxy/management_endpoints/ui_sso.py: Refactored to use utilities
- tests/.../test_oauth2_flow.py: Updated to use new utility classes
- enterprise/.../custom_sso_handler.py: Fixed return type compatibility
Update return type annotation to support OAuth2 JSON responses alongside
traditional redirect responses for consistency with main OAuth2 implementation.
This enhancement enables VSCode extension compatibility by supporting OAuth2
redirect flows alongside the existing JSON response format.

**New Features:**
- redirect_uri parameter support for OAuth2 flows
- Dual response mode: redirect vs JSON based on redirect_uri presence
- VSCode URI scheme validation (vscode://, vscode-insiders://)
- Secure redirect_uri validation with allowlist

**OAuth2 Flow Enhancements:**
- Enhanced OAuth2URLManager with callback redirect URL building
- Secure state management stores redirect_uri with nonce/timestamp validation
- OAuth2StateManager extract_redirect_uri() method for state parsing
- Comprehensive redirect_uri validation prevents XSS attacks

**VSCode Extension Compatibility:**
- URL format: /sso/key/generate?response_type=oauth_token&redirect_uri=vscode://ext/callback
- Callback format: vscode://ext/callback?access_token=sk-xxx&token_type=Bearer&expires_in=86400
- Maintains full backward compatibility with existing JSON flows

**Security:**
- Validates redirect_uri against allowed schemes (vscode, https, http)
- Prevents malicious redirects (javascript:, data:, file: schemes blocked)
- Enhanced state parameter includes redirect_uri with secure validation
- 5-minute state expiry with nonce protection

**Testing:**
- Added 6 new test cases for redirect_uri functionality
- Tests cover VSCode URI validation, callback URL building, state management
- All 23 OAuth2 tests passing with full coverage
- Integration tests for VSCode extension flow structure

**Backward Compatibility:**
- Without redirect_uri: Returns JSON response (original behavior)
- With redirect_uri: Redirects to callback with access_token query param
- All existing flows continue to work unchanged

**Implementation Details:**
- OAuth2URLManager.build_callback_redirect_url() for VSCode callbacks
- OAuth2URLManager.validate_redirect_uri() with security checks
- Enhanced serve_login_page() and sso_login_redirect() endpoints
- Modified auth_callback() to support both redirect and JSON responses

This makes LiteLLM OAuth2 consistent with OpenRouter, Glama, and Requesty
for seamless VSCode extension integration.
This enhancement significantly expands OAuth2 redirect_uri support to include
all popular IDEs, editors, and development tools, making LiteLLM compatible
with a wide range of desktop applications and extensions.

**New Supported URI Schemes:**
- IDE/Editor support: cursor, vscodium, code-oss, fleet, zed, sublime, atom, brackets, nova
- Development tools: github-desktop, sourcetree, tower, fork
- Legacy editors: textmate, coderunner
- Custom schemes via OAUTH_ALLOWED_REDIRECT_SCHEMES environment variable

**Key Features:**
- Comprehensive URI scheme validation for 15+ popular IDEs/editors
- Environment variable OAUTH_ALLOWED_REDIRECT_SCHEMES for custom schemes
- Secure validation prevents malicious redirects while supporting legitimate tools
- Maintains backward compatibility with existing vscode:// and https:// schemes

**Security:**
- Validates IDE URIs require proper format: scheme://extension-id/callback-path
- Blocks dangerous schemes (javascript:, data:, file:) while allowing dev tools
- Custom schemes from environment variable are safely validated
- All schemes maintain existing security requirements

**Testing:**
- Added comprehensive tests for all new URI schemes
- Environment variable configuration testing
- Cursor editor specific flow testing
- Integration tests for popular IDE flows
- All 26 OAuth2 tests passing with expanded coverage

**Configuration:**
Set custom schemes via environment variable:
```bash
export OAUTH_ALLOWED_REDIRECT_SCHEMES="myide,customapp,special-editor"
```

**Supported Flows:**
- Cursor: cursor://extension/callback?access_token=...
- Fleet: fleet://extension/callback?access_token=...
- Zed: zed://extension/callback?access_token=...
- And 10+ more popular development tools

This makes LiteLLM OAuth2 compatible with virtually any desktop IDE or
development tool that supports custom URI schemes for OAuth callbacks.
- Update modify_url_for_oauth_flow to preserve redirect_uri parameter
- Add comprehensive documentation for redirect_uri handling
- Ensure VSCode and IDE extension compatibility during OAuth flow
- Maintain backward compatibility for existing OAuth implementations
- Add authentication check for OAuth token flows via Authorization header
- Generate new session keys directly for authenticated users without SSO redirect
- Implement _check_existing_authentication() to validate existing tokens
- Implement _handle_authenticated_oauth_flow() for seamless key generation
- Add comprehensive tests for both authenticated and non-authenticated scenarios
- Improve user experience for IDE extensions like RooCode, VSCode, Cursor
- Maintain full backward compatibility with existing OAuth flows

Benefits:
- Faster token generation for already-logged-in users
- No unnecessary SSO redirects when user has valid session
- Better UX for IDE extensions and external applications
- Secure token validation before generating new OAuth session keys
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