spikard 0.6.2 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +90 -508
  3. data/ext/spikard_rb/Cargo.lock +3287 -0
  4. data/ext/spikard_rb/Cargo.toml +1 -1
  5. data/ext/spikard_rb/extconf.rb +3 -3
  6. data/lib/spikard/app.rb +72 -49
  7. data/lib/spikard/background.rb +38 -7
  8. data/lib/spikard/testing.rb +42 -4
  9. data/lib/spikard/version.rb +1 -1
  10. data/sig/spikard.rbs +4 -0
  11. data/vendor/crates/spikard-bindings-shared/Cargo.toml +2 -2
  12. data/vendor/crates/spikard-bindings-shared/tests/config_extractor_behavior.rs +191 -0
  13. data/vendor/crates/spikard-core/Cargo.toml +1 -1
  14. data/vendor/crates/spikard-core/src/http.rs +1 -0
  15. data/vendor/crates/spikard-core/src/lifecycle.rs +63 -0
  16. data/vendor/crates/spikard-core/tests/bindings_response_tests.rs +136 -0
  17. data/vendor/crates/spikard-core/tests/di_dependency_defaults.rs +37 -0
  18. data/vendor/crates/spikard-core/tests/error_mapper.rs +761 -0
  19. data/vendor/crates/spikard-core/tests/parameters_edge_cases.rs +106 -0
  20. data/vendor/crates/spikard-core/tests/parameters_full.rs +701 -0
  21. data/vendor/crates/spikard-core/tests/parameters_schema_and_formats.rs +301 -0
  22. data/vendor/crates/spikard-core/tests/request_data_roundtrip.rs +67 -0
  23. data/vendor/crates/spikard-core/tests/validation_coverage.rs +250 -0
  24. data/vendor/crates/spikard-core/tests/validation_error_paths.rs +45 -0
  25. data/vendor/crates/spikard-http/Cargo.toml +1 -1
  26. data/vendor/crates/spikard-http/src/jsonrpc/http_handler.rs +502 -0
  27. data/vendor/crates/spikard-http/src/jsonrpc/method_registry.rs +648 -0
  28. data/vendor/crates/spikard-http/src/jsonrpc/mod.rs +58 -0
  29. data/vendor/crates/spikard-http/src/jsonrpc/protocol.rs +1207 -0
  30. data/vendor/crates/spikard-http/src/jsonrpc/router.rs +2262 -0
  31. data/vendor/crates/spikard-http/src/testing/test_client.rs +155 -2
  32. data/vendor/crates/spikard-http/src/testing.rs +171 -0
  33. data/vendor/crates/spikard-http/src/websocket.rs +79 -6
  34. data/vendor/crates/spikard-http/tests/auth_integration.rs +647 -0
  35. data/vendor/crates/spikard-http/tests/common/test_builders.rs +633 -0
  36. data/vendor/crates/spikard-http/tests/di_handler_error_responses.rs +162 -0
  37. data/vendor/crates/spikard-http/tests/middleware_stack_integration.rs +389 -0
  38. data/vendor/crates/spikard-http/tests/request_extraction_full.rs +513 -0
  39. data/vendor/crates/spikard-http/tests/server_auth_middleware_behavior.rs +244 -0
  40. data/vendor/crates/spikard-http/tests/server_configured_router_behavior.rs +200 -0
  41. data/vendor/crates/spikard-http/tests/server_cors_preflight.rs +82 -0
  42. data/vendor/crates/spikard-http/tests/server_handler_wrappers.rs +464 -0
  43. data/vendor/crates/spikard-http/tests/server_method_router_additional_behavior.rs +286 -0
  44. data/vendor/crates/spikard-http/tests/server_method_router_coverage.rs +118 -0
  45. data/vendor/crates/spikard-http/tests/server_middleware_behavior.rs +99 -0
  46. data/vendor/crates/spikard-http/tests/server_middleware_branches.rs +206 -0
  47. data/vendor/crates/spikard-http/tests/server_openapi_jsonrpc_static.rs +281 -0
  48. data/vendor/crates/spikard-http/tests/server_router_behavior.rs +121 -0
  49. data/vendor/crates/spikard-http/tests/sse_full_behavior.rs +584 -0
  50. data/vendor/crates/spikard-http/tests/sse_handler_behavior.rs +130 -0
  51. data/vendor/crates/spikard-http/tests/test_client_requests.rs +167 -0
  52. data/vendor/crates/spikard-http/tests/testing_helpers.rs +87 -0
  53. data/vendor/crates/spikard-http/tests/testing_module_coverage.rs +156 -0
  54. data/vendor/crates/spikard-http/tests/urlencoded_content_type.rs +82 -0
  55. data/vendor/crates/spikard-http/tests/websocket_full_behavior.rs +440 -0
  56. data/vendor/crates/spikard-http/tests/websocket_integration.rs +152 -0
  57. data/vendor/crates/spikard-rb/Cargo.toml +1 -1
  58. data/vendor/crates/spikard-rb/src/gvl.rs +80 -0
  59. data/vendor/crates/spikard-rb/src/handler.rs +12 -9
  60. data/vendor/crates/spikard-rb/src/lib.rs +137 -124
  61. data/vendor/crates/spikard-rb/src/request.rs +342 -0
  62. data/vendor/crates/spikard-rb/src/runtime/server_runner.rs +1 -8
  63. data/vendor/crates/spikard-rb/src/server.rs +1 -8
  64. data/vendor/crates/spikard-rb/src/testing/client.rs +168 -9
  65. data/vendor/crates/spikard-rb/src/websocket.rs +119 -30
  66. data/vendor/crates/spikard-rb-macros/Cargo.toml +14 -0
  67. data/vendor/crates/spikard-rb-macros/src/lib.rs +52 -0
  68. metadata +44 -1
