Skip to main content

spikard_core/
http.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use std::sync::OnceLock;
4
5/// HTTP method
6#[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/// CORS configuration for a route
95#[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    /// Get the cached joined methods string for preflight responses
120    pub fn allowed_methods_joined(&self) -> &str {
121        self.methods_joined_cache
122            .get_or_init(|| self.allowed_methods.join(", "))
123    }
124
125    /// Get the cached joined headers string for preflight responses
126    pub fn allowed_headers_joined(&self) -> &str {
127        self.headers_joined_cache
128            .get_or_init(|| self.allowed_headers.join(", "))
129    }
130
131    /// Check if an origin is allowed (O(1) with wildcard, O(n) for exact match)
132    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    /// Check if a method is allowed (O(1) with wildcard, O(n) for exact match)
140    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    /// Check if all requested headers are allowed (O(n) where n = num requested headers)
147    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/// Route metadata extracted from bindings
176#[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    /// Optional per-route maximum request body size in bytes, overriding the server-global default
192    #[serde(skip_serializing_if = "Option::is_none")]
193    pub body_limit: Option<usize>,
194    /// Optional per-route request timeout in seconds, overriding the server-global default
195    #[serde(skip_serializing_if = "Option::is_none")]
196    pub request_timeout_secs: Option<u64>,
197    /// Optional per-route rate limiting configuration, overriding the server-global default
198    #[serde(skip_serializing_if = "Option::is_none")]
199    pub rate_limit: Option<RateLimitConfig>,
200    /// Optional per-route request-id generation override (`Some(RequestIdConfig { enabled: true })`
201    /// forces it on, `Some(RequestIdConfig { enabled: false })` forces it off, `None` inherits the
202    /// server-global default)
203    #[serde(skip_serializing_if = "Option::is_none")]
204    pub request_id: Option<RequestIdConfig>,
205    /// Optional per-route JWT authentication requirement.
206    #[serde(skip_serializing_if = "Option::is_none")]
207    pub jwt_auth: Option<JwtAuthConfig>,
208    /// Optional per-route API key authentication requirement.
209    #[serde(skip_serializing_if = "Option::is_none")]
210    pub api_key_auth: Option<ApiKeyAuthConfig>,
211    /// Optional per-route roles/scopes/permissions authorization requirement.
212    #[serde(skip_serializing_if = "Option::is_none")]
213    pub authorization: Option<AuthorizationConfig>,
214    /// Optional per-route lifecycle hook selection, by registered hook name.
215    #[serde(skip_serializing_if = "Option::is_none")]
216    pub lifecycle_hooks: Option<LifecycleHooksConfig>,
217    /// Name of the body parameter (defaults to "body" if not specified)
218    #[serde(skip_serializing_if = "Option::is_none")]
219    pub body_param_name: Option<String>,
220    /// List of dependency keys this handler requires (for DI)
221    #[cfg(feature = "di")]
222    #[serde(skip_serializing_if = "Option::is_none")]
223    pub handler_dependencies: Option<Vec<String>>,
224    /// JSON-RPC method metadata (if this route is exposed as a JSON-RPC method)
225    #[serde(skip_serializing_if = "Option::is_none")]
226    pub jsonrpc_method: Option<Value>,
227    /// Optional literal `OpenRPC` method spec document, overriding auto-derivation from
228    /// `jsonrpc_method` when present
229    #[serde(skip_serializing_if = "Option::is_none")]
230    pub openrpc_spec: Option<Value>,
231    /// Optional static response configuration: `{"status": 200, "body": "OK", "content_type": "text/plain"}`
232    /// When present, the handler is replaced by a `StaticResponseHandler` that bypasses the full
233    /// middleware pipeline for maximum throughput.
234    #[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/// Compression configuration shared across runtimes
270#[derive(Debug, Clone, Serialize, Deserialize)]
271pub struct CompressionConfig {
272    /// Enable gzip compression
273    #[serde(default = "default_true")]
274    pub gzip: bool,
275    /// Enable brotli compression
276    #[serde(default = "default_true")]
277    pub brotli: bool,
278    /// Minimum response size to compress (bytes)
279    #[serde(default = "default_compression_min_size")]
280    pub min_size: usize,
281    /// Compression quality (0-11 for brotli, 0-9 for gzip)
282    #[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/// Rate limiting configuration shared across runtimes
310#[derive(Debug, Clone, Serialize, Deserialize)]
311pub struct RateLimitConfig {
312    /// Requests per second
313    pub per_second: u64,
314    /// Burst allowance
315    pub burst: u32,
316    /// Use IP-based rate limiting
317    #[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/// Per-route request-id generation/propagation override.
332///
333/// Modeled as a struct rather than `Option<bool>` on `RouteMetadata` because the wire shape is an
334/// object, not a bare boolean: `fixtures/request_id.json`'s `request_id_middleware_can_be_disabled`
335/// sends `{"enabled": false}`, which `Option<bool>` cannot deserialize at all ("invalid type: map,
336/// expected a boolean") — the very fixture whose purpose is proving the middleware can be disabled
337/// was the one that failed to parse. ~keep
338#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
339pub struct RequestIdConfig {
340    /// Whether request-id generation/propagation is active for this route
341    pub enabled: bool,
342}
343
344impl From<bool> for RequestIdConfig {
345    fn from(enabled: bool) -> Self {
346        Self { enabled }
347    }
348}
349
350/// Per-route JWT authentication requirement.
351///
352/// `spikard-http` defines the canonical `JwtConfig` used by `ServerConfig.jwt_auth`, but
353/// `spikard-core` cannot depend on `spikard-http` (the dependency runs the other way), so that
354/// type cannot be reused here. This mirrors its fields so a later enforcement phase in
355/// `spikard-http` can convert between the two without losing information. ~keep
356///
357/// `secret` and `public_key` are both optional because asymmetric algorithms (RS256, ES256, ...)
358/// verify against a public key rather than a shared secret; see `fixtures/auth.json`'s
359/// `jwt_config_algorithm_rs256`, which carries `public_key` and no `secret` at all. Exactly one is
360/// expected to be populated for a given `algorithm`, but that cross-field invariant is left to a
361/// later enforcement phase rather than the type itself. ~keep
362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
363pub struct JwtAuthConfig {
364    /// Whether this per-route JWT auth requirement is active. Present on 21/21 `jwt_auth` fixture
365    /// payloads in the corpus; defaults to `true` because presence of a `jwt_auth` block has always
366    /// meant "enabled" up to now. Without this field a fixture setting `"enabled": false` would
367    /// silently keep auth on while the fixture's parse still succeeds — a vacuous pass. ~keep
368    #[serde(default = "default_true")]
369    pub enabled: bool,
370    /// Symmetric secret key for JWT verification (HS256, HS384, HS512)
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub secret: Option<String>,
373    /// Asymmetric public key for JWT verification (RS256, ES256, etc.)
374    #[serde(default, skip_serializing_if = "Option::is_none")]
375    pub public_key: Option<String>,
376    /// Required algorithm (HS256, HS384, HS512, RS256, etc.)
377    #[serde(default = "default_jwt_algorithm")]
378    pub algorithm: String,
379    /// Required audience claim
380    pub audience: Option<Vec<String>>,
381    /// Required issuer claim
382    pub issuer: Option<String>,
383    /// Leeway for expiration checks (seconds)
384    #[serde(default)]
385    pub leeway: u64,
386}
387
388fn default_jwt_algorithm() -> String {
389    "HS256".to_string()
390}
391
392/// Per-route API key authentication requirement.
393///
394/// Mirrors `spikard_http::ApiKeyConfig` for the same reason `JwtAuthConfig` mirrors
395/// `spikard_http::JwtConfig`: `spikard-core` cannot depend on `spikard-http`. ~keep
396#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
397pub struct ApiKeyAuthConfig {
398    /// Whether this per-route API key auth requirement is active. Present on 10/10 `api_key_auth`
399    /// fixture payloads in the corpus; defaults to `true` for the same reason as
400    /// [`JwtAuthConfig::enabled`]. ~keep
401    #[serde(default = "default_true")]
402    pub enabled: bool,
403    /// Valid API keys. Defaults to empty (rather than being a required field) so that
404    /// `fixtures/server_config.json`'s `server_jwt_and_api_key_auth_combined` payload
405    /// (`{"enabled": true, "header": "X-API-Key"}`, no `keys` at all) deserializes instead of
406    /// hard-failing with "missing field `keys`". An empty list is NOT "allow everyone": a later
407    /// enforcement phase MUST treat an empty `keys` list as a hard misconfiguration error, never
408    /// as an open gate. ~keep
409    #[serde(default)]
410    pub keys: Vec<String>,
411    /// Header name to check (e.g., "X-API-Key")
412    #[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/// Per-route roles/scopes/permissions authorization requirement.
421///
422/// `spikard_http::auth::Claims` does not yet carry roles, scopes, or permissions, so nothing can
423/// enforce this today. This type only defines the requirement shape; a later phase must extend
424/// `Claims` (or an equivalent claims-decoding path) to populate them before enforcement is
425/// possible. ~keep
426///
427/// Deserialization goes through [`AuthorizationConfigRepr`] rather than a derive so the fixture's
428/// singular `{"required_role": "admin"}` shape (`fixtures/problem_details.json`'s
429/// `problem_details_403_forbidden`) populates `required_roles` instead of being silently dropped
430/// as an unrecognized field — a config that parses to "no constraint" from real authorization
431/// data is a vacuous-pass bug, not a compatibility shim. `deny_unknown_fields` on the repr means
432/// any other unrecognized key is a loud deserialize error instead. ~keep
433#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
434pub struct AuthorizationConfig {
435    /// Roles the authenticated caller must have
436    pub required_roles: Vec<String>,
437    /// OAuth-style scopes the authenticated caller must have
438    pub required_scopes: Vec<String>,
439    /// Fine-grained permissions the authenticated caller must have
440    pub required_permissions: Vec<String>,
441    /// When true, the caller must satisfy every listed requirement (AND); when false, any single
442    /// listed requirement is sufficient (OR)
443    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/// Wire representation of [`AuthorizationConfig`], matching the exact JSON shapes fixtures and
458/// bindings send (both the singular `required_role` string and a plural `required_roles` array).
459/// `deny_unknown_fields` here is what turns future fixture drift into a deserialize error instead
460/// of a silent no-op. ~keep
461#[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/// A single lifecycle hook reference within a [`LifecycleHooksConfig`] phase.
496///
497/// Matches the fixture shape exactly (`fixtures/lifecycle_hooks.json`, `fixtures/di.json`): each
498/// entry is an object with a required `name` and `handler`, an optional list of dependency keys,
499/// and an optional free-form `config` blob (e.g. `{"max_requests": 10, "window_seconds": 60}` for
500/// a rate-limiting hook). `deny_unknown_fields` turns future fixture drift into a loud error. ~keep
501#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
502#[serde(deny_unknown_fields)]
503pub struct LifecycleHookRef {
504    /// Registered name of the hook to run, resolved against the server's `LifecycleHooks`
505    pub name: String,
506    /// Name of the handler function this hook invokes
507    pub handler: String,
508    /// Dependency keys this hook requires (for DI), resolved before the hook runs
509    #[serde(default)]
510    pub dependencies: Vec<String>,
511    /// Optional free-form configuration passed to the hook (e.g. rate-limit thresholds)
512    #[serde(default, skip_serializing_if = "Option::is_none")]
513    pub config: Option<serde_json::Value>,
514    /// Explicit execution order within the phase, where the corpus states one
515    /// (`fixtures/lifecycle_hooks.json`'s `hook_execution_order`). Array position already implies
516    /// an order, so this exists to let a fixture assert ordering rather than rely on it. ~keep
517    #[serde(default, skip_serializing_if = "Option::is_none")]
518    pub order: Option<u32>,
519}
520
521/// Per-route selection of registered lifecycle hooks.
522///
523/// `ServerConfig.lifecycle_hooks` holds `Arc<dyn LifecycleHook>` function pointers and is marked
524/// `#[serde(skip)]` / `#[alef(skip)]` because closures cannot be serialized or cross the FFI
525/// boundary. A per-route field with that same shape would be invisible to alef, and therefore
526/// invisible to every binding — defeating the purpose of exposing it here. This descriptor
527/// carries [`LifecycleHookRef`] entries instead: each one names a registered hook (plus its
528/// declared dependencies and optional config), so a later enforcement phase can resolve those
529/// names against the server's registered `LifecycleHooks` and run the matches for this route. The
530/// five fields mirror the five hook phases documented in the `tower-middleware-and-lifecycle`
531/// project convention (onRequest, preValidation, preHandler, onResponse, onError). ~keep
532#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
533pub struct LifecycleHooksConfig {
534    /// Hooks to run in the `on_request` phase
535    #[serde(default)]
536    pub on_request: Vec<LifecycleHookRef>,
537    /// Hooks to run in the `pre_validation` phase
538    #[serde(default)]
539    pub pre_validation: Vec<LifecycleHookRef>,
540    /// Hooks to run in the `pre_handler` phase
541    #[serde(default)]
542    pub pre_handler: Vec<LifecycleHookRef>,
543    /// Hooks to run in the `on_response` phase
544    #[serde(default)]
545    pub on_response: Vec<LifecycleHookRef>,
546    /// Hooks to run in the `on_error` phase
547    #[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    /// Real fixture payload: `fixtures/request_id.json` id `request_id_is_generated_when_not_provided`.
834    #[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    /// Real fixture payload: `fixtures/request_id.json` id `request_id_middleware_can_be_disabled`.
842    /// This is the payload that could not deserialize at all when `request_id` was `Option<bool>`:
843    /// `{"enabled": false}` is an object, and serde reports "invalid type: map, expected a boolean"
844    /// against a bare `bool` field.
845    #[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    /// End-to-end proof that `RouteMetadata` itself (not just the leaf `RequestIdConfig` type)
853    /// deserializes the disable fixture, since that is the payload's actual real-world path.
854    #[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    /// Real fixture payload: `fixtures/auth.json` id `jwt_config_algorithm_rs256`. RS256 verifies
878    /// against a public key and carries no `secret` at all; a `secret`-required type would fail
879    /// to deserialize this fixture. Also proves `enabled` is captured rather than silently
880    /// discarded.
881    #[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    /// Synthetic payload (no corpus fixture currently sets `"enabled": false` on `jwt_auth`), used
899    /// to prove `false` is representable and preserved rather than silently coerced to `true`.
900    #[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    /// Real fixture payload: `fixtures/auth.json` id `api_key_authentication_valid_key`. Proves
917    /// `enabled` is captured rather than silently discarded.
918    #[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    /// Synthetic payload (no corpus fixture currently sets `"enabled": false` on `api_key_auth`),
935    /// used to prove `false` is representable and preserved rather than silently coerced to `true`.
936    #[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    /// Real fixture payload: `fixtures/server_config.json` id `server_jwt_and_api_key_auth_combined`.
944    /// This is the only `api_key_auth` payload in the corpus that omits `keys` entirely and spells
945    /// the header field `header` instead of `header_name`. `keys` must default to empty rather than
946    /// hard-failing with "missing field `keys`" — see the field doc comment for why an empty list
947    /// is not itself a security hole (enforcement, not parsing, must reject it). The unrecognized
948    /// `header` key is simply ignored since `ApiKeyAuthConfig` has no `deny_unknown_fields`.
949    #[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    /// Real fixture payload: `fixtures/problem_details.json` id `problem_details_403_forbidden`.
981    /// The fixture uses the singular `required_role` string form; the config must actually
982    /// require that role, not silently parse to an empty (vacuously-passing) requirement.
983    #[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    /// Real fixture payload: `fixtures/lifecycle_hooks.json` id `onrequest_request_logging`.
1051    #[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    /// Real fixture payload: `fixtures/lifecycle_hooks.json` id `prevalidation_rate_limiting`.
1069    /// Covers the optional `config` blob.
1070    #[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    /// Real fixture payload: `fixtures/di.json` id `dependency_injection_in_lifecycle_hooks_success`.
1090    /// Covers the optional `dependencies` array and multiple phases in one payload.
1091    #[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    /// Real fixture payload: `fixtures/lifecycle_hooks.json` id `multiple_hooks_all_phases`.
1111    #[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}