auth-framework 0.4.0

A comprehensive, production-ready authentication and authorization framework for Rust applications
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# 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


| **Aspect** | **SQLx v0.8.6** | **mysql_async v0.34+** |
|------------|------------------|-------------------------|
| **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


| **Aspect** | **openidconnect v4.0.1** | **oidc-jwt-validator** | **Custom OIDC** |
|------------|---------------------------|-------------------------|------------------|
| **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**


| **Approach** | **Initial Development** | **Maintenance (Annual)** | **Security Risk** |
|--------------|------------------------|---------------------------|-------------------|
| **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.*