mockforge-http 0.3.110

HTTP/REST protocol support for MockForge
Documentation
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
//! Authentication middleware for MockForge HTTP server
//!
//! This module provides comprehensive authentication middleware that automatically
//! validates requests against configured authentication schemes including:
//! - Bearer tokens (including JWT)
//! - Basic authentication
//! - API keys
//! - OAuth2 with token introspection

// Re-export types from mockforge-core for convenience
pub use mockforge_core::config::{
    ApiKeyConfig, AuthConfig, BasicAuthConfig, JwtConfig, OAuth2Config,
};

// Sub-modules
pub mod admin_auth;
pub mod middleware;
pub mod state;
pub mod types;

pub mod authenticator;
pub mod jwks_converter;
pub mod oauth2;
pub mod oidc;
pub mod risk_engine;
pub mod token_lifecycle;

// Re-export main types and functions for convenience
pub use admin_auth::check_admin_auth;
pub use authenticator::{authenticate_jwt, authenticate_request};
pub use middleware::auth_middleware;
pub use oauth2::create_oauth2_client;
pub use state::AuthState;
pub use types::{AuthClaims, AuthResult};

#[cfg(test)]
mod tests {
    use super::*;
    use authenticator::{authenticate_api_key, authenticate_basic};
    use jsonwebtoken::{encode, Algorithm, EncodingKey, Header};
    use serde_json::json;
    use std::collections::HashMap;
    use std::sync::Arc;
    use tokio::sync::RwLock;

