Skip to content

Conversation

@ksylvan
Copy link
Collaborator

@ksylvan ksylvan commented Jul 1, 2025

OAuth Authentication Support for Anthropic

Summary

This PR adds OAuth authentication support for the Anthropic Claude provider in Fabric, allowing users to authenticate using their Claude account credentials instead of requiring an API key. The implementation includes secure token storage, automatic token refresh, and comprehensive test coverage.

Related Issues

Closes #1534

Screen Shots

image

image

Files Changed

New Files Added

  • common/oauth_storage.go - Core OAuth token storage functionality with secure file operations
  • common/oauth_storage_test.go - Comprehensive test suite for OAuth storage operations
  • plugins/ai/anthropic/oauth.go - OAuth flow implementation specific to Anthropic's authentication system

Modified Files

  • plugins/ai/anthropic/anthropic.go - Enhanced to support OAuth authentication alongside existing API key authentication
  • go.mod - Moved golang.org/x/oauth2 from indirect to direct dependency
  • restapi/configuration.go - Added OAuth configuration option to REST API endpoints

Code Changes

OAuth Storage Implementation

The new OAuthStorage struct provides secure token management:

type OAuthToken struct {
    AccessToken  string `json:"access_token"`
    RefreshToken string `json:"refresh_token"`
    ExpiresAt    int64  `json:"expires_at"`
    TokenType    string `json:"token_type"`
    Scope        string `json:"scope"`
}

Key features:

  • Tokens stored in ~/.config/fabric/ with 0600 permissions
  • Atomic file operations using temporary files
  • Expiration checking with configurable buffer time
  • Safe deletion of expired tokens

Anthropic OAuth Integration

The OAuth implementation includes:

  • PKCE (Proof Key for Code Exchange) for enhanced security
  • Custom HTTP transport that automatically adds Bearer tokens
  • Automatic token refresh when tokens expire
  • Fallback to re-authentication if refresh fails

Configuration Updates

Added OAuth support to the REST API configuration:

  • New anthropic_use_oauth_login configuration option
  • Maintains backward compatibility with existing API key authentication

Reason for Changes

This enhancement addresses the need for users to authenticate with Claude using their existing accounts rather than requiring separate API keys. OAuth provides a more user-friendly authentication experience and aligns with modern authentication practices.

Impact of Changes

Positive Impacts

  • Improved User Experience: Users can authenticate using their existing Claude accounts
  • Enhanced Security: OAuth tokens are more secure than long-lived API keys
  • Automatic Token Management: Tokens are automatically refreshed, reducing authentication failures

Potential Risks

  • Additional Complexity: OAuth flow is more complex than API key authentication
  • Network Dependencies: OAuth requires internet connectivity for token refresh
  • Browser Dependency: Initial authentication requires opening a web browser

Test Plan

The implementation includes comprehensive unit tests covering:

  • Token expiration logic with various scenarios
  • Secure file operations with proper permissions
  • Token save/load/delete operations
  • Error handling for non-existent tokens
  • Path generation for different providers

Manual testing should verify:

  1. OAuth flow completion in web browser
  2. Token storage and retrieval
  3. Automatic token refresh
  4. Fallback to API key authentication when OAuth is disabled

Demo of functionality

Removed the auth token (~/.config/fabric/.claude_oauth).

fabric --search -m $MODEL_CLAUDE 'Tell me about the world news today in the world of Chess.'
No OAuth token found, initiating authentication...
Open the following URL in your browser. Fabric would like to authorize:
https://claude.ai/oauth/authorize?client_id=[...]
Paste the authorization code here: [REDACTED]

image

Additional Notes

Security Considerations

  • OAuth tokens are stored with restrictive file permissions (0600)
  • Temporary files are used for atomic operations
  • Tokens include expiration times and are automatically refreshed
  • The implementation follows OAuth 2.0 best practices with PKCE

Backward Compatibility

  • Existing API key authentication continues to work unchanged
  • OAuth is opt-in via configuration setting
  • No breaking changes to existing functionality

@ksylvan
Copy link
Collaborator Author

ksylvan commented Jul 2, 2025

Stopped here:

