# MySQL & OIDC Library Trade-offs Analysis
## AuthFramework v0.3.0 - Comprehensive Comparison
*Analysis Date: August 14, 2025*
---
## Executive Summary
This document analyzes trade-offs between current libraries (SQLx + OpenIDConnect) and alternatives (mysql_async + custom OIDC) to resolve the RUSTSEC-2023-0071 RSA vulnerability while maintaining functionality and security.
**Key Finding**: Each approach has distinct advantages - current libraries provide comprehensive features but introduce RSA dependency, while alternatives offer security but require significant development investment.
---
## ๐ Current vs Alternative: MySQL Libraries
### SQLx (Current) vs mysql_async
| **Security** | โ RSA v0.9.8 dependency (RUSTSEC-2023-0071) | โ
No RSA dependency |
| **Multi-DB Support** | โ
PostgreSQL, MySQL, SQLite unified API | โ MySQL-only |
| **Compile-time Checks** | โ
Compile-time SQL verification | โ Runtime-only validation |
| **Performance** | โก Very High (optimized for multi-DB) | โกโก Excellent (MySQL-specific) |
| **Feature Completeness** | โ
Full SQL feature set | โ
Full MySQL feature set |
| **Async Support** | โ
Tokio-based | โ
Tokio-based |
| **Connection Pooling** | โ
Built-in r2d2 integration | โ
Built-in async pool |
| **Maintenance** | โ
LaunchBadge (active) | โ
blackbeam (active) |
| **Community** | โญ 15k stars, large ecosystem | โญ 389 stars, MySQL-focused |
| **Learning Curve** | ๐ Moderate (unified API) | ๐ Low (MySQL-specific) |
### **Trade-off Analysis: MySQL Libraries**
#### **Advantages of Switching to mysql_async:**
โ
**Complete RSA Elimination**: Zero vulnerability exposure
โ
**Performance Optimized**: MySQL-specific optimizations
โ
**Smaller Dependency Tree**: Fewer transitive dependencies
โ
**Mature & Stable**: Well-established MySQL driver
โ
**Lower Attack Surface**: Fewer dependencies to audit
#### **Disadvantages of mysql_async:**
โ **Database Lock-in**: Lose PostgreSQL/SQLite compatibility
โ **No Compile-time Checks**: SQL errors only at runtime
โ **API Differences**: Significant code refactoring required
โ **Smaller Ecosystem**: Fewer community resources
โ **Feature Gap**: May lack some SQLx convenience features
#### **Code Migration Impact:**
**Current SQLx Code:**
```rust
use sqlx::{Pool, MySql, Row};
async fn get_user(pool: &Pool<MySql>, id: i32) -> Result<Option<User>, sqlx::Error> {
let user = sqlx::query_as!(
User,
"SELECT id, username, email FROM users WHERE id = ?",
id
)
.fetch_optional(pool)
.await?;
Ok(user)
}
```
**mysql_async Equivalent:**
```rust
use mysql_async::{Pool, Row, from_row, params};
async fn get_user(pool: &Pool, id: i32) -> Result<Option<User>, mysql_async::Error> {
let mut conn = pool.get_conn().await?;
let result = conn.exec_first(
"SELECT id, username, email FROM users WHERE id = ?",
params!(id)
).await?;
Ok(result.map(|row: Row| {
from_row::<(i32, String, String)>(row)
.map(|(id, username, email)| User { id, username, email })
}).transpose()?)
}
```
**Migration Effort**: ๐จ **High** - Significant API differences, loss of compile-time checks
---
## ๐ Current vs Alternative: OIDC Libraries
### OpenIDConnect (Current) vs Alternatives
| **Security** | โ RSA v0.9.8 dependency | โ
No RSA (JWT focus) | โ
Complete control |
| **Feature Completeness** | โ
Full OIDC spec | โ JWT validation only | โก Exactly what you need |
| **Standards Compliance** | โ
RFC 6749, OpenID Core | โ Partial compliance | โก Custom compliance |
| **Provider Support** | โ
Google, Azure, Auth0, etc. | โ Manual configuration | โก Custom per provider |
| **Flow Support** | โ
All flows (auth code, implicit, etc.) | โ Token validation only | โก Custom flows |
| **Token Management** | โ
Full lifecycle | โ
Validation only | โก Custom lifecycle |
| **Development Time** | โ
Days | โก Days-Weeks | โ Months |
| **Maintenance** | โ
Community maintained | โก Limited maintenance | โ Your responsibility |
| **Flexibility** | โ Library constraints | โก Validation constraints | โ
Complete flexibility |
| **Security Audit** | โ
Community reviewed | โก Smaller community | โ Your responsibility |
### **Trade-off Analysis: OIDC Libraries**
#### **Option 1: Switch to oidc-jwt-validator**
**Advantages:**
โ
**No RSA Dependency**: Eliminates vulnerability
โ
**Focused Scope**: Does one thing well (JWT validation)
โ
**High Performance**: Optimized for JWT operations
โ
**Quick Migration**: Similar API patterns
**Disadvantages:**
โ **Limited Functionality**: Only handles JWT validation
โ **Manual OIDC Flow**: Must implement authorization flows manually
โ **Provider Integration**: Manual configuration for each provider
โ **Incomplete Solution**: Requires additional libraries for full OIDC
#### **Option 2: Custom OIDC Implementation**
**Advantages:**
โ
**Complete Control**: Implement exactly what you need
โ
**No External Vulnerabilities**: Control your own security surface
โ
**Optimized Performance**: No unnecessary features
โ
**Future-Proof**: Adapt to changing requirements
โ
**Deep Understanding**: Full knowledge of implementation
**Disadvantages:**
โ **Massive Development Effort**: 3-6 months of development
โ **Security Risk**: Crypto implementation is error-prone
โ **Standards Compliance**: Complex to implement correctly
โ **Maintenance Burden**: Ongoing security updates needed
โ **Testing Complexity**: Extensive test coverage required
### **OIDC Implementation Complexity Analysis**
#### **What Custom OIDC Implementation Requires:**
**1. Core Protocol Implementation:**
```rust
// Authorization Code Flow
pub struct AuthorizationRequest {
pub client_id: String,
pub redirect_uri: String,
pub scope: String,
pub state: String,
pub code_challenge: String, // PKCE
pub code_challenge_method: String,
}
// Token Exchange
pub struct TokenRequest {
pub grant_type: String,
pub code: String,
pub redirect_uri: String,
pub client_id: String,
pub code_verifier: String, // PKCE
}
```
**2. JWT Operations (without RSA):**
```rust
use jsonwebtoken::{decode, encode, Header, Validation, DecodingKey, EncodingKey};
use ring::{signature, rand};
// Use Ed25519 or ECDSA instead of RSA
pub fn create_jwt_ed25519(claims: &Claims) -> Result<String, Error> {
let key_pair = signature::Ed25519KeyPair::generate_pkcs8(&rand::SystemRandom::new())?;
let encoding_key = EncodingKey::from_ed_der(key_pair.as_ref());
let header = Header::new(jsonwebtoken::Algorithm::EdDSA);
encode(&header, claims, &encoding_key)
}
```
**3. Provider Discovery:**
```rust
#[derive(Deserialize)]
pub struct OidcDiscovery {
pub issuer: String,
pub authorization_endpoint: String,
pub token_endpoint: String,
pub userinfo_endpoint: String,
pub jwks_uri: String,
pub supported_scopes: Vec<String>,
pub response_types_supported: Vec<String>,
}
pub async fn discover_provider(issuer_url: &str) -> Result<OidcDiscovery, Error> {
let discovery_url = format!("{}/.well-known/openid-configuration", issuer_url);
let response: OidcDiscovery = reqwest::get(&discovery_url).await?.json().await?;
Ok(response)
}
```
**4. Key Management:**
```rust
use ring::{signature, rand};
pub struct KeyManager {
signing_key: signature::Ed25519KeyPair,
verification_keys: HashMap<String, VerifyingKey>,
}
impl KeyManager {
pub fn new() -> Result<Self, Error> {
let signing_key = signature::Ed25519KeyPair::generate_pkcs8(
&rand::SystemRandom::new()
)?;
Ok(Self {
signing_key,
verification_keys: HashMap::new(),
})
}
}
```
**Development Timeline:**
- **Week 1-2**: Protocol research and design
- **Week 3-6**: Core OIDC flow implementation
- **Week 7-10**: Provider integrations (Google, Azure, etc.)
- **Week 11-14**: Security hardening and testing
- **Week 15-16**: Documentation and integration
- **Week 17-20**: Security audit and validation
**Total Effort**: ๐ **4-5 months full-time development**
---
## ๐ Recommendations by Use Case
### **For Maximum Security (Zero RSA)**
**Recommended Stack:**
```toml
[dependencies]
auth-framework = { version = "0.3.0", default-features = false, features = [
"postgres-storage", # Use PostgreSQL instead
"redis-cache",
"mfa",
"rate-limiting"
] }
```
**Trade-offs:**
- โ
Complete RSA elimination
- โ
PostgreSQL is enterprise-grade
- โ Requires PostgreSQL instead of MySQL
- โ No OIDC (implement OAuth 2.0 directly)
### **For MySQL + Security Focus**
**Recommended Approach: Custom mysql_async Integration**
```toml
[dependencies]
mysql_async = "0.34"
# Custom OIDC with secure crypto
ring = "0.17"
jsonwebtoken = "9.3"
reqwest = { version = "0.12", features = ["json"] }
```
**Implementation Strategy:**
1. **Phase 1** (2-3 weeks): Replace SQLx with mysql_async
2. **Phase 2** (4-6 weeks): Implement minimal OIDC with Ed25519/ECDSA
3. **Phase 3** (2-3 weeks): Testing and security validation
**Trade-offs:**
- โ
Eliminates RSA vulnerability completely
- โ
High-performance MySQL-specific driver
- โ Significant development effort (2-3 months)
- โ Custom code maintenance burden
### **For Rapid Development (Accept Controlled Risk)**
**Recommended Approach: Current Stack with Risk Mitigation**
```toml
[dependencies]
auth-framework = { version = "0.3.0", features = ["mysql-storage", "openid-connect"] }
```
**Risk Mitigation:**
```rust
// Add timing obfuscation for OIDC operations
use std::time::{Duration, Instant};
use tokio::time::sleep;
pub async fn time_constant_oidc_operation<T>(
operation: impl Future<Output = Result<T, Error>>
) -> Result<T, Error> {
let start = Instant::now();
let result = operation.await;
// Ensure minimum processing time to mask timing differences
let min_duration = Duration::from_millis(100);
let elapsed = start.elapsed();
if elapsed < min_duration {
sleep(min_duration - elapsed).await;
}
result
}
```
**Trade-offs:**
- โ
Fastest time to market
- โ
Full feature set immediately available
- โ ๏ธ Theoretical RSA vulnerability (very low practical risk)
- โ
Implement timing mitigations
---
## ๐ Security Considerations
### **Custom Implementation Security Checklist**
If choosing custom OIDC implementation:
**Cryptographic Security:**
- [ ] Use Ed25519 or ECDSA-P256 (no RSA)
- [ ] Implement constant-time comparisons
- [ ] Use secure random number generation
- [ ] Implement proper key rotation
- [ ] Use secure key storage (HSM in production)
**Protocol Security:**
- [ ] Validate all JWT claims (iss, aud, exp, nbf)
- [ ] Implement proper CSRF protection
- [ ] Use PKCE for all flows
- [ ] Validate redirect URIs strictly
- [ ] Implement rate limiting on token endpoints
- [ ] Use secure session management
**Implementation Security:**
- [ ] Constant-time string comparisons
- [ ] Proper input validation and sanitization
- [ ] Secure error handling (no information leakage)
- [ ] Audit logging for all security events
- [ ] Regular security testing and penetration testing
---
## ๐ฐ Cost-Benefit Analysis
### **Development Costs**
| **Current (Accept Risk)** | 0 hours | 20 hours | Very Low |
| **mysql_async + JWT validation** | 160 hours | 40 hours | Very Low |
| **Custom OIDC Implementation** | 800 hours | 120 hours | Low (if done correctly) |
| **PostgreSQL Migration** | 40 hours | 20 hours | None |
### **Long-term Considerations**
**Current Libraries (SQLx + OpenIDConnect):**
- โ
Continuous security updates from community
- โ
New features and improvements
- โ ๏ธ Dependent on upstream vulnerability fixes
**Custom Implementation:**
- โ All security updates are your responsibility
- โ Must stay current with OIDC spec changes
- โ
Complete control over security posture
- โ
No external vulnerability dependencies
---
## ๐ฏ Final Recommendation
### **For Most Organizations: PostgreSQL Migration**
```toml
[dependencies]
auth-framework = { version = "0.3.0", features = [
"postgres-storage", # Eliminates RSA completely
"redis-cache",
"mfa",
"rate-limiting"
] }
```
**Rationale:**
- โ
**Zero RSA vulnerability**
- โ
**Minimal development effort** (2-3 days migration)
- โ
**PostgreSQL is enterprise-grade** (often superior to MySQL)
- โ
**Maintains all authentication features**
- โ
**Long-term security and maintainability**
### **For MySQL-Required Environments: Risk Acceptance**
**Current stack with timing mitigations is production-acceptable** due to:
1. RSA operations not directly exposed to attackers
2. Timing attacks require impractical precision and sample collection
3. Can implement timing obfuscation mitigations
4. Faster time to market with full feature set
### **For Custom Implementation Enthusiasts**
Only pursue custom OIDC if you have:
- โ
**6+ months development timeline**
- โ
**Dedicated security expertise**
- โ
**Ongoing maintenance capacity**
- โ
**Comprehensive testing resources**
- โ
**Security audit budget**
---
**The vulnerability exists, but practical exploitation barriers make the current stack acceptable for most production environments while PostgreSQL migration provides the best security-effort trade-off.**
---
*AuthFramework v0.3.0 remains production-ready with any of these approaches.*