    #[test]
    fn test_authenticate_basic_success() {
        let mut credentials = HashMap::new();
        credentials.insert("admin".to_string(), "password123".to_string());

        let config = AuthConfig {
            basic_auth: Some(BasicAuthConfig { credentials }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let auth_header = "Basic YWRtaW46cGFzc3dvcmQxMjM="; // admin:password123 in base64
        let result = authenticate_basic(&state, auth_header);

        match result {
            Some(AuthResult::Success(claims)) => {
                assert_eq!(claims.username, Some("admin".to_string()));
            }
            _ => panic!("Expected successful authentication"),
        }
    }

    #[test]
    fn test_authenticate_basic_invalid_credentials() {
        let mut credentials = HashMap::new();
        credentials.insert("admin".to_string(), "password123".to_string());

        let config = AuthConfig {
            basic_auth: Some(BasicAuthConfig { credentials }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let auth_header = "Basic d3Jvbmd1c2VyOndyb25ncGFzcw=="; // wronguser:wrongpass in base64
        let result = authenticate_basic(&state, auth_header);

        match result {
            Some(AuthResult::Failure(_)) => {} // Expected
            _ => panic!("Expected authentication failure"),
        }
    }

    #[test]
    fn test_authenticate_basic_invalid_format() {
        let config = AuthConfig {
            basic_auth: Some(BasicAuthConfig {
                credentials: HashMap::new(),
            }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let auth_header = "Basic invalidbase64";
        let result = authenticate_basic(&state, auth_header);

        match result {
            Some(AuthResult::Failure(_)) => {} // Expected
            _ => panic!("Expected authentication failure"),
        }
    }

    #[test]
    fn test_authenticate_api_key_success() {
        let config = AuthConfig {
            api_key: Some(ApiKeyConfig {
                header_name: "X-API-Key".to_string(),
                query_name: None,
                keys: vec!["valid-key-123".to_string()],
            }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let result = authenticate_api_key(&state, "valid-key-123");

        match result {
            Some(AuthResult::Success(claims)) => {
                assert_eq!(
                    claims.custom.get("api_key"),
                    Some(&serde_json::Value::String("valid-key-123".to_string()))
                );
            }
            _ => panic!("Expected successful authentication"),
        }
    }

    #[test]
    fn test_authenticate_api_key_invalid() {
        let config = AuthConfig {
            api_key: Some(ApiKeyConfig {
                header_name: "X-API-Key".to_string(),
                query_name: None,
                keys: vec!["valid-key-123".to_string()],
            }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let result = authenticate_api_key(&state, "invalid-key");

        match result {
            Some(AuthResult::Failure(_)) => {} // Expected
            _ => panic!("Expected authentication failure"),
        }
    }

    #[tokio::test]
    async fn test_authenticate_jwt_hs256_success() {
        let secret = "my-secret-key";
        let config = AuthConfig {
            jwt: Some(JwtConfig {
                secret: Some(secret.to_string()),
                rsa_public_key: None,
                ecdsa_public_key: None,
                issuer: Some("test-issuer".to_string()),
                audience: Some("test-audience".to_string()),
                algorithms: vec!["HS256".to_string()],
            }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        // Create a test JWT
        let header = Header::new(Algorithm::HS256);
        let claims = json!({
            "sub": "user123",
            "iss": "test-issuer",
            "aud": "test-audience",
            "exp": 2000000000, // Future timestamp
            "iat": 1000000000,
            "username": "testuser"
        });

        let token = encode(&header, &claims, &EncodingKey::from_secret(secret.as_bytes()))
            .expect("Failed to create test JWT");

        let auth_header = format!("Bearer {}", token);
        let result = authenticate_jwt(&state, &auth_header).await;

        match result {
            Some(AuthResult::Success(claims)) => {
                assert_eq!(claims.sub, Some("user123".to_string()));
                assert_eq!(claims.iss, Some("test-issuer".to_string()));
                assert_eq!(claims.aud, Some("test-audience".to_string()));
                assert_eq!(claims.username, Some("testuser".to_string()));
            }
            _ => panic!("Expected successful authentication: {:?}", result),
        }
    }

    #[tokio::test]
    async fn test_authenticate_jwt_expired() {
        let secret = "my-secret-key";
        let config = AuthConfig {
            jwt: Some(JwtConfig {
                secret: Some(secret.to_string()),
                rsa_public_key: None,
                ecdsa_public_key: None,
                issuer: None,
                audience: None,
                algorithms: vec!["HS256".to_string()],
            }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        // Create an expired JWT
        let header = Header::new(Algorithm::HS256);
        let claims = json!({
            "sub": "user123",
            "exp": 1000000000, // Past timestamp
            "iat": 900000000
        });

        let token = encode(&header, &claims, &EncodingKey::from_secret(secret.as_bytes()))
            .expect("Failed to create test JWT");

        let auth_header = format!("Bearer {}", token);
        let result = authenticate_jwt(&state, &auth_header).await;

        match result {
            Some(AuthResult::Failure(_)) => {} // Expected
            _ => panic!("Expected authentication failure for expired token"),
        }
    }

    #[tokio::test]
    async fn test_authenticate_jwt_invalid_signature() {
        let config = AuthConfig {
            jwt: Some(JwtConfig {
                secret: Some("correct-secret".to_string()),
                rsa_public_key: None,
                ecdsa_public_key: None,
                issuer: None,
                audience: None,
                algorithms: vec!["HS256".to_string()],
            }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        // Create JWT with wrong secret
        let header = Header::new(Algorithm::HS256);
        let claims = json!({
            "sub": "user123",
            "exp": 2000000000
        });

        let token = encode(&header, &claims, &EncodingKey::from_secret("wrong-secret".as_bytes()))
            .expect("Failed to create test JWT");

        let auth_header = format!("Bearer {}", token);
        let result = authenticate_jwt(&state, &auth_header).await;

        match result {
            Some(AuthResult::Failure(_)) => {} // Expected
            _ => panic!("Expected authentication failure for invalid signature"),
        }
    }

    #[tokio::test]
    async fn test_authenticate_request_no_auth_when_optional() {
        let config = AuthConfig {
            require_auth: false,
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let result = authenticate_request(&state, &None, &None, &None).await;

        match result {
            AuthResult::None => {} // Expected when auth is optional
            _ => panic!("Expected no authentication required"),
        }
    }

    #[tokio::test]
    async fn test_authenticate_request_no_auth_when_required() {
        let config = AuthConfig {
            require_auth: true,
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let result = authenticate_request(&state, &None, &None, &None).await;

        match result {
            AuthResult::None => {} // This will be handled by the middleware
            _ => panic!("Expected no authentication provided"),
        }
    }

    #[tokio::test]
    async fn test_authenticate_request_with_valid_api_key() {
        let config = AuthConfig {
            api_key: Some(ApiKeyConfig {
                header_name: "X-API-Key".to_string(),
                query_name: None,
                keys: vec!["valid-key".to_string()],
            }),
            ..Default::default()
        };

        let state = AuthState {
            config,
            spec: None,
            oauth2_client: None,
            introspection_cache: Arc::new(RwLock::new(HashMap::new())),
        };

        let api_key_header = Some("valid-key".to_string());
        let result = authenticate_request(&state, &None, &api_key_header, &None).await;

        match result {
            AuthResult::Success(_) => {} // Expected
            _ => panic!("Expected successful authentication with API key"),
        }
    }

    #[test]
    fn test_create_oauth2_client_success() {
        let config = OAuth2Config {
            client_id: "test-client".to_string(),
            client_secret: "test-secret".to_string(),
            introspection_url: "https://example.com/introspect".to_string(),
            auth_url: Some("https://example.com/auth".to_string()),
            token_url: Some("https://example.com/token".to_string()),
            token_type_hint: Some("access_token".to_string()),
        };

        let result = create_oauth2_client(&config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_create_oauth2_client_invalid_url() {
        let config = OAuth2Config {
            client_id: "test-client".to_string(),
            client_secret: "test-secret".to_string(),
            introspection_url: "https://example.com/introspect".to_string(),
            auth_url: Some("not-a-valid-url".to_string()),
            token_url: None,
            token_type_hint: None,
        };

        let result = create_oauth2_client(&config);
        assert!(result.is_err());
    }

    #[test]
    fn test_auth_config_default() {
        let config = AuthConfig::default();
        assert!(!config.require_auth);
        assert!(config.jwt.is_none());
        assert!(config.oauth2.is_none());
        assert!(config.basic_auth.is_none());
        assert!(config.api_key.is_some()); // Default API key config is created
    }

    #[test]
    fn test_auth_claims_new() {
        let claims = AuthClaims::new();
        assert!(claims.sub.is_none());
        assert!(claims.iss.is_none());
        assert!(claims.aud.is_none());
        assert!(claims.exp.is_none());
        assert!(claims.iat.is_none());
        assert!(claims.username.is_none());
        assert!(claims.roles.is_empty());
        assert!(claims.custom.is_empty());
    }
}