ultrafast_mcp_auth/
lib.rs

1//! # UltraFast MCP Authentication
2//!
3//! Comprehensive authentication and authorization support for the Model Context Protocol (MCP).
4//!
5//! This crate provides robust authentication mechanisms for MCP servers and clients,
6//! including OAuth 2.1 support, PKCE (Proof Key for Code Exchange), and token validation.
7//! It's designed to be secure, flexible, and easy to integrate into MCP applications.
8//!
9//! ## Overview
10//!
11//! The UltraFast MCP Authentication crate provides:
12//!
13//! - **OAuth 2.1 Support**: Complete OAuth 2.1 implementation with PKCE
14//! - **Token Management**: Secure token storage, validation, and rotation
15//! - **PKCE Support**: Proof Key for Code Exchange for enhanced security
16//! - **Session Management**: Secure session handling and management
17//! - **Validation**: Comprehensive token and credential validation
18//! - **Security**: Industry-standard security practices and protocols
19//!
20//! ## Key Features
21//!
22//! ### OAuth 2.1 Implementation
23//! - **Authorization Code Flow**: Complete OAuth 2.1 authorization code flow
24//! - **PKCE Support**: Proof Key for Code Exchange for public clients
25//! - **Token Refresh**: Automatic token refresh and rotation
26//! - **Scope Management**: Fine-grained permission and scope handling
27//! - **State Validation**: CSRF protection through state parameter validation
28//!
29//! ### Security Features
30//! - **PKCE**: Enhanced security for public clients
31//! - **State Validation**: Protection against CSRF attacks
32//! - **Token Validation**: Comprehensive token verification
33//! - **Secure Storage**: Encrypted token storage
34//! - **Session Management**: Secure session handling
35//!
36//! ### Token Management
37//! - **Access Tokens**: Short-lived access token handling
38//! - **Refresh Tokens**: Long-lived refresh token management
39//! - **ID Tokens**: OpenID Connect ID token support
40//! - **Token Validation**: JWT validation and verification
41//! - **Token Rotation**: Automatic token refresh and rotation
42//!
43//! ## Modules
44//!
45//! - **[`oauth`]**: OAuth 2.1 client implementation and flow management
46//! - **[`pkce`]**: PKCE (Proof Key for Code Exchange) utilities
47//! - **[`types`]**: Authentication-related type definitions
48//! - **[`validation`]**: Token and credential validation utilities
49//! - **[`error`]**: Authentication-specific error types
50//!
51//! ## Usage Examples
52//!
53//! ### Basic OAuth 2.1 Flow
54//!
55//! ```rust,ignore
56//! use ultrafast_mcp_auth::{
57//!     OAuthClient, OAuthConfig, generate_pkce_params,
58//!     AuthResult, AuthError
59//! };
60//! use ultrafast_mcp_core::utils::identifiers::{generate_session_id, generate_state};
61//!
62//! #[tokio::main]
63//! async fn main() -> AuthResult<()> {
64//!     // Create OAuth configuration
65//!     let config = OAuthConfig {
66//!         client_id: "your-client-id".to_string(),
67//!         client_secret: "your-client-secret".to_string(),
68//!         auth_url: "https://auth.example.com/oauth/authorize".to_string(),
69//!         token_url: "https://auth.example.com/oauth/token".to_string(),
70//!         redirect_uri: "http://localhost:8080/callback".to_string(),
71//!         scopes: vec!["read".to_string(), "write".to_string()],
72//!     };
73//!
74//!     // Create OAuth client
75//!     let client = OAuthClient::from_config(config.clone());
76//!
77//!     // Generate PKCE parameters
78//!     let pkce_params = generate_pkce_params()?;
79//!
80//!     // Generate state parameter for CSRF protection
81//!     let state = generate_state();
82//!
83//!     // Create authorization URL
84//!     let auth_url = client.get_authorization_url_with_pkce(state, pkce_params.clone()).await?;
85//!     println!("Authorization URL: {}", auth_url);
86//!
87//!     // After user authorization, exchange code for tokens
88//!     let code = "authorization_code_from_callback";
89//!     let tokens = client.exchange_code_for_token(
90//!         &config.token_url,
91//!         &config.client_id,
92//!         Some(&config.client_secret),
93//!         &config.redirect_uri,
94//!         code,
95//!         &pkce_params.code_verifier
96//!     ).await?;
97//!
98//!     println!("Access token: {}", tokens.access_token);
99//!     if let Some(refresh_token) = &tokens.refresh_token {
100//!         println!("Refresh token: {}", refresh_token);
101//!     }
102//!
103//!     Ok(())
104//! }
105//! ```
106//!
107//! ### Token Validation
108//!
109//! ```rust
110//! use ultrafast_mcp_auth::{TokenValidator, AuthResult, AuthError};
111//!
112//! async fn validate_request(token: &str) -> AuthResult<()> {
113//!     // Create token validator with secret
114//!     let validator = TokenValidator::new("your-jwt-secret".to_string());
115//!
116//!     // Validate the token
117//!     let claims = validator.validate_token(token).await?;
118//!
119//!     // Check if token has required scopes
120//!     if let Some(scope) = &claims.scope {
121//!         if !scope.contains("read") {
122//!             return Err(AuthError::MissingScope {
123//!                 scope: "read".to_string()
124//!             });
125//!         }
126//!     }
127//!
128//!     println!("Token is valid for user: {}", claims.sub);
129//!     Ok(())
130//! }
131//! ```
132//!
133//! ### PKCE Implementation
134//!
135//! ```rust,ignore
136//! use ultrafast_mcp_auth::{generate_pkce_params, AuthResult};
137//! use ultrafast_mcp_core::utils::identifiers::{generate_session_id, generate_state};
138//!
139//! fn setup_pkce_flow() -> AuthResult<(String, String, String)> {
140//!     // Generate PKCE parameters
141//!     let pkce_params = generate_pkce_params()?;
142//!
143//!     // Generate session ID for tracking
144//!     let session_id = generate_session_id();
145//!
146//!     // Generate state parameter
147//!     let state = generate_state();
148//!
149//!     println!("Code verifier: {}", pkce_params.code_verifier);
150//!     println!("Code challenge: {}", pkce_params.code_challenge);
151//!     println!("Session ID: {}", session_id);
152//!     println!("State: {}", state);
153//!
154//!     Ok((pkce_params.code_verifier, session_id, state))
155//! }
156//! ```
157//!
158//! ### OAuth Client with Refresh
159//!
160//! ```rust
161//! use ultrafast_mcp_auth::{OAuthClient, OAuthConfig, TokenResponse, AuthResult};
162//!
163//! async fn handle_token_refresh(client: &OAuthClient, refresh_token: &str, token_url: &str) -> AuthResult<()> {
164//!     // Refresh the access token
165//!     let new_tokens = client.refresh_token(token_url, &client.client_id(), Some(&client.client_secret()), refresh_token).await?;
166//!
167//!     // Store the new tokens securely
168//!     store_tokens_securely(&new_tokens).await?;
169//!
170//!     println!("Tokens refreshed successfully");
171//!     Ok(())
172//! }
173//!
174//! async fn store_tokens_securely(tokens: &TokenResponse) -> AuthResult<()> {
175//!     // Implement secure token storage
176//!     // This could involve encryption, secure key storage, etc.
177//!     Ok(())
178//! }
179//! ```
180//!
181//! ## OAuth 2.1 Flow
182//!
183//! The crate implements the complete OAuth 2.1 authorization code flow:
184//!
185//! ```text
186//! Client                    Authorization Server
187//!   |                              |
188//!   |-- Authorization Request ---->|
189//!   |<-- Authorization Code -------|
190//!   |                              |
191//!   |-- Token Request ------------>|
192//!   |<-- Access Token + Refresh ---|
193//!   |                              |
194//!   |-- API Request -------------->|
195//!   |<-- Protected Resource -------|
196//! ```
197//!
198//! ### PKCE Flow
199//!
200//! For enhanced security, the crate supports PKCE:
201//!
202//! ```text
203//! 1. Generate code_verifier (random string)
204//! 2. Generate code_challenge (SHA256 hash of code_verifier)
205//! 3. Send code_challenge in authorization request
206//! 4. Send code_verifier in token request
207//! 5. Server validates code_challenge against code_verifier
208//! ```
209//!
210//! ## Security Features
211//!
212//! ### CSRF Protection
213//! - **State Parameter**: Random state parameter for each authorization request
214//! - **Validation**: Server validates state parameter in callback
215//! - **Session Binding**: State parameter bound to user session
216//!
217//! ### Token Security
218//! - **Short-lived Access Tokens**: Access tokens expire quickly
219//! - **Secure Refresh Tokens**: Long-lived refresh tokens with rotation
220//! - **Token Validation**: Comprehensive JWT validation
221//! - **Scope Validation**: Fine-grained permission checking
222//!
223//! ### PKCE Security
224//! - **Code Verifier**: Random string generated by client
225//! - **Code Challenge**: SHA256 hash of code verifier
226//! - **Validation**: Server validates challenge against verifier
227//! - **Public Client Security**: Enhanced security for public clients
228//!
229//! ## Configuration
230//!
231//! ### OAuth Configuration
232//! ```rust
233//! use ultrafast_mcp_auth::OAuthConfig;
234//!
235//! let config = OAuthConfig {
236//!     client_id: "your-client-id".to_string(),
237//!     client_secret: "your-client-secret".to_string(),
238//!     auth_url: "https://auth.example.com/oauth/authorize".to_string(),
239//!     token_url: "https://auth.example.com/oauth/token".to_string(),
240//!     redirect_uri: "http://localhost:8080/callback".to_string(),
241//!     scopes: vec!["read".to_string(), "write".to_string()],
242//! };
243//! ```
244//!
245//! ### Token Validator Configuration
246//! ```rust
247//! use ultrafast_mcp_auth::TokenValidator;
248//!
249//! let validator = TokenValidator::new("your-jwt-secret".to_string());
250//! ```
251//!
252//! ## Error Handling
253//!
254//! The crate provides comprehensive error handling:
255//!
256//! ```rust
257//! use ultrafast_mcp_auth::{AuthError, AuthResult};
258//!
259//! async fn handle_auth_error(result: AuthResult<()>) {
260//!     match result {
261//!         Ok(()) => println!("Authentication successful"),
262//!         Err(AuthError::InvalidToken(message)) => {
263//!             eprintln!("Invalid token: {}", message);
264//!             // Handle invalid token
265//!         }
266//!         Err(AuthError::MissingScope { scope }) => {
267//!             eprintln!("Missing scope: {}", scope);
268//!             // Handle permission error
269//!         }
270//!         Err(AuthError::NetworkError(message)) => {
271//!             eprintln!("Network error: {}", message);
272//!             // Handle network error
273//!         }
274//!         Err(e) => {
275//!             eprintln!("Authentication error: {:?}", e);
276//!             // Handle other errors
277//!         }
278//!     }
279//! }
280//! ```
281//!
282//! ## Best Practices
283//!
284//! ### Security
285//! - Always use PKCE for public clients
286//! - Validate state parameters to prevent CSRF attacks
287//! - Store tokens securely (encrypted, not in plain text)
288//! - Use short-lived access tokens
289//! - Implement proper token refresh logic
290//! - Validate all tokens before use
291//!
292//! ### Implementation
293//! - Handle all error cases gracefully
294//! - Implement proper token refresh logic
295//! - Use secure random number generation
296//! - Validate all inputs and outputs
297//! - Log authentication events for audit
298//!
299//! ### Integration
300//! - Integrate with your application's session management
301//! - Implement proper error handling and user feedback
302//! - Use appropriate timeouts for network requests
303//! - Handle network failures gracefully
304//! - Implement proper logout and token revocation
305//!
306//! ## Performance Considerations
307//!
308//! - **Token Caching**: Cache validated tokens to reduce validation overhead
309//! - **Connection Pooling**: Reuse HTTP connections for token requests
310//! - **Async Operations**: All operations are async for non-blocking performance
311//! - **Efficient Validation**: Optimized JWT validation algorithms
312//! - **Minimal Allocations**: Efficient memory usage in hot paths
313//!
314//! ## Thread Safety
315//!
316//! All authentication components are designed to be thread-safe:
317//! - OAuth clients are `Send + Sync`
318//! - Token validators are stateless and thread-safe
319//! - PKCE utilities are stateless and thread-safe
320//! - No mutable global state is used
321//!
322//! ## Examples
323//!
324//! See the `examples/` directory for complete working examples:
325//! - Basic OAuth 2.1 flow
326//! - PKCE implementation
327//! - Token validation
328//! - Refresh token handling
329//! - Integration with MCP servers and clients
330
331pub mod error;
332pub mod middleware;
333pub mod oauth;
334pub mod pkce;
335pub mod types;
336pub mod validation;
337
338pub use error::AuthError;
339pub use oauth::OAuthClient;
340pub use pkce::generate_pkce_params;
341// generate_session_id and generate_state are now available directly from ultrafast_mcp_core::utils
342pub use middleware::{AuthContext, ClientAuthMiddleware, ServerAuthMiddleware};
343pub use types::*;
344pub use validation::{TokenValidator, extract_bearer_token};
345
346/// Result type for authentication operations
347pub type AuthResult<T> = Result<T, AuthError>;