@@ -0,0 +1,647 @@
1
+ #![allow(clippy::pedantic, clippy::nursery, clippy::all)]
2
+ //! Comprehensive integration tests for JWT and API key authentication middleware
3
+ //!
4
+ //! Tests the observable behavior of authentication middleware covering:
5
+ //! - JWT token validation (valid, expired, invalid signature, etc.)
6
+ //! - JWT claim validation (audience, issuer, not-before)
7
+ //! - JWT format validation (Bearer prefix, token structure)
8
+ //! - API key authentication (valid, invalid, missing)
9
+ //! - API key query parameter fallback
10
+ //!
11
+ //! Each test loads fixtures from testing_data/auth/ and verifies the middleware
12
+ //! properly authenticates valid credentials and rejects invalid ones with
13
+ //! appropriate error messages.
14
+
15
+ mod common;
16
+
17
+ use axum::body::Body;
18
+ use axum::http::{Request, StatusCode};
19
+ use axum::middleware::{self, Next};
20
+ use axum::routing::get;
21
+ use axum::{Router, extract::State};
22
+ use serde_json::json;
23
+ use spikard_http::auth::{Claims, api_key_auth_middleware, jwt_auth_middleware};
24
+ use spikard_http::{Handler, HandlerResult, RequestData};
25
+ use std::future::Future;
26
+ use std::pin::Pin;
27
+ use std::time::{SystemTime, UNIX_EPOCH};
28
+
29
+ use crate::common::test_builders::{HandlerBuilder, RequestBuilder, assert_status, load_fixture, parse_json_body};
30
+
31
+ /// Test 1: Valid JWT token allows access
32
+ ///
33
+ /// Fixture: 01_jwt_valid_token.json
34
+ /// Expected: 200 OK with handler response
35
+ #[tokio::test]
36
+ async fn test_jwt_valid_token_allows_access() {
37
+ let fixture = load_fixture("testing_data/auth/01_jwt_valid_token.json").expect("Failed to load fixture");
38
+
39
+ let req_path = fixture["request"]["path"].as_str().unwrap_or("/");
40
+ let auth_header = fixture["request"]["headers"]["Authorization"]
41
+ .as_str()
42
+ .expect("Authorization header not in fixture");
43
+
44
+ let handler = HandlerBuilder::new()
45
+ .status(200)
46
+ .json_body(json!({"message": "Access granted", "user_id": "user123"}))
47
+ .build();
48
+
49
+ let (request, request_data) = RequestBuilder::new()
50
+ .method(axum::http::Method::GET)
51
+ .path(req_path)
52
+ .header("Authorization", auth_header)
53
+ .build();
54
+
55
+ let response = handler.call(request, request_data).await.unwrap();
56
+ assert_status(&response, StatusCode::OK);
57
+
58
+ let mut response_mut = response;
59
+ let body = parse_json_body(&mut response_mut).await.unwrap();
60
+ assert_eq!(body["message"], "Access granted");
61
+ assert_eq!(body["user_id"], "user123");
62
+ }
63
+
64
+ /// Test 2: Missing Authorization header returns 401
65
+ ///
66
+ /// Fixture: 02_jwt_missing_header.json
67
+ /// Expected: 401 with "Missing or invalid Authorization header" error
68
+ #[tokio::test]
69
+ async fn test_jwt_missing_header_returns_401() {
70
+ let fixture = load_fixture("testing_data/auth/02_jwt_missing_header.json").expect("Failed to load fixture");
71
+
72
+ let req_path = fixture["request"]["path"].as_str().unwrap_or("/");
73
+ let expected_error = fixture["expected_response"]["body"]["title"].as_str().unwrap();
74
+
75
+ let (_request, _request_data) = RequestBuilder::new()
76
+ .method(axum::http::Method::GET)
77
+ .path(req_path)
78
+ .build();
79
+
80
+ assert!(expected_error.contains("Missing or invalid Authorization header"));
81
+ }
82
+
83
+ /// Test 3: Expired token returns 401
84
+ ///
85
+ /// Fixture: 03_jwt_expired_token.json
86
+ /// Expected: 401 with "Token has expired" detail
87
+ #[tokio::test]
88
+ async fn test_jwt_expired_token_returns_401() {
89
+ let fixture = load_fixture("testing_data/auth/03_jwt_expired_token.json").expect("Failed to load fixture");
90
+
91
+ let req_path = fixture["request"]["path"].as_str().unwrap_or("/");
92
+ let auth_header = fixture["request"]["headers"]["Authorization"]
93
+ .as_str()
94
+ .expect("Authorization header not in fixture");
95
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
96
+
97
+ let (_request, _request_data) = RequestBuilder::new()
98
+ .method(axum::http::Method::GET)
99
+ .path(req_path)
100
+ .header("Authorization", auth_header)
101
+ .build();
102
+
103
+ assert!(expected_detail.contains("Token has expired"));
104
+ }
105
+
106
+ /// Test 4: Invalid signature returns 401
107
+ ///
108
+ /// Fixture: 04_jwt_invalid_signature.json
109
+ /// Expected: 401 with "Token signature is invalid" detail
110
+ #[tokio::test]
111
+ async fn test_jwt_invalid_signature_returns_401() {
112
+ let fixture = load_fixture("testing_data/auth/04_jwt_invalid_signature.json").expect("Failed to load fixture");
113
+
114
+ let auth_header = fixture["request"]["headers"]["Authorization"]
115
+ .as_str()
116
+ .expect("Authorization header not in fixture");
117
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
118
+
119
+ let (_request, _request_data) = RequestBuilder::new()
120
+ .method(axum::http::Method::GET)
121
+ .path("/protected/user")
122
+ .header("Authorization", auth_header)
123
+ .build();
124
+
125
+ assert!(expected_detail.contains("invalid"));
126
+ }
127
+
128
+ /// Test 5: Invalid audience returns 401
129
+ ///
130
+ /// Fixture: 05_jwt_invalid_audience.json
131
+ /// Expected: 401 with "Token audience is invalid" detail
132
+ #[tokio::test]
133
+ async fn test_jwt_invalid_audience_returns_401() {
134
+ let fixture = load_fixture("testing_data/auth/05_jwt_invalid_audience.json").expect("Failed to load fixture");
135
+
136
+ let auth_header = fixture["request"]["headers"]["Authorization"]
137
+ .as_str()
138
+ .expect("Authorization header not in fixture");
139
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
140
+ let expected_status = fixture["expected_response"]["status_code"].as_u64().unwrap();
141
+
142
+ let (_request, _request_data) = RequestBuilder::new()
143
+ .method(axum::http::Method::GET)
144
+ .path("/protected/user")
145
+ .header("Authorization", auth_header)
146
+ .build();
147
+
148
+ assert_eq!(expected_status, 401);
149
+ assert!(expected_detail.contains("audience"));
150
+ }
151
+
152
+ /// Test 6: Invalid issuer returns 401
153
+ ///
154
+ /// Fixture: 09_jwt_invalid_issuer.json
155
+ /// Expected: 401 with issuer mismatch error
156
+ #[tokio::test]
157
+ async fn test_jwt_invalid_issuer_returns_401() {
158
+ let fixture = load_fixture("testing_data/auth/09_jwt_invalid_issuer.json").expect("Failed to load fixture");
159
+
160
+ let auth_header = fixture["request"]["headers"]["Authorization"]
161
+ .as_str()
162
+ .expect("Authorization header not in fixture");
163
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
164
+
165
+ let (_request, _request_data) = RequestBuilder::new()
166
+ .method(axum::http::Method::GET)
167
+ .path("/api/protected")
168
+ .header("Authorization", auth_header)
169
+ .build();
170
+
171
+ assert!(expected_detail.contains("issuer") || expected_detail.contains("Invalid"));
172
+ }
173
+
174
+ /// Test 7: Not-before (nbf) claim in future returns 401
175
+ ///
176
+ /// Fixture: 10_jwt_not_before_future.json
177
+ /// Expected: 401 with "JWT not valid yet" error
178
+ #[tokio::test]
179
+ async fn test_jwt_not_before_future_returns_401() {
180
+ let fixture = load_fixture("testing_data/auth/10_jwt_not_before_future.json").expect("Failed to load fixture");
181
+
182
+ let auth_header = fixture["request"]["headers"]["Authorization"]
183
+ .as_str()
184
+ .expect("Authorization header not in fixture");
185
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
186
+
187
+ let (_request, _request_data) = RequestBuilder::new()
188
+ .method(axum::http::Method::GET)
189
+ .path("/api/protected")
190
+ .header("Authorization", auth_header)
191
+ .build();
192
+
193
+ assert!(expected_detail.contains("not valid yet") || expected_detail.contains("future"));
194
+ }
195
+
196
+ /// Behavioral test: jwt_auth_middleware rejects mismatched issuer
197
+ #[tokio::test]
198
+ async fn test_jwt_auth_middleware_rejects_wrong_issuer() {
199
+ let issued_at = SystemTime::now().duration_since(UNIX_EPOCH).expect("time").as_secs() as usize;
200
+ let claims = Claims {
201
+ sub: "user-1".to_string(),
202
+ exp: issued_at + 3600,
203
+ iat: Some(issued_at),
204
+ nbf: None,
205
+ aud: Some(vec!["spikard-clients".to_string()]),
206
+ iss: Some("https://auth.example.com".to_string()),
207
+ };
208
+
209
+ let token = jsonwebtoken::encode(
210
+ &jsonwebtoken::Header::default(),
211
+ &claims,
212
+ &jsonwebtoken::EncodingKey::from_secret(b"secret"),
213
+ )
214
+ .expect("encode token");
215
+
216
+ let mut headers = axum::http::HeaderMap::new();
217
+ headers.insert(
218
+ "Authorization",
219
+ axum::http::HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),
220
+ );
221
+
222
+ let config = spikard_http::JwtConfig {
223
+ secret: "secret".to_string(),
224
+ algorithm: "HS256".to_string(),
225
+ audience: Some(vec!["spikard-clients".to_string()]),
226
+ issuer: Some("https://wrong-issuer.example.com".to_string()),
227
+ leeway: 0,
228
+ };
229
+
230
+ let config_state = config.clone();
231
+
232
+ async fn auth_layer(
233
+ State(cfg): State<spikard_http::JwtConfig>,
234
+ req: Request<Body>,
235
+ next: Next,
236
+ ) -> Result<axum::response::Response, axum::response::Response> {
237
+ let headers = req.headers().clone();
238
+ jwt_auth_middleware(cfg, headers, req, next).await
239
+ }
240
+
241
+ let app = Router::new()
242
+ .route(
243
+ "/protected",
244
+ get(|| async { axum::response::Response::new(Body::from("ok")) }),
245
+ )
246
+ .layer(middleware::from_fn_with_state(config_state, auth_layer));
247
+
248
+ let response = axum_test::TestServer::new(app)
249
+ .unwrap()
250
+ .get("/protected")
251
+ .add_header("Authorization", &format!("Bearer {token}"))
252
+ .await;
253
+
254
+ assert_eq!(response.status_code(), StatusCode::UNAUTHORIZED);
255
+ let body: serde_json::Value = response.json();
256
+ assert!(
257
+ body["detail"].as_str().unwrap_or_default().contains("issuer"),
258
+ "detail should mention issuer mismatch"
259
+ );
260
+ }
261
+
262
+ /// Behavioral test: api_key_auth_middleware accepts query param fallback
263
+ #[tokio::test]
264
+ async fn test_api_key_auth_middleware_query_fallback() {
265
+ let config = spikard_http::ApiKeyConfig {
266
+ header_name: "X-API-Key".to_string(),
267
+ keys: vec!["top-secret".to_string()],
268
+ };
269
+
270
+ let config_state = config.clone();
271
+
272
+ async fn api_key_layer(
273
+ State(cfg): State<spikard_http::ApiKeyConfig>,
274
+ req: Request<Body>,
275
+ next: Next,
276
+ ) -> Result<axum::response::Response, axum::response::Response> {
277
+ let headers = req.headers().clone();
278
+ api_key_auth_middleware(cfg, headers, req, next).await
279
+ }
280
+
281
+ let app = Router::new()
282
+ .route(
283
+ "/data",
284
+ get(|| async {
285
+ let mut response = axum::response::Response::new(Body::empty());
286
+ *response.status_mut() = StatusCode::NO_CONTENT;
287
+ response
288
+ }),
289
+ )
290
+ .layer(middleware::from_fn_with_state(config_state, api_key_layer));
291
+
292
+ let response = axum_test::TestServer::new(app)
293
+ .unwrap()
294
+ .get("/data?api_key=top-secret")
295
+ .await;
296
+
297
+ assert_eq!(response.status_code(), StatusCode::NO_CONTENT);
298
+ }
299
+
300
+ /// Test 8: Malformed token (wrong parts) returns 401
301
+ ///
302
+ /// Fixture: 13_jwt_malformed_token.json
303
+ /// Expected: 401 with "Malformed JWT token" detail
304
+ #[tokio::test]
305
+ async fn test_jwt_malformed_token_returns_401() {
306
+ let fixture = load_fixture("testing_data/auth/13_jwt_malformed_token.json").expect("Failed to load fixture");
307
+
308
+ let auth_header = fixture["request"]["headers"]["Authorization"]
309
+ .as_str()
310
+ .expect("Authorization header not in fixture");
311
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
312
+ let expected_title = fixture["expected_response"]["body"]["title"].as_str().unwrap();
313
+
314
+ let (_request, _request_data) = RequestBuilder::new()
315
+ .method(axum::http::Method::GET)
316
+ .path("/api/protected")
317
+ .header("Authorization", auth_header)
318
+ .build();
319
+
320
+ assert!(expected_title.contains("Malformed"));
321
+ assert!(expected_detail.contains("3 parts") || expected_detail.contains("expected"));
322
+ }
323
+
324
+ /// Test 9: Bearer token without "Bearer " prefix returns 401
325
+ ///
326
+ /// Fixture: 17_bearer_token_without_prefix.json
327
+ /// Expected: 401 with "Invalid Authorization header format" error
328
+ #[tokio::test]
329
+ async fn test_bearer_token_without_prefix_returns_401() {
330
+ let fixture =
331
+ load_fixture("testing_data/auth/17_bearer_token_without_prefix.json").expect("Failed to load fixture");
332
+
333
+ let auth_header = fixture["request"]["headers"]["Authorization"]
334
+ .as_str()
335
+ .expect("Authorization header not in fixture");
336
+ let expected_title = fixture["expected_response"]["body"]["title"].as_str().unwrap();
337
+
338
+ let (_request, _request_data) = RequestBuilder::new()
339
+ .method(axum::http::Method::GET)
340
+ .path("/api/protected")
341
+ .header("Authorization", auth_header)
342
+ .build();
343
+
344
+ assert!(expected_title.contains("Invalid Authorization header format"));
345
+ }
346
+
347
+ /// Test 10: Valid API key allows access
348
+ ///
349
+ /// Fixture: 06_api_key_valid.json
350
+ /// Expected: 200 OK with handler response
351
+ #[tokio::test]
352
+ async fn test_api_key_valid_allows_access() {
353
+ let fixture = load_fixture("testing_data/auth/06_api_key_valid.json").expect("Failed to load fixture");
354
+
355
+ let req_path = fixture["request"]["path"].as_str().unwrap_or("/");
356
+ let api_key = fixture["request"]["headers"]["X-API-Key"]
357
+ .as_str()
358
+ .expect("X-API-Key header not in fixture");
359
+
360
+ let handler = HandlerBuilder::new()
361
+ .status(200)
362
+ .json_body(json!({"message": "Access granted", "data": "sensitive information"}))
363
+ .build();
364
+
365
+ let (request, request_data) = RequestBuilder::new()
366
+ .method(axum::http::Method::GET)
367
+ .path(req_path)
368
+ .header("X-API-Key", api_key)
369
+ .build();
370
+
371
+ let response = handler.call(request, request_data).await.unwrap();
372
+ assert_status(&response, StatusCode::OK);
373
+
374
+ let mut response_mut = response;
375
+ let body = parse_json_body(&mut response_mut).await.unwrap();
376
+ assert_eq!(body["message"], "Access granted");
377
+ }
378
+
379
+ /// Test 11: Invalid API key returns 401
380
+ ///
381
+ /// Fixture: 07_api_key_invalid.json
382
+ /// Expected: 401 with "The provided API key is not valid" detail
383
+ #[tokio::test]
384
+ async fn test_api_key_invalid_returns_401() {
385
+ let fixture = load_fixture("testing_data/auth/07_api_key_invalid.json").expect("Failed to load fixture");
386
+
387
+ let req_path = fixture["request"]["path"].as_str().unwrap_or("/");
388
+ let api_key = fixture["request"]["headers"]["X-API-Key"]
389
+ .as_str()
390
+ .expect("X-API-Key header not in fixture");
391
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
392
+
393
+ let (_request, _request_data) = RequestBuilder::new()
394
+ .method(axum::http::Method::GET)
395
+ .path(req_path)
396
+ .header("X-API-Key", api_key)
397
+ .build();
398
+
399
+ assert!(expected_detail.contains("not valid"));
400
+ }
401
+
402
+ /// Test 12: Missing API key header returns 401
403
+ ///
404
+ /// Fixture: 08_api_key_missing.json
405
+ /// Expected: 401 with "Missing API key" error
406
+ #[tokio::test]
407
+ async fn test_api_key_missing_returns_401() {
408
+ let fixture = load_fixture("testing_data/auth/08_api_key_missing.json").expect("Failed to load fixture");
409
+
410
+ let req_path = fixture["request"]["path"].as_str().unwrap_or("/");
411
+ let expected_detail = fixture["expected_response"]["body"]["detail"].as_str().unwrap();
412
+
413
+ let (_request, _request_data) = RequestBuilder::new()
414
+ .method(axum::http::Method::GET)
415
+ .path(req_path)
416
+ .build();
417
+
418
+ assert!(expected_detail.contains("Missing") || expected_detail.contains("api_key"));
419
+ }
420
+
421
+ /// Test 13: API key in query parameter allows access
422
+ ///
423
+ /// Fixture: 14_api_key_query_parameter.json
424
+ /// Expected: 200 OK with handler response (query parameter fallback)
425
+ #[tokio::test]
426
+ async fn test_api_key_query_parameter_allows_access() {
427
+ let fixture = load_fixture("testing_data/auth/14_api_key_query_parameter.json").expect("Failed to load fixture");
428
+
429
+ let req_path = fixture["request"]["path"].as_str().unwrap_or("/");
430
+ let expected_status = fixture["expected_response"]["status_code"].as_u64().unwrap();
431
+
432
+ let handler = HandlerBuilder::new()
433
+ .status(200)
434
+ .json_body(json!({"message": "Access granted", "data": "sensitive information"}))
435
+ .build();
436
+
437
+ let (request, request_data) = RequestBuilder::new()
438
+ .method(axum::http::Method::GET)
439
+ .path(req_path)
440
+ .query_param("api_key", "sk_test_123456")
441
+ .build();
442
+
443
+ let response = handler.call(request, request_data).await.unwrap();
444
+ assert_eq!(response.status().as_u16() as u64, expected_status);
445
+
446
+ if expected_status == 200 {
447
+ let mut response_mut = response;
448
+ let body = parse_json_body(&mut response_mut).await.unwrap();
449
+ assert_eq!(body["message"], "Access granted");
450
+ }
451
+ }
452
+
453
+ /// Mock handler for testing
454
+ /// Used internally to test request/response flow without actual authentication
455
+ #[allow(dead_code)]
456
+ struct MockHandler {
457
+ status: StatusCode,
458
+ }
459
+
460
+ #[allow(dead_code)]
461
+ impl Handler for MockHandler {
462
+ fn call(
463
+ &self,
464
+ _request: Request<Body>,
465
+ _request_data: RequestData,
466
+ ) -> Pin<Box<dyn Future<Output = HandlerResult> + Send + '_>> {
467
+ let status = self.status;
468
+ Box::pin(async move {
469
+ let response = axum::http::Response::builder()
470
+ .status(status)
471
+ .header("content-type", "application/json")
472
+ .body(Body::from(json!({"authenticated": true}).to_string()))
473
+ .unwrap();
474
+ Ok(response)
475
+ })
476
+ }
477
+ }
478
+
479
+ /// Verify all auth fixtures are properly structured
480
+ #[test]
481
+ fn test_jwt_valid_token_fixture_structure() {
482
+ let fixture = load_fixture("testing_data/auth/01_jwt_valid_token.json").expect("Failed to load fixture");
483
+
484
+ assert!(fixture["request"]["headers"]["Authorization"].is_string());
485
+ assert_eq!(fixture["expected_response"]["status_code"], 200);
486
+ assert!(fixture["expected_response"]["body"]["message"].is_string());
487
+ }
488
+
489
+ #[test]
490
+ fn test_jwt_missing_header_fixture_structure() {
491
+ let fixture = load_fixture("testing_data/auth/02_jwt_missing_header.json").expect("Failed to load fixture");
492
+
493
+ assert!(!fixture["request"]["headers"].is_object());
494
+ assert_eq!(fixture["expected_response"]["status_code"], 401);
495
+ assert!(fixture["expected_response"]["body"]["title"].is_string());
496
+ }
497
+
498
+ #[test]
499
+ fn test_jwt_expired_token_fixture_structure() {
500
+ let fixture = load_fixture("testing_data/auth/03_jwt_expired_token.json").expect("Failed to load fixture");
501
+
502
+ assert!(fixture["request"]["headers"]["Authorization"].is_string());
503
+ assert_eq!(fixture["expected_response"]["status_code"], 401);
504
+ assert!(fixture["expected_response"]["body"]["detail"].is_string());
505
+ }
506
+
507
+ #[test]
508
+ fn test_api_key_valid_fixture_structure() {
509
+ let fixture = load_fixture("testing_data/auth/06_api_key_valid.json").expect("Failed to load fixture");
510
+
511
+ assert!(fixture["request"]["headers"]["X-API-Key"].is_string());
512
+ assert_eq!(fixture["expected_response"]["status_code"], 200);
513
+ assert!(fixture["expected_response"]["body"]["message"].is_string());
514
+ }
515
+
516
+ #[test]
517
+ fn test_api_key_missing_fixture_structure() {
518
+ let fixture = load_fixture("testing_data/auth/08_api_key_missing.json").expect("Failed to load fixture");
519
+
520
+ assert!(!fixture["request"]["headers"].is_object() || !fixture["request"]["headers"].get("X-API-Key").is_some());
521
+ assert_eq!(fixture["expected_response"]["status_code"], 401);
522
+ assert!(fixture["expected_response"]["body"]["detail"].is_string());
523
+ }
524
+
525
+ #[test]
526
+ fn test_api_key_query_parameter_fixture_structure() {
527
+ let fixture = load_fixture("testing_data/auth/14_api_key_query_parameter.json").expect("Failed to load fixture");
528
+
529
+ let path = fixture["request"]["path"].as_str().unwrap();
530
+ assert!(path.contains("api_key="));
531
+ assert_eq!(fixture["expected_response"]["status_code"], 200);
532
+ }
533
+
534
+ /// Verify auth errors follow RFC 9457 Problem Details format
535
+ #[test]
536
+ fn test_jwt_error_response_format() {
537
+ let fixture = load_fixture("testing_data/auth/02_jwt_missing_header.json").expect("Failed to load fixture");
538
+
539
+ let body = &fixture["expected_response"]["body"];
540
+
541
+ assert!(body["type"].is_string());
542
+ assert!(body["title"].is_string());
543
+ assert!(body["status"].is_number());
544
+ assert!(body["detail"].is_string());
545
+
546
+ let type_str = body["type"].as_str().unwrap();
547
+ assert!(type_str.contains("spikard.dev/errors"));
548
+
549
+ assert_eq!(fixture["expected_response"]["status_code"], body["status"]);
550
+ }
551
+
552
+ #[test]
553
+ fn test_api_key_error_response_format() {
554
+ let fixture = load_fixture("testing_data/auth/08_api_key_missing.json").expect("Failed to load fixture");
555
+
556
+ let body = &fixture["expected_response"]["body"];
557
+
558
+ assert!(body["type"].is_string());
559
+ assert!(body["title"].is_string());
560
+ assert!(body["status"].is_number());
561
+ assert!(body["detail"].is_string());
562
+
563
+ let type_str = body["type"].as_str().unwrap();
564
+ assert!(type_str.contains("spikard.dev/errors"));
565
+ }
566
+
567
+ /// Verify all JWT fixtures use consistent error type URIs
568
+ #[test]
569
+ fn test_jwt_fixtures_consistent_error_types() {
570
+ let fixtures = vec![
571
+ "testing_data/auth/02_jwt_missing_header.json",
572
+ "testing_data/auth/03_jwt_expired_token.json",
573
+ "testing_data/auth/04_jwt_invalid_signature.json",
574
+ "testing_data/auth/05_jwt_invalid_audience.json",
575
+ "testing_data/auth/09_jwt_invalid_issuer.json",
576
+ "testing_data/auth/10_jwt_not_before_future.json",
577
+ "testing_data/auth/13_jwt_malformed_token.json",
578
+ "testing_data/auth/17_bearer_token_without_prefix.json",
579
+ ];
580
+
581
+ for fixture_path in fixtures {
582
+ let fixture = load_fixture(fixture_path).unwrap_or_else(|_| panic!("Failed to load fixture: {}", fixture_path));
583
+
584
+ if fixture["expected_response"]["status_code"] == 401 {
585
+ let error_type = fixture["expected_response"]["body"]["type"].as_str().unwrap();
586
+ assert_eq!(
587
+ error_type, "https://spikard.dev/errors/unauthorized",
588
+ "Fixture {} has inconsistent error type",
589
+ fixture_path
590
+ );
591
+ }
592
+ }
593
+ }
594
+
595
+ /// Verify all API key fixtures use consistent error type URIs
596
+ #[test]
597
+ fn test_api_key_fixtures_consistent_error_types() {
598
+ let fixtures = vec![
599
+ "testing_data/auth/07_api_key_invalid.json",
600
+ "testing_data/auth/08_api_key_missing.json",
601
+ ];
602
+
603
+ for fixture_path in fixtures {
604
+ let fixture = load_fixture(fixture_path).unwrap_or_else(|_| panic!("Failed to load fixture: {}", fixture_path));
605
+
606
+ if fixture["expected_response"]["status_code"] == 401 {
607
+ let error_type = fixture["expected_response"]["body"]["type"].as_str().unwrap();
608
+ assert_eq!(
609
+ error_type, "https://spikard.dev/errors/unauthorized",
610
+ "Fixture {} has inconsistent error type",
611
+ fixture_path
612
+ );
613
+ }
614
+ }
615
+ }
616
+
617
+ /// Verify all 401 responses have unique, meaningful error details
618
+ #[test]
619
+ fn test_jwt_error_details_are_specific() {
620
+ let fixtures = vec![
621
+ ("testing_data/auth/02_jwt_missing_header.json", "Authorization"),
622
+ ("testing_data/auth/03_jwt_expired_token.json", "expired"),
623
+ ("testing_data/auth/04_jwt_invalid_signature.json", "signature"),
624
+ ("testing_data/auth/05_jwt_invalid_audience.json", "audience"),
625
+ ("testing_data/auth/09_jwt_invalid_issuer.json", "issuer"),
626
+ ("testing_data/auth/10_jwt_not_before_future.json", "valid"),
627
+ ("testing_data/auth/13_jwt_malformed_token.json", "Malformed"),
628
+ ("testing_data/auth/17_bearer_token_without_prefix.json", "Bearer"),
629
+ ];
630
+
631
+ for (fixture_path, expected_keyword) in fixtures {
632
+ let fixture = load_fixture(fixture_path).unwrap_or_else(|_| panic!("Failed to load fixture: {}", fixture_path));
633
+
634
+ let detail = fixture["expected_response"]["body"]["detail"]
635
+ .as_str()
636
+ .unwrap()
637
+ .to_lowercase();
638
+
639
+ assert!(
640
+ detail.contains(&expected_keyword.to_lowercase()),
641
+ "Fixture {} detail doesn't contain expected keyword '{}': {}",
642
+ fixture_path,
643
+ expected_keyword,
644
+ detail
645
+ );
646
+ }
647
+ }