1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use std::sync::OnceLock;
4
5#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
7pub enum Method {
8 #[default]
9 Get,
10 Post,
11 Put,
12 Patch,
13 Delete,
14 Head,
15 Options,
16 Connect,
17 Trace,
18}
19
20impl Method {
21 #[must_use]
22 pub const fn as_str(&self) -> &'static str {
23 match self {
24 Self::Get => "GET",
25 Self::Post => "POST",
26 Self::Put => "PUT",
27 Self::Patch => "PATCH",
28 Self::Delete => "DELETE",
29 Self::Head => "HEAD",
30 Self::Options => "OPTIONS",
31 Self::Connect => "CONNECT",
32 Self::Trace => "TRACE",
33 }
34 }
35}
36
37impl std::fmt::Display for Method {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 write!(f, "{}", self.as_str())
40 }
41}
42
43impl From<Method> for http::method::Method {
44 fn from(method: Method) -> Self {
45 match method {
46 Method::Get => Self::GET,
47 Method::Post => Self::POST,
48 Method::Put => Self::PUT,
49 Method::Patch => Self::PATCH,
50 Method::Delete => Self::DELETE,
51 Method::Head => Self::HEAD,
52 Method::Options => Self::OPTIONS,
53 Method::Connect => Self::CONNECT,
54 Method::Trace => Self::TRACE,
55 }
56 }
57}
58
59impl From<&Method> for http::method::Method {
60 fn from(method: &Method) -> Self {
61 match method {
62 Method::Get => Self::GET,
63 Method::Post => Self::POST,
64 Method::Put => Self::PUT,
65 Method::Patch => Self::PATCH,
66 Method::Delete => Self::DELETE,
67 Method::Head => Self::HEAD,
68 Method::Options => Self::OPTIONS,
69 Method::Connect => Self::CONNECT,
70 Method::Trace => Self::TRACE,
71 }
72 }
73}
74
75impl std::str::FromStr for Method {
76 type Err = String;
77
78 fn from_str(s: &str) -> Result<Self, Self::Err> {
79 match s.to_uppercase().as_str() {
80 "GET" => Ok(Self::Get),
81 "POST" => Ok(Self::Post),
82 "PUT" => Ok(Self::Put),
83 "PATCH" => Ok(Self::Patch),
84 "DELETE" => Ok(Self::Delete),
85 "HEAD" => Ok(Self::Head),
86 "OPTIONS" => Ok(Self::Options),
87 "CONNECT" => Ok(Self::Connect),
88 "TRACE" => Ok(Self::Trace),
89 _ => Err(format!("Unknown HTTP method: {s}")),
90 }
91 }
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct CorsConfig {
97 pub allowed_origins: Vec<String>,
98 pub allowed_methods: Vec<String>,
99 #[serde(default)]
100 pub allowed_headers: Vec<String>,
101 #[serde(skip_serializing_if = "Option::is_none")]
102 pub expose_headers: Option<Vec<String>>,
103 #[serde(skip_serializing_if = "Option::is_none")]
104 pub max_age: Option<u32>,
105 #[serde(skip_serializing_if = "Option::is_none")]
106 pub allow_credentials: Option<bool>,
107
108 #[serde(skip)]
109 #[doc(hidden)]
110 #[cfg_attr(alef, alef(skip))]
111 pub methods_joined_cache: OnceLock<String>,
112 #[serde(skip)]
113 #[doc(hidden)]
114 #[cfg_attr(alef, alef(skip))]
115 pub headers_joined_cache: OnceLock<String>,
116}
117
118impl CorsConfig {
119 pub fn allowed_methods_joined(&self) -> &str {
121 self.methods_joined_cache
122 .get_or_init(|| self.allowed_methods.join(", "))
123 }
124
125 pub fn allowed_headers_joined(&self) -> &str {
127 self.headers_joined_cache
128 .get_or_init(|| self.allowed_headers.join(", "))
129 }
130
131 pub fn is_origin_allowed(&self, origin: &str) -> bool {
133 if origin.is_empty() {
134 return false;
135 }
136 self.allowed_origins.iter().any(|o| o == "*" || o == origin)
137 }
138
139 pub fn is_method_allowed(&self, method: &str) -> bool {
141 self.allowed_methods
142 .iter()
143 .any(|m| m == "*" || m.eq_ignore_ascii_case(method))
144 }
145
146 pub fn are_headers_allowed(&self, requested: &[&str]) -> bool {
148 if self.allowed_headers.iter().any(|h| h == "*") {
149 return true;
150 }
151
152 requested.iter().all(|req_header| {
153 self.allowed_headers
154 .iter()
155 .any(|h| h.to_lowercase() == req_header.to_lowercase())
156 })
157 }
158}
159
160impl Default for CorsConfig {
161 fn default() -> Self {
162 Self {
163 allowed_origins: vec!["*".to_string()],
164 allowed_methods: vec!["*".to_string()],
165 allowed_headers: vec![],
166 expose_headers: None,
167 max_age: None,
168 allow_credentials: None,
169 methods_joined_cache: OnceLock::new(),
170 headers_joined_cache: OnceLock::new(),
171 }
172 }
173}
174
175#[derive(Debug, Clone, Serialize, Deserialize)]
177pub struct RouteMetadata {
178 pub method: String,
179 pub path: String,
180 pub handler_name: String,
181 pub request_schema: Option<Value>,
182 pub response_schema: Option<Value>,
183 pub parameter_schema: Option<Value>,
184 #[serde(skip_serializing_if = "Option::is_none")]
185 pub file_params: Option<Value>,
186 #[serde(default)]
187 pub is_async: bool,
188 pub cors: Option<CorsConfig>,
189 #[serde(skip_serializing_if = "Option::is_none")]
190 pub compression: Option<CompressionConfig>,
191 #[serde(skip_serializing_if = "Option::is_none")]
193 pub body_limit: Option<usize>,
194 #[serde(skip_serializing_if = "Option::is_none")]
196 pub request_timeout_secs: Option<u64>,
197 #[serde(skip_serializing_if = "Option::is_none")]
199 pub rate_limit: Option<RateLimitConfig>,
200 #[serde(skip_serializing_if = "Option::is_none")]
204 pub request_id: Option<RequestIdConfig>,
205 #[serde(skip_serializing_if = "Option::is_none")]
207 pub jwt_auth: Option<JwtAuthConfig>,
208 #[serde(skip_serializing_if = "Option::is_none")]
210 pub api_key_auth: Option<ApiKeyAuthConfig>,
211 #[serde(skip_serializing_if = "Option::is_none")]
213 pub authorization: Option<AuthorizationConfig>,
214 #[serde(skip_serializing_if = "Option::is_none")]
216 pub lifecycle_hooks: Option<LifecycleHooksConfig>,
217 #[serde(skip_serializing_if = "Option::is_none")]
219 pub body_param_name: Option<String>,
220 #[cfg(feature = "di")]
222 #[serde(skip_serializing_if = "Option::is_none")]
223 pub handler_dependencies: Option<Vec<String>>,
224 #[serde(skip_serializing_if = "Option::is_none")]
226 pub jsonrpc_method: Option<Value>,
227 #[serde(skip_serializing_if = "Option::is_none")]
230 pub openrpc_spec: Option<Value>,
231 #[serde(skip_serializing_if = "Option::is_none")]
235 pub static_response: Option<Value>,
236}
237
238impl Default for RouteMetadata {
239 fn default() -> Self {
240 Self {
241 method: "GET".to_string(),
242 path: "/".to_string(),
243 handler_name: String::new(),
244 request_schema: None,
245 response_schema: None,
246 parameter_schema: None,
247 file_params: None,
248 is_async: true,
249 cors: None,
250 body_param_name: None,
251 #[cfg(feature = "di")]
252 handler_dependencies: None,
253 jsonrpc_method: None,
254 openrpc_spec: None,
255 static_response: None,
256 compression: None,
257 body_limit: None,
258 request_timeout_secs: None,
259 rate_limit: None,
260 request_id: None,
261 jwt_auth: None,
262 api_key_auth: None,
263 authorization: None,
264 lifecycle_hooks: None,
265 }
266 }
267}
268
269#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct CompressionConfig {
272 #[serde(default = "default_true")]
274 pub gzip: bool,
275 #[serde(default = "default_true")]
277 pub brotli: bool,
278 #[serde(default = "default_compression_min_size")]
280 pub min_size: usize,
281 #[serde(default = "default_compression_quality")]
283 pub quality: u32,
284}
285
286const fn default_true() -> bool {
287 true
288}
289
290const fn default_compression_min_size() -> usize {
291 1024
292}
293
294const fn default_compression_quality() -> u32 {
295 6
296}
297
298impl Default for CompressionConfig {
299 fn default() -> Self {
300 Self {
301 gzip: true,
302 brotli: true,
303 min_size: default_compression_min_size(),
304 quality: default_compression_quality(),
305 }
306 }
307}
308
309#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct RateLimitConfig {
312 pub per_second: u64,
314 pub burst: u32,
316 #[serde(default = "default_true")]
318 pub ip_based: bool,
319}
320
321impl Default for RateLimitConfig {
322 fn default() -> Self {
323 Self {
324 per_second: 100,
325 burst: 200,
326 ip_based: true,
327 }
328 }
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
339pub struct RequestIdConfig {
340 pub enabled: bool,
342}
343
344impl From<bool> for RequestIdConfig {
345 fn from(enabled: bool) -> Self {
346 Self { enabled }
347 }
348}
349
350#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
363pub struct JwtAuthConfig {
364 #[serde(default = "default_true")]
369 pub enabled: bool,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub secret: Option<String>,
373 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub public_key: Option<String>,
376 #[serde(default = "default_jwt_algorithm")]
378 pub algorithm: String,
379 pub audience: Option<Vec<String>>,
381 pub issuer: Option<String>,
383 #[serde(default)]
385 pub leeway: u64,
386}
387
388fn default_jwt_algorithm() -> String {
389 "HS256".to_string()
390}
391
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397pub struct ApiKeyAuthConfig {
398 #[serde(default = "default_true")]
402 pub enabled: bool,
403 #[serde(default)]
410 pub keys: Vec<String>,
411 #[serde(default = "default_api_key_header")]
413 pub header_name: String,
414}
415
416fn default_api_key_header() -> String {
417 "X-API-Key".to_string()
418}
419
420#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
434pub struct AuthorizationConfig {
435 pub required_roles: Vec<String>,
437 pub required_scopes: Vec<String>,
439 pub required_permissions: Vec<String>,
441 pub require_all: bool,
444}
445
446impl Default for AuthorizationConfig {
447 fn default() -> Self {
448 Self {
449 required_roles: Vec::new(),
450 required_scopes: Vec::new(),
451 required_permissions: Vec::new(),
452 require_all: true,
453 }
454 }
455}
456
457#[derive(Debug, Deserialize)]
462#[serde(deny_unknown_fields)]
463struct AuthorizationConfigRepr {
464 #[serde(default)]
465 required_role: Option<String>,
466 #[serde(default)]
467 required_roles: Vec<String>,
468 #[serde(default)]
469 required_scopes: Vec<String>,
470 #[serde(default)]
471 required_permissions: Vec<String>,
472 #[serde(default = "default_true")]
473 require_all: bool,
474}
475
476impl<'de> Deserialize<'de> for AuthorizationConfig {
477 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
478 where
479 D: serde::Deserializer<'de>,
480 {
481 let repr = AuthorizationConfigRepr::deserialize(deserializer)?;
482 let mut required_roles = repr.required_roles;
483 if let Some(role) = repr.required_role {
484 required_roles.push(role);
485 }
486 Ok(Self {
487 required_roles,
488 required_scopes: repr.required_scopes,
489 required_permissions: repr.required_permissions,
490 require_all: repr.require_all,
491 })
492 }
493}
494
495#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
502#[serde(deny_unknown_fields)]
503pub struct LifecycleHookRef {
504 pub name: String,
506 pub handler: String,
508 #[serde(default)]
510 pub dependencies: Vec<String>,
511 #[serde(default, skip_serializing_if = "Option::is_none")]
513 pub config: Option<serde_json::Value>,
514 #[serde(default, skip_serializing_if = "Option::is_none")]
518 pub order: Option<u32>,
519}
520
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
533pub struct LifecycleHooksConfig {
534 #[serde(default)]
536 pub on_request: Vec<LifecycleHookRef>,
537 #[serde(default)]
539 pub pre_validation: Vec<LifecycleHookRef>,
540 #[serde(default)]
542 pub pre_handler: Vec<LifecycleHookRef>,
543 #[serde(default)]
545 pub on_response: Vec<LifecycleHookRef>,
546 #[serde(default)]
548 pub on_error: Vec<LifecycleHookRef>,
549}
550
551#[cfg(test)]
552mod tests {
553 use super::*;
554 use std::str::FromStr;
555
556 #[test]
557 fn test_method_as_str_get() {
558 assert_eq!(Method::Get.as_str(), "GET");
559 }
560
561 #[test]
562 fn test_method_as_str_post() {
563 assert_eq!(Method::Post.as_str(), "POST");
564 }
565
566 #[test]
567 fn test_method_as_str_put() {
568 assert_eq!(Method::Put.as_str(), "PUT");
569 }
570
571 #[test]
572 fn test_method_as_str_patch() {
573 assert_eq!(Method::Patch.as_str(), "PATCH");
574 }
575
576 #[test]
577 fn test_method_as_str_delete() {
578 assert_eq!(Method::Delete.as_str(), "DELETE");
579 }
580
581 #[test]
582 fn test_method_as_str_head() {
583 assert_eq!(Method::Head.as_str(), "HEAD");
584 }
585
586 #[test]
587 fn test_method_as_str_options() {
588 assert_eq!(Method::Options.as_str(), "OPTIONS");
589 }
590
591 #[test]
592 fn test_method_as_str_trace() {
593 assert_eq!(Method::Trace.as_str(), "TRACE");
594 }
595
596 #[test]
597 fn test_method_display_get() {
598 assert_eq!(Method::Get.to_string(), "GET");
599 }
600
601 #[test]
602 fn test_method_display_post() {
603 assert_eq!(Method::Post.to_string(), "POST");
604 }
605
606 #[test]
607 fn test_method_display_put() {
608 assert_eq!(Method::Put.to_string(), "PUT");
609 }
610
611 #[test]
612 fn test_method_display_patch() {
613 assert_eq!(Method::Patch.to_string(), "PATCH");
614 }
615
616 #[test]
617 fn test_method_display_delete() {
618 assert_eq!(Method::Delete.to_string(), "DELETE");
619 }
620
621 #[test]
622 fn test_method_display_head() {
623 assert_eq!(Method::Head.to_string(), "HEAD");
624 }
625
626 #[test]
627 fn test_method_display_options() {
628 assert_eq!(Method::Options.to_string(), "OPTIONS");
629 }
630
631 #[test]
632 fn test_method_display_trace() {
633 assert_eq!(Method::Trace.to_string(), "TRACE");
634 }
635
636 #[test]
637 fn test_from_str_get() {
638 assert_eq!(Method::from_str("GET"), Ok(Method::Get));
639 }
640
641 #[test]
642 fn test_from_str_post() {
643 assert_eq!(Method::from_str("POST"), Ok(Method::Post));
644 }
645
646 #[test]
647 fn test_from_str_put() {
648 assert_eq!(Method::from_str("PUT"), Ok(Method::Put));
649 }
650
651 #[test]
652 fn test_from_str_patch() {
653 assert_eq!(Method::from_str("PATCH"), Ok(Method::Patch));
654 }
655
656 #[test]
657 fn test_from_str_delete() {
658 assert_eq!(Method::from_str("DELETE"), Ok(Method::Delete));
659 }
660
661 #[test]
662 fn test_from_str_head() {
663 assert_eq!(Method::from_str("HEAD"), Ok(Method::Head));
664 }
665
666 #[test]
667 fn test_from_str_options() {
668 assert_eq!(Method::from_str("OPTIONS"), Ok(Method::Options));
669 }
670
671 #[test]
672 fn test_from_str_trace() {
673 assert_eq!(Method::from_str("TRACE"), Ok(Method::Trace));
674 }
675
676 #[test]
677 fn test_from_str_lowercase() {
678 assert_eq!(Method::from_str("get"), Ok(Method::Get));
679 }
680
681 #[test]
682 fn test_from_str_mixed_case() {
683 assert_eq!(Method::from_str("PoSt"), Ok(Method::Post));
684 }
685
686 #[test]
687 fn test_from_str_invalid_method() {
688 let result = Method::from_str("INVALID");
689 assert!(result.is_err());
690 assert_eq!(result.unwrap_err(), "Unknown HTTP method: INVALID");
691 }
692
693 #[test]
694 fn test_from_str_empty_string() {
695 let result = Method::from_str("");
696 assert!(result.is_err());
697 assert_eq!(result.unwrap_err(), "Unknown HTTP method: ");
698 }
699
700 #[test]
701 fn test_compression_config_default() {
702 let config = CompressionConfig::default();
703 assert!(config.gzip);
704 assert!(config.brotli);
705 assert_eq!(config.min_size, 1024);
706 assert_eq!(config.quality, 6);
707 }
708
709 #[test]
710 fn test_default_true() {
711 assert!(default_true());
712 }
713
714 #[test]
715 fn test_default_compression_min_size() {
716 assert_eq!(default_compression_min_size(), 1024);
717 }
718
719 #[test]
720 fn test_default_compression_quality() {
721 assert_eq!(default_compression_quality(), 6);
722 }
723
724 #[test]
725 fn test_rate_limit_config_default() {
726 let config = RateLimitConfig::default();
727 assert_eq!(config.per_second, 100);
728 assert_eq!(config.burst, 200);
729 assert!(config.ip_based);
730 }
731
732 #[test]
733 fn test_method_equality() {
734 assert_eq!(Method::Get, Method::Get);
735 assert_ne!(Method::Get, Method::Post);
736 }
737
738 #[test]
739 fn test_method_clone() {
740 let method = Method::Post;
741 let cloned = method.clone();
742 assert_eq!(method, cloned);
743 }
744
745 #[test]
746 fn test_compression_config_custom_values() {
747 let config = CompressionConfig {
748 gzip: false,
749 brotli: false,
750 min_size: 2048,
751 quality: 11,
752 };
753 assert!(!config.gzip);
754 assert!(!config.brotli);
755 assert_eq!(config.min_size, 2048);
756 assert_eq!(config.quality, 11);
757 }
758
759 #[test]
760 fn test_rate_limit_config_custom_values() {
761 let config = RateLimitConfig {
762 per_second: 50,
763 burst: 100,
764 ip_based: false,
765 };
766 assert_eq!(config.per_second, 50);
767 assert_eq!(config.burst, 100);
768 assert!(!config.ip_based);
769 }
770
771 #[test]
772 fn test_cors_config_construction() {
773 let cors = CorsConfig {
774 allowed_origins: vec!["http://localhost:3000".to_string()],
775 allowed_methods: vec!["GET".to_string(), "POST".to_string()],
776 allowed_headers: vec![],
777 expose_headers: None,
778 max_age: None,
779 allow_credentials: None,
780 ..Default::default()
781 };
782 assert_eq!(cors.allowed_origins.len(), 1);
783 assert_eq!(cors.allowed_methods.len(), 2);
784 assert_eq!(cors.allowed_headers.len(), 0);
785 }
786
787 #[test]
788 fn test_route_metadata_construction() {
789 let metadata = RouteMetadata {
790 method: "GET".to_string(),
791 path: "/api/users".to_string(),
792 handler_name: "get_users".to_string(),
793 request_schema: None,
794 response_schema: None,
795 parameter_schema: None,
796 file_params: None,
797 is_async: true,
798 cors: None,
799 body_param_name: None,
800 #[cfg(feature = "di")]
801 handler_dependencies: None,
802 jsonrpc_method: None,
803 openrpc_spec: None,
804 static_response: None,
805 compression: None,
806 body_limit: None,
807 request_timeout_secs: None,
808 rate_limit: None,
809 request_id: None,
810 jwt_auth: None,
811 api_key_auth: None,
812 authorization: None,
813 lifecycle_hooks: None,
814 };
815 assert_eq!(metadata.method, "GET");
816 assert_eq!(metadata.path, "/api/users");
817 assert_eq!(metadata.handler_name, "get_users");
818 assert!(metadata.is_async);
819 }
820
821 #[test]
822 fn test_route_metadata_default_has_no_middleware_configured() {
823 let metadata = RouteMetadata::default();
824 assert!(metadata.rate_limit.is_none());
825 assert!(metadata.request_id.is_none());
826 assert!(metadata.jwt_auth.is_none());
827 assert!(metadata.api_key_auth.is_none());
828 assert!(metadata.authorization.is_none());
829 assert!(metadata.lifecycle_hooks.is_none());
830 assert!(metadata.openrpc_spec.is_none());
831 }
832
833 #[test]
835 fn should_enable_request_id_when_given_real_enabled_true_fixture_payload() {
836 let json = serde_json::json!({ "enabled": true });
837 let config: RequestIdConfig = serde_json::from_value(json).unwrap();
838 assert!(config.enabled);
839 }
840
841 #[test]
846 fn should_disable_request_id_when_given_real_enabled_false_fixture_payload() {
847 let json = serde_json::json!({ "enabled": false });
848 let config: RequestIdConfig = serde_json::from_value(json).unwrap();
849 assert!(!config.enabled);
850 }
851
852 #[test]
855 fn should_deserialize_route_metadata_request_id_when_given_real_disabled_fixture_payload() {
856 let mut json_value = serde_json::json!(RouteMetadata::default());
857 json_value["request_id"] = serde_json::json!({ "enabled": false });
858
859 let metadata: RouteMetadata = serde_json::from_value(json_value).unwrap();
860 let request_id = metadata.request_id.expect("request_id present");
861 assert!(!request_id.enabled);
862 }
863
864 #[test]
865 fn test_jwt_auth_config_deserializes_with_default_algorithm() {
866 let json = serde_json::json!({ "secret": "s3cr3t" });
867 let config: JwtAuthConfig = serde_json::from_value(json).unwrap();
868 assert_eq!(config.secret.as_deref(), Some("s3cr3t"));
869 assert!(config.public_key.is_none());
870 assert_eq!(config.algorithm, "HS256");
871 assert_eq!(config.leeway, 0);
872 assert!(config.audience.is_none());
873 assert!(config.issuer.is_none());
874 assert!(config.enabled);
875 }
876
877 #[test]
882 fn should_deserialize_rs256_public_key_when_given_real_jwt_fixture_payload() {
883 let json = serde_json::json!({
884 "algorithm": "RS256",
885 "enabled": true,
886 "public_key": "-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALRiMLAA\n-----END PUBLIC KEY-----"
887 });
888 let config: JwtAuthConfig = serde_json::from_value(json).unwrap();
889 assert_eq!(config.algorithm, "RS256");
890 assert!(config.secret.is_none());
891 assert_eq!(
892 config.public_key.as_deref(),
893 Some("-----BEGIN PUBLIC KEY-----\nMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALRiMLAA\n-----END PUBLIC KEY-----")
894 );
895 assert!(config.enabled);
896 }
897
898 #[test]
901 fn should_preserve_false_enabled_value_when_jwt_auth_disabled() {
902 let json = serde_json::json!({ "algorithm": "HS256", "enabled": false, "secret": "s3cr3t" });
903 let config: JwtAuthConfig = serde_json::from_value(json).unwrap();
904 assert!(!config.enabled);
905 }
906
907 #[test]
908 fn test_api_key_auth_config_deserializes_with_default_header_name() {
909 let json = serde_json::json!({ "keys": ["abc123"] });
910 let config: ApiKeyAuthConfig = serde_json::from_value(json).unwrap();
911 assert_eq!(config.keys, vec!["abc123".to_string()]);
912 assert_eq!(config.header_name, "X-API-Key");
913 assert!(config.enabled);
914 }
915
916 #[test]
919 fn should_deserialize_api_key_auth_config_capturing_enabled_field_from_real_fixture_payload() {
920 let json = serde_json::json!({
921 "enabled": true,
922 "header_name": "X-API-Key",
923 "keys": ["sk_test_123456", "sk_test_789012"]
924 });
925 let config: ApiKeyAuthConfig = serde_json::from_value(json).unwrap();
926 assert_eq!(
927 config.keys,
928 vec!["sk_test_123456".to_string(), "sk_test_789012".to_string()]
929 );
930 assert_eq!(config.header_name, "X-API-Key");
931 assert!(config.enabled);
932 }
933
934 #[test]
937 fn should_preserve_false_enabled_value_when_api_key_auth_disabled() {
938 let json = serde_json::json!({ "enabled": false, "header_name": "X-API-Key", "keys": ["k1"] });
939 let config: ApiKeyAuthConfig = serde_json::from_value(json).unwrap();
940 assert!(!config.enabled);
941 }
942
943 #[test]
950 fn should_default_keys_to_empty_when_given_real_fixture_payload_missing_keys() {
951 let json = serde_json::json!({ "enabled": true, "header": "X-API-Key" });
952 let config: ApiKeyAuthConfig = serde_json::from_value(json).unwrap();
953 assert!(config.keys.is_empty());
954 assert_eq!(config.header_name, "X-API-Key");
955 assert!(config.enabled);
956 }
957
958 #[test]
959 fn test_authorization_config_default_requires_all() {
960 let config = AuthorizationConfig::default();
961 assert!(config.required_roles.is_empty());
962 assert!(config.required_scopes.is_empty());
963 assert!(config.required_permissions.is_empty());
964 assert!(config.require_all);
965 }
966
967 #[test]
968 fn test_authorization_config_custom_values() {
969 let config = AuthorizationConfig {
970 required_roles: vec!["admin".to_string()],
971 required_scopes: vec!["users:write".to_string()],
972 required_permissions: vec![],
973 require_all: false,
974 };
975 assert_eq!(config.required_roles, vec!["admin".to_string()]);
976 assert_eq!(config.required_scopes, vec!["users:write".to_string()]);
977 assert!(!config.require_all);
978 }
979
980 #[test]
984 fn should_require_admin_role_when_given_real_singular_required_role_fixture_payload() {
985 let json = serde_json::json!({ "required_role": "admin" });
986 let config: AuthorizationConfig = serde_json::from_value(json).unwrap();
987 assert_eq!(config.required_roles, vec!["admin".to_string()]);
988 assert!(config.required_scopes.is_empty());
989 assert!(config.required_permissions.is_empty());
990 }
991
992 #[test]
993 fn should_merge_singular_and_plural_role_fields_when_both_present() {
994 let json = serde_json::json!({ "required_role": "admin", "required_roles": ["editor"] });
995 let config: AuthorizationConfig = serde_json::from_value(json).unwrap();
996 assert_eq!(config.required_roles, vec!["editor".to_string(), "admin".to_string()]);
997 }
998
999 #[test]
1000 fn should_error_when_authorization_config_has_unknown_field() {
1001 let json = serde_json::json!({ "required_group": "admin" });
1002 let result: Result<AuthorizationConfig, _> = serde_json::from_value(json);
1003 assert!(result.is_err());
1004 }
1005
1006 #[test]
1007 fn test_lifecycle_hooks_config_default_has_no_hooks_selected() {
1008 let config = LifecycleHooksConfig::default();
1009 assert!(config.on_request.is_empty());
1010 assert!(config.pre_validation.is_empty());
1011 assert!(config.pre_handler.is_empty());
1012 assert!(config.on_response.is_empty());
1013 assert!(config.on_error.is_empty());
1014 }
1015
1016 #[test]
1017 fn test_lifecycle_hooks_config_serialization_round_trip() {
1018 let config = LifecycleHooksConfig {
1019 on_request: vec![LifecycleHookRef {
1020 name: "auth_check".to_string(),
1021 handler: "run_auth_check".to_string(),
1022 dependencies: vec![],
1023 config: None,
1024 ..Default::default()
1025 }],
1026 pre_validation: vec![],
1027 pre_handler: vec![LifecycleHookRef {
1028 name: "load_tenant".to_string(),
1029 handler: "run_load_tenant".to_string(),
1030 dependencies: vec![],
1031 config: None,
1032 ..Default::default()
1033 }],
1034 on_response: vec![LifecycleHookRef {
1035 name: "add_headers".to_string(),
1036 handler: "run_add_headers".to_string(),
1037 dependencies: vec![],
1038 config: None,
1039 ..Default::default()
1040 }],
1041 on_error: vec![],
1042 };
1043 let json = serde_json::to_value(&config).unwrap();
1044 let deserialized: LifecycleHooksConfig = serde_json::from_value(json).unwrap();
1045 assert_eq!(deserialized.on_request[0].name, "auth_check");
1046 assert_eq!(deserialized.pre_handler[0].name, "load_tenant");
1047 assert_eq!(deserialized.on_response[0].name, "add_headers");
1048 }
1049
1050 #[test]
1052 fn should_deserialize_lifecycle_hooks_when_given_real_on_request_fixture_payload() {
1053 let json = serde_json::json!({
1054 "on_request": [
1055 {"handler": "log_request", "name": "request_logger"},
1056 {"handler": "add_request_id", "name": "request_id_generator"}
1057 ]
1058 });
1059 let config: LifecycleHooksConfig = serde_json::from_value(json).unwrap();
1060 assert_eq!(config.on_request.len(), 2);
1061 assert_eq!(config.on_request[0].name, "request_logger");
1062 assert_eq!(config.on_request[0].handler, "log_request");
1063 assert!(config.on_request[0].dependencies.is_empty());
1064 assert!(config.on_request[0].config.is_none());
1065 assert_eq!(config.on_request[1].name, "request_id_generator");
1066 }
1067
1068 #[test]
1071 fn should_deserialize_lifecycle_hook_config_blob_when_given_real_rate_limit_fixture_payload() {
1072 let json = serde_json::json!({
1073 "pre_validation": [{
1074 "config": {"max_requests": 10, "window_seconds": 60},
1075 "handler": "check_rate_limit",
1076 "name": "rate_limiter"
1077 }]
1078 });
1079 let config: LifecycleHooksConfig = serde_json::from_value(json).unwrap();
1080 assert_eq!(config.pre_validation.len(), 1);
1081 let hook = &config.pre_validation[0];
1082 assert_eq!(hook.name, "rate_limiter");
1083 assert_eq!(hook.handler, "check_rate_limit");
1084 let hook_config = hook.config.as_ref().unwrap();
1085 assert_eq!(hook_config.get("max_requests"), Some(&serde_json::json!(10)));
1086 assert_eq!(hook_config.get("window_seconds"), Some(&serde_json::json!(60)));
1087 }
1088
1089 #[test]
1092 fn should_deserialize_lifecycle_hook_dependencies_when_given_real_di_fixture_payload() {
1093 let json = serde_json::json!({
1094 "on_request": [{
1095 "dependencies": ["logger"],
1096 "handler": "log_incoming_request",
1097 "name": "log_request"
1098 }],
1099 "pre_handler": [{
1100 "dependencies": ["auth_service"],
1101 "handler": "check_authentication",
1102 "name": "auth_check"
1103 }]
1104 });
1105 let config: LifecycleHooksConfig = serde_json::from_value(json).unwrap();
1106 assert_eq!(config.on_request[0].dependencies, vec!["logger".to_string()]);
1107 assert_eq!(config.pre_handler[0].dependencies, vec!["auth_service".to_string()]);
1108 }
1109
1110 #[test]
1112 fn should_deserialize_lifecycle_hooks_when_given_real_multi_phase_fixture_payload() {
1113 let json = serde_json::json!({
1114 "on_error": [{"handler": "log_error", "name": "error_logger"}],
1115 "on_request": [
1116 {"handler": "log_request", "name": "request_logger"},
1117 {"handler": "add_request_id", "name": "request_id_generator"}
1118 ],
1119 "on_response": [
1120 {"handler": "add_security_headers", "name": "security_headers"},
1121 {"handler": "add_response_time", "name": "response_timer"},
1122 {"handler": "log_successful_action", "name": "audit_logger"}
1123 ]
1124 });
1125 let config: LifecycleHooksConfig = serde_json::from_value(json).unwrap();
1126 assert_eq!(config.on_error.len(), 1);
1127 assert_eq!(config.on_request.len(), 2);
1128 assert_eq!(config.on_response.len(), 3);
1129 assert!(config.pre_validation.is_empty());
1130 assert!(config.pre_handler.is_empty());
1131 }
1132
1133 #[test]
1134 fn should_error_when_lifecycle_hook_ref_has_unknown_field() {
1135 let json = serde_json::json!({
1136 "on_request": [{"name": "x", "handler": "y", "unexpected": true}]
1137 });
1138 let result: Result<LifecycleHooksConfig, _> = serde_json::from_value(json);
1139 assert!(result.is_err());
1140 }
1141}