fabric -p ai -m $MODEL_CLAUDE 'Why is the sky blue?'
POST "https://api.anthropic.com/v1/messages": 401 Unauthorized {"type":"error","error":{"type":"authentication_error","message":"OAuth authentication is currently not supported."}}

We have to figure out how Claude Code does its magic when it grabs the OAuth token.

@eugeis
Copy link
Collaborator

eugeis commented Jul 4, 2025

LGTM

@ksylvan ksylvan marked this pull request as ready for review July 5, 2025 15:27
@ksylvan ksylvan marked this pull request as draft July 5, 2025 15:31
- Move golang.org/x/oauth2 from indirect to direct dependency
- Add OAuth login option for Anthropic client
- Implement PKCE OAuth flow with browser integration
- Add custom HTTP transport for OAuth Bearer tokens
- Support both API key and OAuth authentication methods
- Add Claude Code system message for OAuth sessions
- Update REST API to handle OAuth tokens
- Improve environment variable name sanitization with regex
@ksylvan ksylvan force-pushed the 0701-claude-oauth-support branch from 9b0b531 to 4bff88f Compare July 5, 2025 15:32
@ksylvan
Copy link
Collaborator Author

ksylvan commented Jul 5, 2025

Okay, @eugeis and @johnsaigle, I got it to work. I will be finalizing the PR soon.

We use the same technique that the sst/opencode repo uses to spoof being Claude Code.

… authentication

## CHANGES

- Add automatic OAuth token refresh when expired
- Implement persistent token storage using common OAuth storage
- Remove deprecated AuthToken setting from client configuration
- Add token validation with 5-minute expiration buffer
- Create refreshToken function for seamless token renewal
- Update OAuth flow to save complete token information
- Enhance error handling for OAuth authentication failures
- Simplify client configuration by removing manual token management
ksylvan added 2 commits July 5, 2025 09:37
## CHANGES

- Remove OAuth-specific v1 endpoint handling logic
- Standardize all API calls to use v2 endpoint
- Simplify baseURL configuration by removing conditional branching
- Update endpoint logic to always append v2 suffix
…ion and timeout handling

## CHANGES

- Add automatic OAuth flow initiation when no token exists
- Implement fallback re-authentication when token refresh fails
- Add timeout contexts for OAuth and refresh operations
- Create context-aware OAuth flow and token exchange functions
- Enhance error handling with graceful authentication recovery
- Add user input timeout protection for authorization codes
- Preserve refresh tokens during token exchange operations
@ksylvan ksylvan changed the title Add OAuth auhentication support for Anthropic Add OAuth authentication support for Anthropic Jul 5, 2025
@ksylvan ksylvan marked this pull request as ready for review July 5, 2025 18:26
@ksylvan ksylvan requested a review from Copilot July 5, 2025 18:26

This comment was marked as outdated.

ksylvan added 2 commits July 5, 2025 11:39
### CHANGES

- Remove redundant base URL trimming logic
- Append base URL directly without modification
- Eliminate conditional check for API version suffix
@ksylvan ksylvan marked this pull request as draft July 5, 2025 19:01
@ksylvan ksylvan marked this pull request as ready for review July 5, 2025 21:32
@ksylvan ksylvan requested a review from Copilot July 5, 2025 21:32

This comment was marked as outdated.

ksylvan added 2 commits July 5, 2025 14:46
…te module

## CHANGES

- Remove OAuth transport implementation from main client
- Extract OAuth flow functions to separate module
- Remove unused imports and constants from client
- Replace inline OAuth transport with NewOAuthTransport call
- Update runOAuthFlow to exported RunOAuthFlow function
- Clean up token management and refresh logic
- Simplify client configuration by removing OAuth internals
@ksylvan ksylvan changed the title Add OAuth authentication support for Anthropic OAuth Authentication Support for Anthropic Jul 5, 2025
@ksylvan ksylvan merged commit 369a0a8 into danielmiessler:main Jul 5, 2025
1 check passed
@ksylvan ksylvan deleted the 0701-claude-oauth-support branch July 5, 2025 22:24
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.

[Feature request]: Add Claude Pro authentication method

2 participants