1pub mod builder;
13pub mod generation;
14#[doc(hidden)]
15pub mod registry;
16pub mod validation;
17
18use crate::response::AiGenerator;
19use crate::response_rewriter::ResponseRewriter;
20use crate::{OpenApiOperation, OpenApiRoute, OpenApiSchema, OpenApiSpec};
21use axum::extract::{DefaultBodyLimit, Path as AxumPath, RawQuery};
22use axum::http::HeaderMap;
23use axum::response::IntoResponse;
24use axum::routing::*;
25use axum::{Json, Router};
26pub use builder::*;
27use chrono::Utc;
28pub use generation::*;
29use mockforge_foundation::ai_response::RequestContext;
30use mockforge_foundation::error::{Error, Result};
31use mockforge_foundation::latency::LatencyInjector;
32use mockforge_foundation::response_generation_trace::ResponseGenerationTrace;
33use mockforge_foundation::schema_diff::validation_diff;
34use once_cell::sync::Lazy;
35use openapiv3::ParameterSchemaOrContent;
36use serde_json::{json, Map, Value};
37use std::collections::{HashMap, HashSet, VecDeque};
38use std::sync::{Arc, Mutex};
39use tracing;
40pub use validation::*;
41
42#[derive(Clone)]
44pub struct OpenApiRouteRegistry {
45 spec: Arc<OpenApiSpec>,
47 routes: Vec<OpenApiRoute>,
49 options: ValidationOptions,
51 custom_fixture_loader: Option<Arc<crate::custom_fixture::CustomFixtureLoader>>,
53}
54
55#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, Default)]
57pub enum ValidationMode {
58 Disabled,
60 #[default]
62 Warn,
63 Enforce,
65}
66
67#[derive(Debug, Clone)]
69pub struct ValidationOptions {
70 pub request_mode: ValidationMode,
72 pub aggregate_errors: bool,
74 pub validate_responses: bool,
76 pub overrides: HashMap<String, ValidationMode>,
78 pub admin_skip_prefixes: Vec<String>,
80 pub response_template_expand: bool,
82 pub validation_status: Option<u16>,
84}
85
86impl Default for ValidationOptions {
87 fn default() -> Self {
88 Self {
89 request_mode: ValidationMode::Enforce,
90 aggregate_errors: true,
91 validate_responses: false,
92 overrides: HashMap::new(),
93 admin_skip_prefixes: Vec::new(),
94 response_template_expand: false,
95 validation_status: None,
96 }
97 }
98}
99
100#[derive(Clone)]
105pub struct RouterContext {
106 pub custom_fixture_loader: Option<Arc<crate::custom_fixture::CustomFixtureLoader>>,
108 pub latency_injector: Option<LatencyInjector>,
110 pub failure_injector: Option<mockforge_foundation::failure_injection::FailureInjector>,
112 pub response_rewriter: Option<Arc<dyn ResponseRewriter>>,
116 pub overrides_enabled: bool,
119 pub ai_generator: Option<Arc<dyn AiGenerator + Send + Sync>>,
121 pub mockai: Option<
125 Arc<
126 tokio::sync::RwLock<
127 dyn mockforge_foundation::intelligent_behavior::MockAiBehavior + Send + Sync,
128 >,
129 >,
130 >,
131 pub enable_full_validation: bool,
133 pub enable_template_expand: bool,
135 pub add_spec_endpoint: bool,
137}
138
139impl Default for RouterContext {
140 fn default() -> Self {
141 Self {
142 custom_fixture_loader: None,
143 latency_injector: None,
144 failure_injector: None,
145 response_rewriter: None,
146 overrides_enabled: false,
147 ai_generator: None,
148 mockai: None,
149 enable_full_validation: false,
150 enable_template_expand: false,
151 add_spec_endpoint: true,
152 }
153 }
154}
155
156fn openapi_body_limit_bytes() -> usize {
171 const DEFAULT_MB: usize = 50;
172 std::env::var("MOCKFORGE_HTTP_BODY_LIMIT_MB")
173 .ok()
174 .and_then(|v| v.parse::<usize>().ok())
175 .unwrap_or(DEFAULT_MB)
176 .saturating_mul(1024 * 1024)
177}
178
179impl OpenApiRouteRegistry {
180 pub fn new(spec: OpenApiSpec) -> Self {
182 Self::new_with_env(spec)
183 }
184
185 pub fn new_with_env(spec: OpenApiSpec) -> Self {
194 Self::new_with_env_and_persona(spec, None)
195 }
196
197 pub fn new_with_env_and_persona(
199 spec: OpenApiSpec,
200 persona: Option<Arc<mockforge_foundation::intelligent_behavior::Persona>>,
201 ) -> Self {
202 tracing::debug!("Creating OpenAPI route registry");
203 let spec = Arc::new(spec);
204 let routes = Self::generate_routes_with_persona(&spec, persona);
205 let options = ValidationOptions {
206 request_mode: match std::env::var("MOCKFORGE_REQUEST_VALIDATION")
207 .unwrap_or_else(|_| "enforce".into())
208 .to_ascii_lowercase()
209 .as_str()
210 {
211 "off" | "disable" | "disabled" => ValidationMode::Disabled,
212 "warn" | "warning" => ValidationMode::Warn,
213 _ => ValidationMode::Enforce,
214 },
215 aggregate_errors: std::env::var("MOCKFORGE_AGGREGATE_ERRORS")
216 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
217 .unwrap_or(true),
218 validate_responses: std::env::var("MOCKFORGE_RESPONSE_VALIDATION")
219 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
220 .unwrap_or(false),
221 overrides: HashMap::new(),
222 admin_skip_prefixes: Vec::new(),
223 response_template_expand: std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
224 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
225 .unwrap_or(false),
226 validation_status: std::env::var("MOCKFORGE_VALIDATION_STATUS")
227 .ok()
228 .and_then(|s| s.parse::<u16>().ok()),
229 };
230 Self {
231 spec,
232 routes,
233 options,
234 custom_fixture_loader: None,
235 }
236 }
237
238 pub fn new_with_options(spec: OpenApiSpec, options: ValidationOptions) -> Self {
240 Self::new_with_options_and_persona(spec, options, None)
241 }
242
243 pub fn new_with_options_and_persona(
245 spec: OpenApiSpec,
246 options: ValidationOptions,
247 persona: Option<Arc<mockforge_foundation::intelligent_behavior::Persona>>,
248 ) -> Self {
249 tracing::debug!("Creating OpenAPI route registry with custom options");
250 let spec = Arc::new(spec);
251 let routes = Self::generate_routes_with_persona(&spec, persona);
252 Self {
253 spec,
254 routes,
255 options,
256 custom_fixture_loader: None,
257 }
258 }
259
260 pub fn with_custom_fixture_loader(
262 mut self,
263 loader: Arc<crate::custom_fixture::CustomFixtureLoader>,
264 ) -> Self {
265 self.custom_fixture_loader = Some(loader);
266 self
267 }
268
269 pub fn clone_for_validation(&self) -> Self {
274 OpenApiRouteRegistry {
275 spec: self.spec.clone(),
276 routes: self.routes.clone(),
277 options: self.options.clone(),
278 custom_fixture_loader: self.custom_fixture_loader.clone(),
279 }
280 }
281
282 fn generate_routes_with_persona(
284 spec: &Arc<OpenApiSpec>,
285 persona: Option<Arc<mockforge_foundation::intelligent_behavior::Persona>>,
286 ) -> Vec<OpenApiRoute> {
287 let mut routes = Vec::new();
288
289 let all_paths_ops = spec.all_paths_and_operations();
290 tracing::debug!("Generating routes from OpenAPI spec with {} paths", all_paths_ops.len());
291
292 for (path, operations) in all_paths_ops {
293 tracing::debug!("Processing path: {}", path);
294 for (method, operation) in operations {
295 routes.push(OpenApiRoute::from_operation_with_persona(
296 &method,
297 path.clone(),
298 &operation,
299 spec.clone(),
300 persona.clone(),
301 ));
302 }
303 }
304
305 tracing::debug!("Generated {} total routes from OpenAPI spec", routes.len());
306 routes
307 }
308
309 pub fn routes(&self) -> &[OpenApiRoute] {
311 &self.routes
312 }
313
314 pub fn spec(&self) -> &OpenApiSpec {
316 &self.spec
317 }
318
319 fn normalize_path_for_dedup(path: &str) -> String {
323 let mut result = String::with_capacity(path.len());
324 let mut in_brace = false;
325 for ch in path.chars() {
326 if ch == '{' {
327 in_brace = true;
328 result.push_str("{_}");
329 } else if ch == '}' {
330 in_brace = false;
331 } else if !in_brace {
332 result.push(ch);
333 }
334 }
335 result
336 }
337
338 fn deduplicated_routes(&self) -> Vec<(String, &OpenApiRoute)> {
344 let mut result = Vec::new();
345 let mut registered_routes: HashSet<(String, String)> = HashSet::new();
346 let mut canonical_paths: HashMap<String, String> = HashMap::new();
347
348 for route in &self.routes {
349 if !route.is_valid_axum_path() {
350 tracing::warn!(
351 "Skipping route with unsupported path syntax: {} {}",
352 route.method,
353 route.path
354 );
355 continue;
356 }
357 let axum_path = route.axum_path();
358 let normalized = Self::normalize_path_for_dedup(&axum_path);
359 let axum_path = canonical_paths
360 .entry(normalized.clone())
361 .or_insert_with(|| axum_path.clone())
362 .clone();
363 let route_key = (route.method.clone(), normalized);
364 if !registered_routes.insert(route_key) {
365 tracing::debug!(
366 "Skipping duplicate route: {} {} (axum path: {})",
367 route.method,
368 route.path,
369 axum_path
370 );
371 continue;
372 }
373 result.push((axum_path, route));
374 }
375 result
376 }
377
378 fn route_for_method<H, T>(router: Router, path: &str, method: &str, handler: H) -> Router
382 where
383 H: axum::handler::Handler<T, ()>,
384 T: 'static,
385 {
386 match method {
387 "GET" => router.route(path, get(handler)),
388 "POST" => router.route(path, post(handler)),
389 "PUT" => router.route(path, put(handler)),
390 "DELETE" => router.route(path, delete(handler)),
391 "PATCH" => router.route(path, patch(handler)),
392 "HEAD" => router.route(path, head(handler)),
393 "OPTIONS" => router.route(path, options(handler)),
394 _ => router,
395 }
396 }
397
398 pub fn build_router(self) -> Router {
400 let ctx = RouterContext {
401 custom_fixture_loader: self.custom_fixture_loader.clone(),
402 enable_full_validation: true,
403 enable_template_expand: true,
404 add_spec_endpoint: true,
405 ..Default::default()
406 };
407 self.build_router_with_context(ctx)
408 }
409
410 fn build_router_with_context(self, ctx: RouterContext) -> Router {
415 let mut router = Router::new();
416 tracing::debug!("Building router from {} routes", self.routes.len());
417
418 let deduped = self.deduplicated_routes();
419 let ctx = Arc::new(ctx);
420 let validator = Arc::new(self.clone_for_validation());
428 for (axum_path, route) in &deduped {
429 tracing::debug!("Adding route: {} {}", route.method, route.path);
430 let operation = route.operation.clone();
431 let method = route.method.clone();
432 let path_template = route.path.clone();
433 let validator = validator.clone();
434 let route_clone = (*route).clone();
435 let ctx = ctx.clone();
436
437 let mut operation_tags = operation.tags.clone();
439 if let Some(operation_id) = &operation.operation_id {
440 operation_tags.push(operation_id.clone());
441 }
442
443 let handler = move |AxumPath(path_params): AxumPath<HashMap<String, String>>,
445 RawQuery(raw_query): RawQuery,
446 headers: HeaderMap,
447 body: axum::body::Bytes| async move {
448 tracing::debug!("Handling OpenAPI request: {} {}", method, path_template);
449
450 if let Some(ref loader) = ctx.custom_fixture_loader {
452 use crate::request_fingerprint::RequestFingerprint;
453 use axum::http::{Method, Uri};
454
455 let mut request_path = path_template.clone();
457 for (key, value) in &path_params {
458 request_path = request_path.replace(&format!("{{{}}}", key), value);
459 }
460
461 let normalized_request_path =
463 crate::custom_fixture::CustomFixtureLoader::normalize_path(&request_path);
464
465 let query_string =
467 raw_query.as_ref().map(|q| q.to_string()).unwrap_or_default();
468
469 let uri_str = if query_string.is_empty() {
472 normalized_request_path.clone()
473 } else {
474 format!("{}?{}", normalized_request_path, query_string)
475 };
476
477 if let Ok(uri) = uri_str.parse::<Uri>() {
478 let http_method =
479 Method::from_bytes(method.as_bytes()).unwrap_or(Method::GET);
480 let body_slice = if body.is_empty() {
481 None
482 } else {
483 Some(body.as_ref())
484 };
485 let fingerprint =
486 RequestFingerprint::new(http_method, &uri, &headers, body_slice);
487
488 tracing::debug!(
490 "Checking fixture for {} {} (template: '{}', request_path: '{}', normalized: '{}', fingerprint.path: '{}')",
491 method,
492 path_template,
493 path_template,
494 request_path,
495 normalized_request_path,
496 fingerprint.path
497 );
498
499 if let Some(custom_fixture) = loader.load_fixture(&fingerprint) {
500 tracing::debug!(
501 "Using custom fixture for {} {}",
502 method,
503 path_template
504 );
505
506 if custom_fixture.delay_ms > 0 {
508 tokio::time::sleep(tokio::time::Duration::from_millis(
509 custom_fixture.delay_ms,
510 ))
511 .await;
512 }
513
514 let response_body = if custom_fixture.response.is_string() {
516 custom_fixture.response.as_str().unwrap().to_string()
517 } else {
518 serde_json::to_string(&custom_fixture.response)
519 .unwrap_or_else(|_| "{}".to_string())
520 };
521
522 let json_value: Value = serde_json::from_str(&response_body)
524 .unwrap_or_else(|_| serde_json::json!({}));
525
526 let status = axum::http::StatusCode::from_u16(custom_fixture.status)
528 .unwrap_or(axum::http::StatusCode::OK);
529
530 let mut response = (status, Json(json_value)).into_response();
531
532 let response_headers = response.headers_mut();
534 for (key, value) in &custom_fixture.headers {
535 if let (Ok(header_name), Ok(header_value)) = (
536 axum::http::HeaderName::from_bytes(key.as_bytes()),
537 axum::http::HeaderValue::from_str(value),
538 ) {
539 response_headers.insert(header_name, header_value);
540 }
541 }
542
543 if !custom_fixture.headers.contains_key("content-type") {
545 response_headers.insert(
546 axum::http::header::CONTENT_TYPE,
547 axum::http::HeaderValue::from_static("application/json"),
548 );
549 }
550
551 return response;
552 }
553 }
554 }
555
556 if let Some(ref failure_injector) = ctx.failure_injector {
558 if let Some((status_code, error_message)) =
559 failure_injector.process_request(&operation_tags)
560 {
561 let payload = serde_json::json!({
562 "error": error_message,
563 "injected_failure": true
564 });
565 let body_bytes = serde_json::to_vec(&payload)
566 .unwrap_or_else(|_| br#"{"error":"injected failure"}"#.to_vec());
567 return axum::http::Response::builder()
568 .status(
569 axum::http::StatusCode::from_u16(status_code)
570 .unwrap_or(axum::http::StatusCode::INTERNAL_SERVER_ERROR),
571 )
572 .header(axum::http::header::CONTENT_TYPE, "application/json")
573 .body(axum::body::Body::from(body_bytes))
574 .expect("Response builder should create valid response");
575 }
576 }
577
578 if let Some(ref injector) = ctx.latency_injector {
580 if let Err(e) = injector.inject_latency(&operation_tags).await {
581 tracing::warn!("Failed to inject latency: {}", e);
582 }
583 }
584
585 let scenario = headers
587 .get("X-Mockforge-Scenario")
588 .and_then(|v| v.to_str().ok())
589 .map(|s| s.to_string())
590 .or_else(|| std::env::var("MOCKFORGE_HTTP_SCENARIO").ok());
591
592 let status_override = headers
593 .get("X-Mockforge-Response-Status")
594 .and_then(|v| v.to_str().ok())
595 .and_then(|s| s.parse::<u16>().ok());
596
597 let (selected_status, mock_response) = route_clone
599 .mock_response_with_status_and_scenario_and_override(
600 scenario.as_deref(),
601 status_override,
602 );
603
604 if ctx.enable_full_validation {
606 let mut path_map = Map::new();
608 for (k, v) in &path_params {
609 path_map.insert(k.clone(), Value::String(v.clone()));
610 }
611
612 let mut query_map = Map::new();
614 if let Some(ref q) = raw_query {
615 for (k, v) in url::form_urlencoded::parse(q.as_bytes()) {
616 query_map.insert(k.to_string(), Value::String(v.to_string()));
617 }
618 }
619
620 let mut header_map = Map::new();
622 for p_ref in &operation.parameters {
623 if let Some(openapiv3::Parameter::Header { parameter_data, .. }) =
624 p_ref.as_item()
625 {
626 let name_lc = parameter_data.name.to_ascii_lowercase();
627 if let Ok(hn) = axum::http::HeaderName::from_bytes(name_lc.as_bytes()) {
628 if let Some(val) = headers.get(hn) {
629 if let Ok(s) = val.to_str() {
630 header_map.insert(
631 parameter_data.name.clone(),
632 Value::String(s.to_string()),
633 );
634 }
635 }
636 }
637 }
638 }
639
640 let mut cookie_map = Map::new();
642 if let Some(val) = headers.get(axum::http::header::COOKIE) {
643 if let Ok(s) = val.to_str() {
644 for part in s.split(';') {
645 let part = part.trim();
646 if let Some((k, v)) = part.split_once('=') {
647 cookie_map.insert(k.to_string(), Value::String(v.to_string()));
648 }
649 }
650 }
651 }
652
653 let is_multipart = headers
655 .get(axum::http::header::CONTENT_TYPE)
656 .and_then(|v| v.to_str().ok())
657 .map(|ct| ct.starts_with("multipart/form-data"))
658 .unwrap_or(false);
659
660 #[allow(unused_assignments)]
662 let mut multipart_fields = HashMap::new();
663 let mut _multipart_files = HashMap::new();
664 let mut body_json: Option<Value> = None;
665
666 if is_multipart {
667 match extract_multipart_from_bytes(&body, &headers).await {
669 Ok((fields, files)) => {
670 multipart_fields = fields;
671 _multipart_files = files;
672 let mut body_obj = Map::new();
674 for (k, v) in &multipart_fields {
675 body_obj.insert(k.clone(), v.clone());
676 }
677 if !body_obj.is_empty() {
678 body_json = Some(Value::Object(body_obj));
679 }
680 }
681 Err(e) => {
682 tracing::warn!("Failed to parse multipart data: {}", e);
683 }
684 }
685 } else {
686 body_json = if !body.is_empty() {
688 serde_json::from_slice(&body).ok()
689 } else {
690 None
691 };
692 }
693
694 let actual_ct =
707 headers.get(axum::http::header::CONTENT_TYPE).and_then(|v| v.to_str().ok());
708 if let Err(ct_err) =
709 validator.check_request_content_type(&path_template, &method, actual_ct)
710 {
711 let status_code =
712 validator.options.validation_status.unwrap_or_else(|| {
713 std::env::var("MOCKFORGE_VALIDATION_STATUS")
714 .ok()
715 .and_then(|s| s.parse::<u16>().ok())
716 .unwrap_or(415)
717 });
718 let (client_mockforge_version, client_sent_at) =
719 mockforge_foundation::conformance_violations::read_client_stamps(
720 |name| {
721 headers
722 .get(name)
723 .and_then(|v| v.to_str().ok())
724 .map(|s| s.to_string())
725 },
726 );
727 mockforge_foundation::conformance_violations::record(
728 mockforge_foundation::conformance_violations::ServerConformanceViolation {
729 timestamp: Utc::now(),
730 method: method.to_string(),
731 path: path_template.clone(),
732 client_ip: "unknown".to_string(),
733 status: status_code,
734 reason: ct_err.clone(),
735 category: "content-types".to_string(),
736 occurrences: 1,
737 client_mockforge_version,
738 client_sent_at,
739 },
740 );
741 let status = axum::http::StatusCode::from_u16(status_code)
742 .unwrap_or(axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE);
743 let payload = serde_json::json!({
744 "error": "content_type_not_allowed",
745 "message": ct_err,
746 });
747 let body_bytes = serde_json::to_vec(&payload)
748 .unwrap_or_else(|_| br#"{"error":"Serialization failed"}"#.to_vec());
749 return axum::response::Response::builder()
750 .status(status)
751 .header("content-type", "application/json")
752 .body(axum::body::Body::from(body_bytes))
753 .unwrap_or_else(|_| {
754 axum::response::Response::builder()
755 .status(axum::http::StatusCode::INTERNAL_SERVER_ERROR)
756 .body(axum::body::Body::empty())
757 .unwrap()
758 });
759 }
760
761 if let Err(e) = validator.validate_request_with_all(
762 &path_template,
763 &method,
764 &path_map,
765 &query_map,
766 &header_map,
767 &cookie_map,
768 body_json.as_ref(),
769 ) {
770 let status_code =
772 validator.options.validation_status.unwrap_or_else(|| {
773 std::env::var("MOCKFORGE_VALIDATION_STATUS")
774 .ok()
775 .and_then(|s| s.parse::<u16>().ok())
776 .unwrap_or(400)
777 });
778
779 let payload = if status_code == 422 {
780 generate_enhanced_422_response(
782 &validator,
783 &path_template,
784 &method,
785 body_json.as_ref(),
786 &path_map,
787 &query_map,
788 &header_map,
789 &cookie_map,
790 )
791 } else {
792 let msg = format!("{}", e);
794 let detail_val = serde_json::from_str::<Value>(&msg)
795 .unwrap_or(serde_json::json!(msg));
796 json!({
797 "error": "request validation failed",
798 "detail": detail_val,
799 "method": method,
800 "path": path_template,
801 "timestamp": Utc::now().to_rfc3339(),
802 })
803 };
804
805 record_validation_error(&payload);
806
807 let reason = payload
814 .get("detail")
815 .and_then(|d| {
816 if d.is_string() {
817 d.as_str().map(|s| s.to_string())
818 } else {
819 serde_json::to_string(d).ok()
820 }
821 })
822 .unwrap_or_else(|| {
823 payload
824 .get("error")
825 .and_then(|v| v.as_str())
826 .unwrap_or("request validation failed")
827 .to_string()
828 });
829 let category = classify_validation_reason(&reason);
830 let (client_mockforge_version, client_sent_at) =
831 mockforge_foundation::conformance_violations::read_client_stamps(
832 |name| {
833 headers
834 .get(name)
835 .and_then(|v| v.to_str().ok())
836 .map(|s| s.to_string())
837 },
838 );
839 mockforge_foundation::conformance_violations::record(
840 mockforge_foundation::conformance_violations::ServerConformanceViolation {
841 timestamp: Utc::now(),
842 method: method.to_string(),
843 path: path_template.clone(),
844 client_ip: "unknown".to_string(),
845 status: status_code,
846 reason,
847 category,
848 occurrences: 1,
849 client_mockforge_version,
850 client_sent_at,
851 },
852 );
853
854 let status = axum::http::StatusCode::from_u16(status_code)
855 .unwrap_or(axum::http::StatusCode::BAD_REQUEST);
856
857 let body_bytes = serde_json::to_vec(&payload)
859 .unwrap_or_else(|_| br#"{"error":"Serialization failed"}"#.to_vec());
860
861 return axum::http::Response::builder()
862 .status(status)
863 .header(axum::http::header::CONTENT_TYPE, "application/json")
864 .body(axum::body::Body::from(body_bytes))
865 .expect("Response builder should create valid response with valid headers and body");
866 }
867 }
868
869 let mut final_response = mock_response.clone();
878 let env_expand: Option<bool> = std::env::var("MOCKFORGE_RESPONSE_TEMPLATE_EXPAND")
879 .ok()
880 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"));
881 let expand = match env_expand {
882 Some(v) => v,
883 None => {
884 ctx.enable_template_expand || validator.options.response_template_expand
885 }
886 };
887 if expand {
888 if let Some(ref rewriter) = ctx.response_rewriter {
889 rewriter.expand_tokens(&mut final_response);
890 }
891 }
892
893 if ctx.overrides_enabled {
895 if let Some(ref rewriter) = ctx.response_rewriter {
896 let op_tags =
897 operation.operation_id.clone().map(|id| vec![id]).unwrap_or_default();
898 rewriter.apply_overrides(
899 &operation.operation_id.clone().unwrap_or_default(),
900 &op_tags,
901 &path_template,
902 &mut final_response,
903 );
904 }
905 }
906
907 if ctx.enable_full_validation {
909 if validator.options.validate_responses {
911 if let Some((status_code, _response)) = operation
913 .responses
914 .responses
915 .iter()
916 .filter_map(|(status, resp)| match status {
917 openapiv3::StatusCode::Code(code)
918 if *code >= 200 && *code < 300 =>
919 {
920 resp.as_item().map(|r| ((*code), r))
921 }
922 openapiv3::StatusCode::Range(range)
923 if *range >= 200 && *range < 300 =>
924 {
925 resp.as_item().map(|r| (200, r))
926 }
927 _ => None,
928 })
929 .next()
930 {
931 if serde_json::from_value::<Value>(final_response.clone()).is_err() {
933 tracing::warn!(
934 "Response validation failed: invalid JSON for status {}",
935 status_code
936 );
937 }
938 }
939 }
940
941 let mut trace = ResponseGenerationTrace::new();
943 trace.set_final_payload(final_response.clone());
944
945 if let Some((_status_code, response_ref)) = operation
947 .responses
948 .responses
949 .iter()
950 .filter_map(|(status, resp)| match status {
951 openapiv3::StatusCode::Code(code) if *code == selected_status => {
952 resp.as_item().map(|r| ((*code), r))
953 }
954 openapiv3::StatusCode::Range(range)
955 if *range >= 200 && *range < 300 =>
956 {
957 resp.as_item().map(|r| (200, r))
958 }
959 _ => None,
960 })
961 .next()
962 .or_else(|| {
963 operation
965 .responses
966 .responses
967 .iter()
968 .filter_map(|(status, resp)| match status {
969 openapiv3::StatusCode::Code(code)
970 if *code >= 200 && *code < 300 =>
971 {
972 resp.as_item().map(|r| ((*code), r))
973 }
974 _ => None,
975 })
976 .next()
977 })
978 {
979 let response_item = response_ref;
981 if let Some(content) = response_item.content.get("application/json") {
983 if let Some(schema_ref) = &content.schema {
984 if let Some(schema) = schema_ref.as_item() {
986 if let Ok(schema_json) = serde_json::to_value(schema) {
987 let validation_errors =
989 validation_diff(&schema_json, &final_response);
990 trace.set_schema_validation_diff(validation_errors);
991 }
992 }
993 }
994 }
995 }
996
997 let mut response = Json(final_response).into_response();
999 response.extensions_mut().insert(trace);
1000 *response.status_mut() = axum::http::StatusCode::from_u16(selected_status)
1001 .unwrap_or(axum::http::StatusCode::OK);
1002 return response;
1003 }
1004
1005 let mut response = Json(final_response).into_response();
1007 *response.status_mut() = axum::http::StatusCode::from_u16(selected_status)
1008 .unwrap_or(axum::http::StatusCode::OK);
1009 response
1010 };
1011
1012 router = Self::route_for_method(router, axum_path, &route.method, handler);
1013 }
1014
1015 if ctx.add_spec_endpoint {
1017 let spec_json = serde_json::to_value(&self.spec.spec).unwrap_or(Value::Null);
1018 router = router.route("/openapi.json", get(move || async move { Json(spec_json) }));
1019 }
1020
1021 router.layer(DefaultBodyLimit::max(openapi_body_limit_bytes()))
1025 }
1026
1027 pub fn build_router_with_latency(self, latency_injector: LatencyInjector) -> Router {
1029 self.build_router_with_injectors(latency_injector, None)
1030 }
1031
1032 pub fn build_router_with_injectors(
1034 self,
1035 latency_injector: LatencyInjector,
1036 failure_injector: Option<mockforge_foundation::failure_injection::FailureInjector>,
1037 ) -> Router {
1038 self.build_router_with_injectors_and_overrides(
1039 latency_injector,
1040 failure_injector,
1041 None,
1042 false,
1043 )
1044 }
1045
1046 pub fn build_router_with_injectors_and_overrides(
1050 self,
1051 latency_injector: LatencyInjector,
1052 failure_injector: Option<mockforge_foundation::failure_injection::FailureInjector>,
1053 response_rewriter: Option<Arc<dyn ResponseRewriter>>,
1054 overrides_enabled: bool,
1055 ) -> Router {
1056 let ctx = RouterContext {
1057 custom_fixture_loader: self.custom_fixture_loader.clone(),
1058 latency_injector: Some(latency_injector),
1059 failure_injector,
1060 response_rewriter,
1061 overrides_enabled,
1062 enable_full_validation: true,
1063 enable_template_expand: true,
1064 add_spec_endpoint: true,
1065 ..Default::default()
1066 };
1067 self.build_router_with_context(ctx)
1068 }
1069
1070 pub fn get_route(&self, path: &str, method: &str) -> Option<&OpenApiRoute> {
1072 self.routes.iter().find(|route| route.path == path && route.method == method)
1073 }
1074
1075 pub fn get_routes_for_path(&self, path: &str) -> Vec<&OpenApiRoute> {
1077 self.routes.iter().filter(|route| route.path == path).collect()
1078 }
1079
1080 pub fn validate_request(&self, path: &str, method: &str, body: Option<&Value>) -> Result<()> {
1082 self.validate_request_with(path, method, &Map::new(), &Map::new(), body)
1083 }
1084
1085 pub fn check_request_content_type(
1101 &self,
1102 path: &str,
1103 method: &str,
1104 actual_content_type: Option<&str>,
1105 ) -> std::result::Result<(), String> {
1106 let Some(route) = self.get_route(path, method) else {
1107 return Ok(());
1108 };
1109 let Some(rb_ref) = &route.operation.request_body else {
1110 return Ok(());
1111 };
1112 let request_body = match rb_ref {
1113 openapiv3::ReferenceOr::Item(rb) => rb,
1114 openapiv3::ReferenceOr::Reference { reference } => {
1115 let resolved = self
1116 .spec
1117 .spec
1118 .components
1119 .as_ref()
1120 .and_then(|components| {
1121 components
1122 .request_bodies
1123 .get(reference.trim_start_matches("#/components/requestBodies/"))
1124 })
1125 .and_then(|rb_ref| rb_ref.as_item());
1126 let Some(rb) = resolved else { return Ok(()) };
1127 rb
1128 }
1129 };
1130 if request_body.content.is_empty() {
1131 return Ok(());
1132 }
1133 let actual = actual_content_type
1134 .and_then(|s| s.split(';').next())
1135 .map(|s| s.trim().to_ascii_lowercase());
1136 let Some(actual) = actual else {
1137 return Ok(());
1142 };
1143 let allowed: Vec<String> = request_body
1144 .content
1145 .keys()
1146 .map(|k| k.split(';').next().unwrap_or(k).trim().to_ascii_lowercase())
1147 .collect();
1148 if allowed.iter().any(|a| a == &actual) {
1149 return Ok(());
1150 }
1151 Err(format!(
1152 "Content-Type '{actual}' not allowed; spec declares: [{}]",
1153 allowed.join(", ")
1154 ))
1155 }
1156
1157 pub fn validate_request_with(
1159 &self,
1160 path: &str,
1161 method: &str,
1162 path_params: &Map<String, Value>,
1163 query_params: &Map<String, Value>,
1164 body: Option<&Value>,
1165 ) -> Result<()> {
1166 self.validate_request_with_all(
1167 path,
1168 method,
1169 path_params,
1170 query_params,
1171 &Map::new(),
1172 &Map::new(),
1173 body,
1174 )
1175 }
1176
1177 #[allow(clippy::too_many_arguments)]
1190 pub fn run_validation_with_recording(
1191 &self,
1192 path_template: &str,
1193 method: &str,
1194 path_params: &Map<String, Value>,
1195 query_params: &Map<String, Value>,
1196 header_map: &Map<String, Value>,
1197 cookie_map: &Map<String, Value>,
1198 body: Option<&Value>,
1199 ) -> std::result::Result<(), (u16, Value)> {
1200 let e = match self.validate_request_with_all(
1201 path_template,
1202 method,
1203 path_params,
1204 query_params,
1205 header_map,
1206 cookie_map,
1207 body,
1208 ) {
1209 Ok(()) => {
1210 mockforge_foundation::conformance_violations::record_ok();
1214 return Ok(());
1215 }
1216 Err(e) => e,
1217 };
1218
1219 let status_code = self.options.validation_status.unwrap_or_else(|| {
1220 std::env::var("MOCKFORGE_VALIDATION_STATUS")
1221 .ok()
1222 .and_then(|s| s.parse::<u16>().ok())
1223 .unwrap_or(400)
1224 });
1225
1226 let payload = if status_code == 422 {
1227 generate_enhanced_422_response(
1228 self,
1229 path_template,
1230 method,
1231 body,
1232 path_params,
1233 query_params,
1234 header_map,
1235 cookie_map,
1236 )
1237 } else {
1238 let msg = format!("{}", e);
1239 let detail_val = serde_json::from_str::<Value>(&msg).unwrap_or(serde_json::json!(msg));
1240 json!({
1241 "error": "request validation failed",
1242 "detail": detail_val,
1243 "method": method,
1244 "path": path_template,
1245 "timestamp": Utc::now().to_rfc3339(),
1246 })
1247 };
1248
1249 record_validation_error(&payload);
1250
1251 let reason = payload
1252 .get("detail")
1253 .and_then(|d| {
1254 if d.is_string() {
1255 d.as_str().map(|s| s.to_string())
1256 } else {
1257 serde_json::to_string(d).ok()
1258 }
1259 })
1260 .unwrap_or_else(|| {
1261 payload
1262 .get("error")
1263 .and_then(|v| v.as_str())
1264 .unwrap_or("request validation failed")
1265 .to_string()
1266 });
1267 let category = classify_validation_reason(&reason);
1268 tracing::debug!(
1276 target: "mockforge::conformance",
1277 method = %method,
1278 path = %path_template,
1279 status = status_code,
1280 category = %category,
1281 reason = %reason,
1282 "request conformance violation"
1283 );
1284 let (client_mockforge_version, client_sent_at) =
1285 mockforge_foundation::conformance_violations::read_client_stamps(|name| {
1286 header_map
1287 .iter()
1288 .find(|(k, _)| k.eq_ignore_ascii_case(name))
1289 .and_then(|(_, v)| v.as_str().map(|s| s.to_string()))
1290 });
1291 mockforge_foundation::conformance_violations::record(
1292 mockforge_foundation::conformance_violations::ServerConformanceViolation {
1293 timestamp: Utc::now(),
1294 method: method.to_string(),
1295 path: path_template.to_string(),
1296 client_ip: "unknown".to_string(),
1297 status: status_code,
1298 reason,
1299 category,
1300 occurrences: 1,
1301 client_mockforge_version,
1302 client_sent_at,
1303 },
1304 );
1305
1306 if mockforge_foundation::unknown_paths::shadow_mode_enabled() {
1313 return Ok(());
1314 }
1315
1316 Err((status_code, payload))
1317 }
1318
1319 #[allow(clippy::too_many_arguments)]
1321 pub fn validate_request_with_all(
1322 &self,
1323 path: &str,
1324 method: &str,
1325 path_params: &Map<String, Value>,
1326 query_params: &Map<String, Value>,
1327 header_params: &Map<String, Value>,
1328 cookie_params: &Map<String, Value>,
1329 body: Option<&Value>,
1330 ) -> Result<()> {
1331 for pref in &self.options.admin_skip_prefixes {
1333 if !pref.is_empty() && path.starts_with(pref) {
1334 return Ok(());
1335 }
1336 }
1337 let env_mode = std::env::var("MOCKFORGE_REQUEST_VALIDATION").ok().map(|v| {
1339 match v.to_ascii_lowercase().as_str() {
1340 "off" | "disable" | "disabled" => ValidationMode::Disabled,
1341 "warn" | "warning" => ValidationMode::Warn,
1342 _ => ValidationMode::Enforce,
1343 }
1344 });
1345 let aggregate = std::env::var("MOCKFORGE_AGGREGATE_ERRORS")
1346 .ok()
1347 .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
1348 .unwrap_or(self.options.aggregate_errors);
1349 let env_overrides: Option<Map<String, Value>> =
1351 std::env::var("MOCKFORGE_VALIDATION_OVERRIDES_JSON")
1352 .ok()
1353 .and_then(|s| serde_json::from_str::<Value>(&s).ok())
1354 .and_then(|v| v.as_object().cloned());
1355 let mut effective_mode = env_mode.unwrap_or(self.options.request_mode.clone());
1357 if let Some(map) = &env_overrides {
1359 if let Some(v) = map.get(&format!("{} {}", method, path)) {
1360 if let Some(m) = v.as_str() {
1361 effective_mode = match m {
1362 "off" => ValidationMode::Disabled,
1363 "warn" => ValidationMode::Warn,
1364 _ => ValidationMode::Enforce,
1365 };
1366 }
1367 }
1368 }
1369 if let Some(override_mode) = self.options.overrides.get(&format!("{} {}", method, path)) {
1371 effective_mode = override_mode.clone();
1372 }
1373 if matches!(effective_mode, ValidationMode::Disabled) {
1374 return Ok(());
1375 }
1376 if let Some(route) = self.get_route(path, method) {
1377 if matches!(effective_mode, ValidationMode::Disabled) {
1378 return Ok(());
1379 }
1380 let mut errors: Vec<String> = Vec::new();
1381 let mut details: Vec<Value> = Vec::new();
1382 if let Some(schema) = &route.operation.request_body {
1384 if let Some(value) = body {
1385 let request_body = match schema {
1387 openapiv3::ReferenceOr::Item(rb) => Some(rb),
1388 openapiv3::ReferenceOr::Reference { reference } => {
1389 self.spec
1391 .spec
1392 .components
1393 .as_ref()
1394 .and_then(|components| {
1395 components.request_bodies.get(
1396 reference.trim_start_matches("#/components/requestBodies/"),
1397 )
1398 })
1399 .and_then(|rb_ref| rb_ref.as_item())
1400 }
1401 };
1402
1403 if let Some(rb) = request_body {
1404 if let Some(content) = rb.content.get("application/json") {
1405 if let Some(schema_ref) = &content.schema {
1406 let root_schema = match schema_ref {
1419 openapiv3::ReferenceOr::Item(s) => Some((*s).clone()),
1420 openapiv3::ReferenceOr::Reference { reference } => {
1421 self.spec.get_schema(reference).map(|s| s.schema.clone())
1422 }
1423 };
1424 if let Some(root_schema) = root_schema {
1425 let result = crate::schema_ref_resolver::build_validator(
1426 &root_schema,
1427 &self.spec.spec,
1428 )
1429 .and_then(|validator| {
1430 let errs: Vec<String> = validator
1431 .iter_errors(value)
1432 .map(|e| e.to_string())
1433 .collect();
1434 if errs.is_empty() {
1435 Ok(())
1436 } else {
1437 Err(errs.join("; "))
1438 }
1439 });
1440 if let Err(error_msg) = result {
1441 errors
1442 .push(format!("body validation failed: {}", error_msg));
1443 if aggregate {
1444 details.push(serde_json::json!({"path":"body","code":"schema_validation","message":error_msg}));
1445 }
1446 }
1447 } else if let openapiv3::ReferenceOr::Reference { reference } =
1448 schema_ref
1449 {
1450 errors.push(format!("body validation failed: could not resolve schema reference {}", reference));
1452 if aggregate {
1453 details.push(serde_json::json!({"path":"body","code":"reference_error","message":"Could not resolve schema reference"}));
1454 }
1455 }
1456 }
1457 }
1458 } else {
1459 errors.push("body validation failed: could not resolve request body or no application/json content".to_string());
1461 if aggregate {
1462 details.push(serde_json::json!({"path":"body","code":"reference_error","message":"Could not resolve request body reference"}));
1463 }
1464 }
1465 } else {
1466 errors.push("body: Request body is required but not provided".to_string());
1467 details.push(serde_json::json!({"path":"body","code":"required","message":"Request body is required"}));
1468 }
1469 } else if body.is_some() {
1470 tracing::debug!("Body provided for operation without requestBody; accepting");
1472 }
1473
1474 for p_ref in &route.operation.parameters {
1476 if let Some(p) = p_ref.as_item() {
1477 match p {
1478 openapiv3::Parameter::Path { parameter_data, .. } => {
1479 validate_parameter(
1480 parameter_data,
1481 path_params,
1482 "path",
1483 aggregate,
1484 &mut errors,
1485 &mut details,
1486 );
1487 }
1488 openapiv3::Parameter::Query {
1489 parameter_data,
1490 style,
1491 ..
1492 } => {
1493 let deep_value = if matches!(style, openapiv3::QueryStyle::DeepObject) {
1496 let prefix_bracket = format!("{}[", parameter_data.name);
1497 let mut obj = Map::new();
1498 for (key, val) in query_params.iter() {
1499 if let Some(rest) = key.strip_prefix(&prefix_bracket) {
1500 if let Some(prop) = rest.strip_suffix(']') {
1501 obj.insert(prop.to_string(), val.clone());
1502 }
1503 }
1504 }
1505 if obj.is_empty() {
1506 None
1507 } else {
1508 Some(Value::Object(obj))
1509 }
1510 } else {
1511 None
1512 };
1513 let style_str = match style {
1514 openapiv3::QueryStyle::Form => Some("form"),
1515 openapiv3::QueryStyle::SpaceDelimited => Some("spaceDelimited"),
1516 openapiv3::QueryStyle::PipeDelimited => Some("pipeDelimited"),
1517 openapiv3::QueryStyle::DeepObject => Some("deepObject"),
1518 };
1519 validate_parameter_with_deep_object(
1520 parameter_data,
1521 query_params,
1522 "query",
1523 deep_value,
1524 style_str,
1525 aggregate,
1526 &mut errors,
1527 &mut details,
1528 );
1529 }
1530 openapiv3::Parameter::Header { parameter_data, .. } => {
1531 validate_parameter(
1532 parameter_data,
1533 header_params,
1534 "header",
1535 aggregate,
1536 &mut errors,
1537 &mut details,
1538 );
1539 }
1540 openapiv3::Parameter::Cookie { parameter_data, .. } => {
1541 validate_parameter(
1542 parameter_data,
1543 cookie_params,
1544 "cookie",
1545 aggregate,
1546 &mut errors,
1547 &mut details,
1548 );
1549 }
1550 }
1551 }
1552 }
1553 if errors.is_empty() {
1554 return Ok(());
1555 }
1556 match effective_mode {
1557 ValidationMode::Disabled => Ok(()),
1558 ValidationMode::Warn => {
1559 tracing::warn!("Request validation warnings: {:?}", errors);
1560 Ok(())
1561 }
1562 ValidationMode::Enforce => Err(Error::validation(
1563 serde_json::json!({"errors": errors, "details": details}).to_string(),
1564 )),
1565 }
1566 } else {
1567 Err(Error::internal(format!("Route {} {} not found in OpenAPI spec", method, path)))
1568 }
1569 }
1570
1571 pub fn paths(&self) -> Vec<String> {
1575 let mut paths: Vec<String> = self.routes.iter().map(|route| route.path.clone()).collect();
1576 paths.sort();
1577 paths.dedup();
1578 paths
1579 }
1580
1581 pub fn methods(&self) -> Vec<String> {
1583 let mut methods: Vec<String> =
1584 self.routes.iter().map(|route| route.method.clone()).collect();
1585 methods.sort();
1586 methods.dedup();
1587 methods
1588 }
1589
1590 pub fn get_operation(&self, path: &str, method: &str) -> Option<OpenApiOperation> {
1592 self.get_route(path, method).map(|route| {
1593 OpenApiOperation::from_operation(
1594 &route.method,
1595 route.path.clone(),
1596 &route.operation,
1597 &self.spec,
1598 )
1599 })
1600 }
1601
1602 pub fn extract_path_parameters(&self, path: &str, method: &str) -> HashMap<String, String> {
1604 let mut best: Option<(usize, HashMap<String, String>)> = None;
1610 for route in &self.routes {
1611 if route.method != method {
1612 continue;
1613 }
1614
1615 if let Some(params) = self.match_path_to_route(path, &route.path) {
1616 let static_segments = route
1617 .path
1618 .trim_start_matches('/')
1619 .split('/')
1620 .filter(|s| !(s.starts_with('{') && s.ends_with('}')))
1621 .count();
1622 let is_more_specific = match &best {
1623 None => true,
1624 Some((score, _)) => static_segments > *score,
1625 };
1626 if is_more_specific {
1627 best = Some((static_segments, params));
1628 }
1629 }
1630 }
1631 best.map(|(_, params)| params).unwrap_or_default()
1632 }
1633
1634 fn match_path_to_route(
1636 &self,
1637 request_path: &str,
1638 route_pattern: &str,
1639 ) -> Option<HashMap<String, String>> {
1640 let mut params = HashMap::new();
1641
1642 let request_segments: Vec<&str> = request_path.trim_start_matches('/').split('/').collect();
1644 let pattern_segments: Vec<&str> =
1645 route_pattern.trim_start_matches('/').split('/').collect();
1646
1647 if request_segments.len() != pattern_segments.len() {
1648 return None;
1649 }
1650
1651 for (req_seg, pat_seg) in request_segments.iter().zip(pattern_segments.iter()) {
1652 if pat_seg.starts_with('{') && pat_seg.ends_with('}') {
1653 if req_seg.is_empty() {
1658 return None;
1659 }
1660 let param_name = &pat_seg[1..pat_seg.len() - 1];
1661 params.insert(param_name.to_string(), req_seg.to_string());
1662 } else if req_seg != pat_seg {
1663 return None;
1665 }
1666 }
1667
1668 Some(params)
1669 }
1670
1671 pub fn convert_path_to_axum(openapi_path: &str) -> String {
1674 openapi_path.to_string()
1676 }
1677
1678 pub fn build_router_with_ai(
1680 &self,
1681 ai_generator: Option<Arc<dyn AiGenerator + Send + Sync>>,
1682 ) -> Router {
1683 let mut router = Router::new();
1684 let deduped = self.deduplicated_routes();
1685 tracing::debug!("Building router with AI support from {} routes", self.routes.len());
1686
1687 let validator = Arc::new(self.clone_for_validation());
1691 for (axum_path, route) in &deduped {
1692 tracing::debug!("Adding AI-enabled route: {} {}", route.method, route.path);
1693
1694 let route_clone = (*route).clone();
1695 let ai_generator_clone = ai_generator.clone();
1696 let validator_clone = validator.clone();
1700
1701 let handler = move |AxumPath(path_params): AxumPath<HashMap<String, String>>,
1703 axum::extract::Query(query_params): axum::extract::Query<
1704 HashMap<String, String>,
1705 >,
1706 headers: HeaderMap,
1707 body: Option<Json<Value>>| {
1708 let route = route_clone.clone();
1709 let ai_generator = ai_generator_clone.clone();
1710 let validator = validator_clone.clone();
1711
1712 async move {
1713 let mut path_map = Map::new();
1718 for (k, v) in &path_params {
1719 path_map.insert(k.clone(), Value::String(v.clone()));
1720 }
1721 let mut query_map = Map::new();
1722 for (k, v) in &query_params {
1723 query_map.insert(k.clone(), Value::String(v.clone()));
1724 }
1725 let mut header_map = Map::new();
1726 for (k, v) in headers.iter() {
1727 if let Ok(s) = v.to_str() {
1728 header_map.insert(k.to_string(), Value::String(s.to_string()));
1729 }
1730 }
1731 let body_val: Option<&Value> = body.as_ref().map(|Json(b)| b);
1732 if let Err((status_code, payload)) = validator.run_validation_with_recording(
1733 &route.path,
1734 &route.method,
1735 &path_map,
1736 &query_map,
1737 &header_map,
1738 &Map::new(),
1739 body_val,
1740 ) {
1741 let status = axum::http::StatusCode::from_u16(status_code)
1742 .unwrap_or(axum::http::StatusCode::BAD_REQUEST);
1743 return (status, Json(payload));
1744 }
1745
1746 tracing::debug!(
1747 "Handling AI request for route: {} {}",
1748 route.method,
1749 route.path
1750 );
1751
1752 let mut context = RequestContext::new(route.method.clone(), route.path.clone());
1754
1755 context.headers = headers
1757 .iter()
1758 .map(|(k, v)| {
1759 (k.to_string(), Value::String(v.to_str().unwrap_or("").to_string()))
1760 })
1761 .collect();
1762
1763 context.body = body.map(|Json(b)| b);
1765
1766 let (status, response) = if let (Some(generator), Some(_ai_config)) =
1768 (ai_generator, &route.ai_config)
1769 {
1770 route
1771 .mock_response_with_status_async(&context, Some(generator.as_ref()))
1772 .await
1773 } else {
1774 route.mock_response_with_status()
1776 };
1777
1778 (
1779 axum::http::StatusCode::from_u16(status)
1780 .unwrap_or(axum::http::StatusCode::OK),
1781 Json(response),
1782 )
1783 }
1784 };
1785
1786 router = Self::route_for_method(router, axum_path, &route.method, handler);
1787 }
1788
1789 router.layer(DefaultBodyLimit::max(openapi_body_limit_bytes()))
1793 }
1794
1795 pub fn build_router_with_mockai(
1806 &self,
1807 mockai: Option<
1808 Arc<
1809 tokio::sync::RwLock<
1810 dyn mockforge_foundation::intelligent_behavior::MockAiBehavior + Send + Sync,
1811 >,
1812 >,
1813 >,
1814 ) -> Router {
1815 use mockforge_foundation::intelligent_behavior::Request as MockAIRequest;
1816
1817 let mut router = Router::new();
1818 let deduped = self.deduplicated_routes();
1819 tracing::debug!("Building router with MockAI support from {} routes", self.routes.len());
1820
1821 let custom_loader = self.custom_fixture_loader.clone();
1822 let validator = Arc::new(self.clone_for_validation());
1826 for (axum_path, route) in &deduped {
1827 tracing::debug!("Adding MockAI-enabled route: {} {}", route.method, route.path);
1828
1829 let route_clone = (*route).clone();
1830 let mockai_clone = mockai.clone();
1831 let custom_loader_clone = custom_loader.clone();
1832 let validator_clone = validator.clone();
1838
1839 let handler = move |AxumPath(path_params): AxumPath<HashMap<String, String>>,
1855 query: axum::extract::Query<HashMap<String, String>>,
1856 headers: HeaderMap,
1857 body_bytes: axum::body::Bytes| {
1858 let route = route_clone.clone();
1859 let mockai = mockai_clone.clone();
1860 let validator = validator_clone.clone();
1861
1862 async move {
1863 let mut path_map = Map::new();
1864 for (k, v) in &path_params {
1865 path_map.insert(k.clone(), Value::String(v.clone()));
1866 }
1867 let mut query_map = Map::new();
1868 for (k, v) in &query.0 {
1869 query_map.insert(k.clone(), Value::String(v.clone()));
1870 }
1871 let mut header_map = Map::new();
1872 for (k, v) in headers.iter() {
1873 if let Ok(s) = v.to_str() {
1874 header_map.insert(k.to_string(), Value::String(s.to_string()));
1875 }
1876 }
1877
1878 if !body_bytes.is_empty() {
1884 let actual_ct = headers
1885 .get(axum::http::header::CONTENT_TYPE)
1886 .and_then(|v| v.to_str().ok());
1887 if let Err(ct_err) = validator.check_request_content_type(
1888 &route.path,
1889 &route.method,
1890 actual_ct,
1891 ) {
1892 let status_code =
1893 validator.options.validation_status.unwrap_or_else(|| {
1894 std::env::var("MOCKFORGE_VALIDATION_STATUS")
1895 .ok()
1896 .and_then(|s| s.parse::<u16>().ok())
1897 .unwrap_or(415)
1898 });
1899 let (client_mockforge_version, client_sent_at) =
1900 mockforge_foundation::conformance_violations::read_client_stamps(
1901 |name| {
1902 headers
1903 .get(name)
1904 .and_then(|v| v.to_str().ok())
1905 .map(|s| s.to_string())
1906 },
1907 );
1908 mockforge_foundation::conformance_violations::record(
1909 mockforge_foundation::conformance_violations::ServerConformanceViolation {
1910 timestamp: Utc::now(),
1911 method: route.method.clone(),
1912 path: route.path.clone(),
1913 client_ip: "unknown".to_string(),
1914 status: status_code,
1915 reason: ct_err.clone(),
1916 category: "content-types".to_string(),
1917 occurrences: 1,
1918 client_mockforge_version,
1919 client_sent_at,
1920 },
1921 );
1922 let status = axum::http::StatusCode::from_u16(status_code)
1923 .unwrap_or(axum::http::StatusCode::UNSUPPORTED_MEDIA_TYPE);
1924 return (
1925 status,
1926 Json(serde_json::json!({
1927 "error": "content_type_not_allowed",
1928 "message": ct_err,
1929 })),
1930 );
1931 }
1932 }
1933
1934 let body: Option<Json<Value>> = if body_bytes.is_empty() {
1940 None
1941 } else {
1942 serde_json::from_slice::<Value>(&body_bytes).ok().map(Json)
1943 };
1944
1945 let body_val: Option<&Value> = body.as_ref().map(|Json(b)| b);
1950 if let Err((status_code, payload)) = validator.run_validation_with_recording(
1951 &route.path,
1952 &route.method,
1953 &path_map,
1954 &query_map,
1955 &header_map,
1956 &Map::new(),
1957 body_val,
1958 ) {
1959 let status = axum::http::StatusCode::from_u16(status_code)
1960 .unwrap_or(axum::http::StatusCode::BAD_REQUEST);
1961 return (status, Json(payload));
1962 }
1963
1964 tracing::info!(
1965 "[FIXTURE DEBUG] Starting fixture check for {} {} (custom_loader available: {})",
1966 route.method,
1967 route.path,
1968 custom_loader_clone.is_some()
1969 );
1970
1971 if let Some(ref loader) = custom_loader_clone {
1973 use crate::request_fingerprint::RequestFingerprint;
1974 use axum::http::{Method, Uri};
1975
1976 let query_string = if query.0.is_empty() {
1978 String::new()
1979 } else {
1980 query
1981 .0
1982 .iter()
1983 .map(|(k, v)| format!("{}={}", k, v))
1984 .collect::<Vec<_>>()
1985 .join("&")
1986 };
1987
1988 let normalized_request_path =
1990 crate::custom_fixture::CustomFixtureLoader::normalize_path(&route.path);
1991
1992 tracing::info!(
1993 "[FIXTURE DEBUG] Path normalization: original='{}', normalized='{}'",
1994 route.path,
1995 normalized_request_path
1996 );
1997
1998 let uri_str = if query_string.is_empty() {
2000 normalized_request_path.clone()
2001 } else {
2002 format!("{}?{}", normalized_request_path, query_string)
2003 };
2004
2005 tracing::info!(
2006 "[FIXTURE DEBUG] URI construction: uri_str='{}', query_string='{}'",
2007 uri_str,
2008 query_string
2009 );
2010
2011 if let Ok(uri) = uri_str.parse::<Uri>() {
2012 let http_method =
2013 Method::from_bytes(route.method.as_bytes()).unwrap_or(Method::GET);
2014
2015 let body_bytes =
2017 body.as_ref().and_then(|Json(b)| serde_json::to_vec(b).ok());
2018 let body_slice = body_bytes.as_deref();
2019
2020 let fingerprint =
2021 RequestFingerprint::new(http_method, &uri, &headers, body_slice);
2022
2023 tracing::info!(
2024 "[FIXTURE DEBUG] RequestFingerprint created: method='{}', path='{}', query='{}', body_hash={:?}",
2025 fingerprint.method,
2026 fingerprint.path,
2027 fingerprint.query,
2028 fingerprint.body_hash
2029 );
2030
2031 let available_fixtures = loader.has_fixture(&fingerprint);
2033 tracing::info!(
2034 "[FIXTURE DEBUG] Fixture check result: has_fixture={}",
2035 available_fixtures
2036 );
2037
2038 if let Some(custom_fixture) = loader.load_fixture(&fingerprint) {
2039 tracing::info!(
2040 "[FIXTURE DEBUG] ✅ FIXTURE MATCHED! Using custom fixture for {} {} (status: {}, path: '{}')",
2041 route.method,
2042 route.path,
2043 custom_fixture.status,
2044 custom_fixture.path
2045 );
2046
2047 if custom_fixture.delay_ms > 0 {
2049 tokio::time::sleep(tokio::time::Duration::from_millis(
2050 custom_fixture.delay_ms,
2051 ))
2052 .await;
2053 }
2054
2055 let response_body = if custom_fixture.response.is_string() {
2057 custom_fixture.response.as_str().unwrap().to_string()
2058 } else {
2059 serde_json::to_string(&custom_fixture.response)
2060 .unwrap_or_else(|_| "{}".to_string())
2061 };
2062
2063 let json_value: Value = serde_json::from_str(&response_body)
2065 .unwrap_or_else(|_| serde_json::json!({}));
2066
2067 let status =
2069 axum::http::StatusCode::from_u16(custom_fixture.status)
2070 .unwrap_or(axum::http::StatusCode::OK);
2071
2072 return (status, Json(json_value));
2074 } else {
2075 tracing::warn!(
2076 "[FIXTURE DEBUG] ❌ No fixture match found for {} {} (fingerprint.path='{}', normalized='{}')",
2077 route.method,
2078 route.path,
2079 fingerprint.path,
2080 normalized_request_path
2081 );
2082 }
2083 } else {
2084 tracing::warn!("[FIXTURE DEBUG] Failed to parse URI: '{}'", uri_str);
2085 }
2086 } else {
2087 tracing::warn!(
2088 "[FIXTURE DEBUG] Custom fixture loader not available for {} {}",
2089 route.method,
2090 route.path
2091 );
2092 }
2093
2094 tracing::debug!(
2095 "Handling MockAI request for route: {} {}",
2096 route.method,
2097 route.path
2098 );
2099
2100 let mockai_query = query.0;
2102
2103 let method_upper = route.method.to_uppercase();
2108 let should_use_mockai =
2109 matches!(method_upper.as_str(), "POST" | "PUT" | "PATCH" | "DELETE");
2110
2111 if should_use_mockai {
2112 if let Some(mockai_arc) = mockai {
2113 let mockai_guard = mockai_arc.read().await;
2114
2115 let mut mockai_headers = HashMap::new();
2117 for (k, v) in headers.iter() {
2118 mockai_headers
2119 .insert(k.to_string(), v.to_str().unwrap_or("").to_string());
2120 }
2121
2122 let mockai_request = MockAIRequest {
2123 method: route.method.clone(),
2124 path: route.path.clone(),
2125 body: body.as_ref().map(|Json(b)| b.clone()),
2126 query_params: mockai_query,
2127 headers: mockai_headers,
2128 };
2129
2130 match mockai_guard.process_request(&mockai_request).await {
2132 Ok(mockai_response) => {
2133 let is_empty = mockai_response.body.is_object()
2135 && mockai_response
2136 .body
2137 .as_object()
2138 .map(|obj| obj.is_empty())
2139 .unwrap_or(false);
2140
2141 if is_empty {
2142 tracing::debug!(
2143 "MockAI returned empty object for {} {}, falling back to OpenAPI response generation",
2144 route.method,
2145 route.path
2146 );
2147 } else {
2149 let spec_status = route.find_first_available_status_code();
2153 tracing::debug!(
2154 "MockAI generated response for {} {}, using spec status: {} (MockAI suggested: {})",
2155 route.method,
2156 route.path,
2157 spec_status,
2158 mockai_response.status_code
2159 );
2160 return (
2161 axum::http::StatusCode::from_u16(spec_status)
2162 .unwrap_or(axum::http::StatusCode::OK),
2163 Json(mockai_response.body),
2164 );
2165 }
2166 }
2167 Err(e) => {
2168 tracing::warn!(
2169 "MockAI processing failed for {} {}: {}, falling back to standard response",
2170 route.method,
2171 route.path,
2172 e
2173 );
2174 }
2176 }
2177 }
2178 } else {
2179 tracing::debug!(
2180 "Skipping MockAI for {} request {} - using OpenAPI response generation",
2181 method_upper,
2182 route.path
2183 );
2184 }
2185
2186 let status_override = headers
2188 .get("X-Mockforge-Response-Status")
2189 .and_then(|v| v.to_str().ok())
2190 .and_then(|s| s.parse::<u16>().ok());
2191
2192 let scenario = headers
2194 .get("X-Mockforge-Scenario")
2195 .and_then(|v| v.to_str().ok())
2196 .map(|s| s.to_string())
2197 .or_else(|| std::env::var("MOCKFORGE_HTTP_SCENARIO").ok());
2198
2199 let (status, response) = route
2201 .mock_response_with_status_and_scenario_and_override(
2202 scenario.as_deref(),
2203 status_override,
2204 );
2205 (
2206 axum::http::StatusCode::from_u16(status)
2207 .unwrap_or(axum::http::StatusCode::OK),
2208 Json(response),
2209 )
2210 }
2211 };
2212
2213 router = Self::route_for_method(router, axum_path, &route.method, handler);
2214 }
2215
2216 router.layer(DefaultBodyLimit::max(openapi_body_limit_bytes()))
2219 }
2220}
2221
2222async fn extract_multipart_from_bytes(
2227 body: &axum::body::Bytes,
2228 headers: &HeaderMap,
2229) -> Result<(HashMap<String, Value>, HashMap<String, String>)> {
2230 let boundary = headers
2232 .get(axum::http::header::CONTENT_TYPE)
2233 .and_then(|v| v.to_str().ok())
2234 .and_then(|ct| {
2235 ct.split(';').find_map(|part| {
2236 let part = part.trim();
2237 if part.starts_with("boundary=") {
2238 Some(part.strip_prefix("boundary=").unwrap_or("").trim_matches('"'))
2239 } else {
2240 None
2241 }
2242 })
2243 })
2244 .ok_or_else(|| Error::internal("Missing boundary in Content-Type header"))?;
2245
2246 let mut fields = HashMap::new();
2247 let mut files = HashMap::new();
2248
2249 let boundary_prefix = format!("--{}", boundary).into_bytes();
2252 let boundary_line = format!("\r\n--{}\r\n", boundary).into_bytes();
2253 let end_boundary = format!("\r\n--{}--\r\n", boundary).into_bytes();
2254
2255 let mut pos = 0;
2257 let mut parts = Vec::new();
2258
2259 if body.starts_with(&boundary_prefix) {
2261 if let Some(first_crlf) = body.iter().position(|&b| b == b'\r') {
2262 pos = first_crlf + 2; }
2264 }
2265
2266 while let Some(boundary_pos) = body[pos..]
2268 .windows(boundary_line.len())
2269 .position(|window| window == boundary_line.as_slice())
2270 {
2271 let actual_pos = pos + boundary_pos;
2272 if actual_pos > pos {
2273 parts.push((pos, actual_pos));
2274 }
2275 pos = actual_pos + boundary_line.len();
2276 }
2277
2278 if let Some(end_pos) = body[pos..]
2280 .windows(end_boundary.len())
2281 .position(|window| window == end_boundary.as_slice())
2282 {
2283 let actual_end = pos + end_pos;
2284 if actual_end > pos {
2285 parts.push((pos, actual_end));
2286 }
2287 } else if pos < body.len() {
2288 parts.push((pos, body.len()));
2290 }
2291
2292 for (start, end) in parts {
2294 let part_data = &body[start..end];
2295
2296 let separator = b"\r\n\r\n";
2298 if let Some(sep_pos) =
2299 part_data.windows(separator.len()).position(|window| window == separator)
2300 {
2301 let header_bytes = &part_data[..sep_pos];
2302 let body_start = sep_pos + separator.len();
2303 let body_data = &part_data[body_start..];
2304
2305 let header_str = String::from_utf8_lossy(header_bytes);
2307 let mut field_name = None;
2308 let mut filename = None;
2309
2310 for header_line in header_str.lines() {
2311 if header_line.starts_with("Content-Disposition:") {
2312 if let Some(name_start) = header_line.find("name=\"") {
2314 let name_start = name_start + 6;
2315 if let Some(name_end) = header_line[name_start..].find('"') {
2316 field_name =
2317 Some(header_line[name_start..name_start + name_end].to_string());
2318 }
2319 }
2320
2321 if let Some(file_start) = header_line.find("filename=\"") {
2323 let file_start = file_start + 10;
2324 if let Some(file_end) = header_line[file_start..].find('"') {
2325 filename =
2326 Some(header_line[file_start..file_start + file_end].to_string());
2327 }
2328 }
2329 }
2330 }
2331
2332 if let Some(name) = field_name {
2333 if let Some(file) = filename {
2334 let temp_dir = std::env::temp_dir().join("mockforge-uploads");
2336 std::fs::create_dir_all(&temp_dir)
2337 .map_err(|e| Error::io_with_context("temp directory", e.to_string()))?;
2338
2339 let file_path = temp_dir.join(format!("{}_{}", uuid::Uuid::new_v4(), file));
2340 std::fs::write(&file_path, body_data)
2341 .map_err(|e| Error::io_with_context("file", e.to_string()))?;
2342
2343 let file_path_str = file_path.to_string_lossy().to_string();
2344 files.insert(name.clone(), file_path_str.clone());
2345 fields.insert(name, Value::String(file_path_str));
2346 } else {
2347 let body_str = body_data
2350 .strip_suffix(b"\r\n")
2351 .or_else(|| body_data.strip_suffix(b"\n"))
2352 .unwrap_or(body_data);
2353
2354 if let Ok(field_value) = String::from_utf8(body_str.to_vec()) {
2355 fields.insert(name, Value::String(field_value.trim().to_string()));
2356 } else {
2357 use base64::{engine::general_purpose, Engine as _};
2359 fields.insert(
2360 name,
2361 Value::String(general_purpose::STANDARD.encode(body_str)),
2362 );
2363 }
2364 }
2365 }
2366 }
2367 }
2368
2369 Ok((fields, files))
2370}
2371
2372static LAST_ERRORS: Lazy<Mutex<VecDeque<Value>>> =
2373 Lazy::new(|| Mutex::new(VecDeque::with_capacity(20)));
2374
2375pub fn classify_validation_reason(reason: &str) -> String {
2383 let r = reason.to_ascii_lowercase();
2384 if r.contains("required")
2385 && (r.contains("param") || r.contains("query") || r.contains("header"))
2386 {
2387 return "parameters".into();
2388 }
2389 if r.contains("schema") || r.contains("body") || r.contains("json") {
2390 return "request-body".into();
2391 }
2392 if r.contains("content-type") || r.contains("content type") {
2393 return "content-types".into();
2394 }
2395 if r.contains("header") {
2396 return "headers".into();
2397 }
2398 if r.contains("cookie") {
2399 return "cookies".into();
2400 }
2401 if r.contains("method") {
2402 return "http-methods".into();
2403 }
2404 if r.contains("auth") || r.contains("security") {
2405 return "security".into();
2406 }
2407 if r.contains("enum") || r.contains("min") || r.contains("max") || r.contains("pattern") {
2408 return "constraints".into();
2409 }
2410 String::new()
2411}
2412
2413pub fn record_validation_error(v: &Value) {
2415 if let Ok(mut q) = LAST_ERRORS.lock() {
2416 if q.len() >= 20 {
2417 q.pop_front();
2418 }
2419 q.push_back(v.clone());
2420 }
2421 }
2423
2424pub fn get_last_validation_error() -> Option<Value> {
2426 LAST_ERRORS.lock().ok()?.back().cloned()
2427}
2428
2429pub fn get_validation_errors() -> Vec<Value> {
2431 LAST_ERRORS.lock().map(|q| q.iter().cloned().collect()).unwrap_or_default()
2432}
2433
2434fn coerce_value_for_schema(value: &Value, schema: &openapiv3::Schema) -> Value {
2439 match value {
2441 Value::String(s) => {
2442 if let openapiv3::SchemaKind::Type(openapiv3::Type::Array(array_type)) =
2444 &schema.schema_kind
2445 {
2446 if s.contains(',') {
2447 let parts: Vec<&str> = s.split(',').map(|s| s.trim()).collect();
2449 let mut array_values = Vec::new();
2450
2451 for part in parts {
2452 if let Some(items_schema) = &array_type.items {
2454 if let Some(items_schema_obj) = items_schema.as_item() {
2455 let part_value = Value::String(part.to_string());
2456 let coerced_part =
2457 coerce_value_for_schema(&part_value, items_schema_obj);
2458 array_values.push(coerced_part);
2459 } else {
2460 array_values.push(Value::String(part.to_string()));
2462 }
2463 } else {
2464 array_values.push(Value::String(part.to_string()));
2466 }
2467 }
2468 return Value::Array(array_values);
2469 }
2470 }
2471
2472 match &schema.schema_kind {
2474 openapiv3::SchemaKind::Type(openapiv3::Type::String(_)) => {
2475 value.clone()
2477 }
2478 openapiv3::SchemaKind::Type(openapiv3::Type::Number(_)) => {
2479 if let Ok(n) = s.parse::<f64>() {
2481 if let Some(num) = serde_json::Number::from_f64(n) {
2482 return Value::Number(num);
2483 }
2484 }
2485 value.clone()
2486 }
2487 openapiv3::SchemaKind::Type(openapiv3::Type::Integer(_)) => {
2488 if let Ok(n) = s.parse::<i64>() {
2490 if let Some(num) = serde_json::Number::from_f64(n as f64) {
2491 return Value::Number(num);
2492 }
2493 }
2494 value.clone()
2495 }
2496 openapiv3::SchemaKind::Type(openapiv3::Type::Boolean(_)) => {
2497 match s.to_lowercase().as_str() {
2499 "true" | "1" | "yes" | "on" => Value::Bool(true),
2500 "false" | "0" | "no" | "off" => Value::Bool(false),
2501 _ => value.clone(),
2502 }
2503 }
2504 _ => {
2505 value.clone()
2507 }
2508 }
2509 }
2510 _ => value.clone(),
2511 }
2512}
2513
2514fn coerce_by_style(value: &Value, schema: &openapiv3::Schema, style: Option<&str>) -> Value {
2516 match value {
2518 Value::String(s) => {
2519 if let openapiv3::SchemaKind::Type(openapiv3::Type::Array(array_type)) =
2521 &schema.schema_kind
2522 {
2523 let delimiter = match style {
2524 Some("spaceDelimited") => " ",
2525 Some("pipeDelimited") => "|",
2526 Some("form") | None => ",", _ => ",", };
2529
2530 if s.contains(delimiter) {
2531 let parts: Vec<&str> = s.split(delimiter).map(|s| s.trim()).collect();
2533 let mut array_values = Vec::new();
2534
2535 for part in parts {
2536 if let Some(items_schema) = &array_type.items {
2538 if let Some(items_schema_obj) = items_schema.as_item() {
2539 let part_value = Value::String(part.to_string());
2540 let coerced_part =
2541 coerce_by_style(&part_value, items_schema_obj, style);
2542 array_values.push(coerced_part);
2543 } else {
2544 array_values.push(Value::String(part.to_string()));
2546 }
2547 } else {
2548 array_values.push(Value::String(part.to_string()));
2550 }
2551 }
2552 return Value::Array(array_values);
2553 }
2554 }
2555
2556 if let Ok(n) = s.parse::<f64>() {
2558 if let Some(num) = serde_json::Number::from_f64(n) {
2559 return Value::Number(num);
2560 }
2561 }
2562 match s.to_lowercase().as_str() {
2564 "true" | "1" | "yes" | "on" => return Value::Bool(true),
2565 "false" | "0" | "no" | "off" => return Value::Bool(false),
2566 _ => {}
2567 }
2568 value.clone()
2570 }
2571 _ => value.clone(),
2572 }
2573}
2574
2575fn build_deep_object(name: &str, params: &Map<String, Value>) -> Option<Value> {
2577 let prefix = format!("{}[", name);
2578 let mut obj = Map::new();
2579 for (k, v) in params.iter() {
2580 if let Some(rest) = k.strip_prefix(&prefix) {
2581 if let Some(key) = rest.strip_suffix(']') {
2582 obj.insert(key.to_string(), v.clone());
2583 }
2584 }
2585 }
2586 if obj.is_empty() {
2587 None
2588 } else {
2589 Some(Value::Object(obj))
2590 }
2591}
2592
2593#[allow(clippy::too_many_arguments)]
2599fn generate_enhanced_422_response(
2600 validator: &OpenApiRouteRegistry,
2601 path_template: &str,
2602 method: &str,
2603 body: Option<&Value>,
2604 path_params: &Map<String, Value>,
2605 query_params: &Map<String, Value>,
2606 header_params: &Map<String, Value>,
2607 cookie_params: &Map<String, Value>,
2608) -> Value {
2609 let mut field_errors = Vec::new();
2610
2611 if let Some(route) = validator.get_route(path_template, method) {
2613 if let Some(schema) = &route.operation.request_body {
2615 if let Some(value) = body {
2616 if let Some(content) =
2617 schema.as_item().and_then(|rb| rb.content.get("application/json"))
2618 {
2619 if let Some(_schema_ref) = &content.schema {
2620 if serde_json::from_value::<Value>(value.clone()).is_err() {
2622 field_errors.push(json!({
2623 "path": "body",
2624 "message": "invalid JSON"
2625 }));
2626 }
2627 }
2628 }
2629 } else {
2630 field_errors.push(json!({
2631 "path": "body",
2632 "expected": "object",
2633 "found": "missing",
2634 "message": "Request body is required but not provided"
2635 }));
2636 }
2637 }
2638
2639 for param_ref in &route.operation.parameters {
2641 if let Some(param) = param_ref.as_item() {
2642 match param {
2643 openapiv3::Parameter::Path { parameter_data, .. } => {
2644 validate_parameter_detailed(
2645 parameter_data,
2646 path_params,
2647 "path",
2648 "path parameter",
2649 &mut field_errors,
2650 );
2651 }
2652 openapiv3::Parameter::Query { parameter_data, .. } => {
2653 let deep_value = if Some("form") == Some("deepObject") {
2654 build_deep_object(¶meter_data.name, query_params)
2655 } else {
2656 None
2657 };
2658 validate_parameter_detailed_with_deep(
2659 parameter_data,
2660 query_params,
2661 "query",
2662 "query parameter",
2663 deep_value,
2664 &mut field_errors,
2665 );
2666 }
2667 openapiv3::Parameter::Header { parameter_data, .. } => {
2668 validate_parameter_detailed(
2669 parameter_data,
2670 header_params,
2671 "header",
2672 "header parameter",
2673 &mut field_errors,
2674 );
2675 }
2676 openapiv3::Parameter::Cookie { parameter_data, .. } => {
2677 validate_parameter_detailed(
2678 parameter_data,
2679 cookie_params,
2680 "cookie",
2681 "cookie parameter",
2682 &mut field_errors,
2683 );
2684 }
2685 }
2686 }
2687 }
2688 }
2689
2690 json!({
2692 "error": "Schema validation failed",
2693 "details": field_errors,
2694 "method": method,
2695 "path": path_template,
2696 "timestamp": Utc::now().to_rfc3339(),
2697 "validation_type": "openapi_schema"
2698 })
2699}
2700
2701fn validate_parameter(
2703 parameter_data: &openapiv3::ParameterData,
2704 params_map: &Map<String, Value>,
2705 prefix: &str,
2706 aggregate: bool,
2707 errors: &mut Vec<String>,
2708 details: &mut Vec<Value>,
2709) {
2710 match params_map.get(¶meter_data.name) {
2711 Some(v) => {
2712 if let ParameterSchemaOrContent::Schema(s) = ¶meter_data.format {
2713 if let Some(schema) = s.as_item() {
2714 let coerced = coerce_value_for_schema(v, schema);
2715 if let Err(validation_error) =
2717 OpenApiSchema::new(schema.clone()).validate(&coerced)
2718 {
2719 let error_msg = validation_error.to_string();
2720 errors.push(format!(
2721 "{} parameter '{}' validation failed: {}",
2722 prefix, parameter_data.name, error_msg
2723 ));
2724 if aggregate {
2725 details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"schema_validation","message":error_msg}));
2726 }
2727 }
2728 }
2729 }
2730 }
2731 None => {
2732 if parameter_data.required {
2733 errors.push(format!(
2734 "missing required {} parameter '{}'",
2735 prefix, parameter_data.name
2736 ));
2737 details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"required","message":"Missing required parameter"}));
2738 }
2739 }
2740 }
2741}
2742
2743#[allow(clippy::too_many_arguments)]
2745fn validate_parameter_with_deep_object(
2746 parameter_data: &openapiv3::ParameterData,
2747 params_map: &Map<String, Value>,
2748 prefix: &str,
2749 deep_value: Option<Value>,
2750 style: Option<&str>,
2751 aggregate: bool,
2752 errors: &mut Vec<String>,
2753 details: &mut Vec<Value>,
2754) {
2755 match deep_value.as_ref().or_else(|| params_map.get(¶meter_data.name)) {
2756 Some(v) => {
2757 if let ParameterSchemaOrContent::Schema(s) = ¶meter_data.format {
2758 if let Some(schema) = s.as_item() {
2759 let coerced = coerce_by_style(v, schema, style); if let Err(validation_error) =
2762 OpenApiSchema::new(schema.clone()).validate(&coerced)
2763 {
2764 let error_msg = validation_error.to_string();
2765 errors.push(format!(
2766 "{} parameter '{}' validation failed: {}",
2767 prefix, parameter_data.name, error_msg
2768 ));
2769 if aggregate {
2770 details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"schema_validation","message":error_msg}));
2771 }
2772 }
2773 }
2774 }
2775 }
2776 None => {
2777 if parameter_data.required {
2778 errors.push(format!(
2779 "missing required {} parameter '{}'",
2780 prefix, parameter_data.name
2781 ));
2782 details.push(serde_json::json!({"path":format!("{}.{}", prefix, parameter_data.name),"code":"required","message":"Missing required parameter"}));
2783 }
2784 }
2785 }
2786}
2787
2788fn validate_parameter_detailed(
2790 parameter_data: &openapiv3::ParameterData,
2791 params_map: &Map<String, Value>,
2792 location: &str,
2793 value_type: &str,
2794 field_errors: &mut Vec<Value>,
2795) {
2796 match params_map.get(¶meter_data.name) {
2797 Some(value) => {
2798 if let ParameterSchemaOrContent::Schema(schema) = ¶meter_data.format {
2799 let details: Vec<Value> = Vec::new();
2801 let param_path = format!("{}.{}", location, parameter_data.name);
2802
2803 if let Some(schema_ref) = schema.as_item() {
2805 let coerced_value = coerce_value_for_schema(value, schema_ref);
2806 if let Err(validation_error) =
2808 OpenApiSchema::new(schema_ref.clone()).validate(&coerced_value)
2809 {
2810 field_errors.push(json!({
2811 "path": param_path,
2812 "expected": "valid according to schema",
2813 "found": coerced_value,
2814 "message": validation_error.to_string()
2815 }));
2816 }
2817 }
2818
2819 for detail in details {
2820 field_errors.push(json!({
2821 "path": detail["path"],
2822 "expected": detail["expected_type"],
2823 "found": detail["value"],
2824 "message": detail["message"]
2825 }));
2826 }
2827 }
2828 }
2829 None => {
2830 if parameter_data.required {
2831 field_errors.push(json!({
2832 "path": format!("{}.{}", location, parameter_data.name),
2833 "expected": "value",
2834 "found": "missing",
2835 "message": format!("Missing required {} '{}'", value_type, parameter_data.name)
2836 }));
2837 }
2838 }
2839 }
2840}
2841
2842fn validate_parameter_detailed_with_deep(
2844 parameter_data: &openapiv3::ParameterData,
2845 params_map: &Map<String, Value>,
2846 location: &str,
2847 value_type: &str,
2848 deep_value: Option<Value>,
2849 field_errors: &mut Vec<Value>,
2850) {
2851 match deep_value.as_ref().or_else(|| params_map.get(¶meter_data.name)) {
2852 Some(value) => {
2853 if let ParameterSchemaOrContent::Schema(schema) = ¶meter_data.format {
2854 let details: Vec<Value> = Vec::new();
2856 let param_path = format!("{}.{}", location, parameter_data.name);
2857
2858 if let Some(schema_ref) = schema.as_item() {
2860 let coerced_value = coerce_by_style(value, schema_ref, Some("form")); if let Err(validation_error) =
2863 OpenApiSchema::new(schema_ref.clone()).validate(&coerced_value)
2864 {
2865 field_errors.push(json!({
2866 "path": param_path,
2867 "expected": "valid according to schema",
2868 "found": coerced_value,
2869 "message": validation_error.to_string()
2870 }));
2871 }
2872 }
2873
2874 for detail in details {
2875 field_errors.push(json!({
2876 "path": detail["path"],
2877 "expected": detail["expected_type"],
2878 "found": detail["value"],
2879 "message": detail["message"]
2880 }));
2881 }
2882 }
2883 }
2884 None => {
2885 if parameter_data.required {
2886 field_errors.push(json!({
2887 "path": format!("{}.{}", location, parameter_data.name),
2888 "expected": "value",
2889 "found": "missing",
2890 "message": format!("Missing required {} '{}'", value_type, parameter_data.name)
2891 }));
2892 }
2893 }
2894 }
2895}
2896
2897pub async fn create_registry_from_file<P: AsRef<std::path::Path>>(
2899 path: P,
2900) -> Result<OpenApiRouteRegistry> {
2901 let spec = OpenApiSpec::from_file(path).await?;
2902 spec.validate()?;
2903 Ok(OpenApiRouteRegistry::new(spec))
2904}
2905
2906pub fn create_registry_from_json(json: Value) -> Result<OpenApiRouteRegistry> {
2908 let spec = OpenApiSpec::from_json(json)?;
2909 spec.validate()?;
2910 Ok(OpenApiRouteRegistry::new(spec))
2911}
2912
2913#[cfg(test)]
2914mod tests {
2915 use super::*;
2916 use serde_json::json;
2917 use tempfile::TempDir;
2918
2919 #[tokio::test]
2920 async fn test_registry_creation() {
2921 let spec_json = json!({
2922 "openapi": "3.0.0",
2923 "info": {
2924 "title": "Test API",
2925 "version": "1.0.0"
2926 },
2927 "paths": {
2928 "/users": {
2929 "get": {
2930 "summary": "Get users",
2931 "responses": {
2932 "200": {
2933 "description": "Success",
2934 "content": {
2935 "application/json": {
2936 "schema": {
2937 "type": "array",
2938 "items": {
2939 "type": "object",
2940 "properties": {
2941 "id": {"type": "integer"},
2942 "name": {"type": "string"}
2943 }
2944 }
2945 }
2946 }
2947 }
2948 }
2949 }
2950 },
2951 "post": {
2952 "summary": "Create user",
2953 "requestBody": {
2954 "content": {
2955 "application/json": {
2956 "schema": {
2957 "type": "object",
2958 "properties": {
2959 "name": {"type": "string"}
2960 },
2961 "required": ["name"]
2962 }
2963 }
2964 }
2965 },
2966 "responses": {
2967 "201": {
2968 "description": "Created",
2969 "content": {
2970 "application/json": {
2971 "schema": {
2972 "type": "object",
2973 "properties": {
2974 "id": {"type": "integer"},
2975 "name": {"type": "string"}
2976 }
2977 }
2978 }
2979 }
2980 }
2981 }
2982 }
2983 },
2984 "/users/{id}": {
2985 "get": {
2986 "summary": "Get user by ID",
2987 "parameters": [
2988 {
2989 "name": "id",
2990 "in": "path",
2991 "required": true,
2992 "schema": {"type": "integer"}
2993 }
2994 ],
2995 "responses": {
2996 "200": {
2997 "description": "Success",
2998 "content": {
2999 "application/json": {
3000 "schema": {
3001 "type": "object",
3002 "properties": {
3003 "id": {"type": "integer"},
3004 "name": {"type": "string"}
3005 }
3006 }
3007 }
3008 }
3009 }
3010 }
3011 }
3012 }
3013 }
3014 });
3015
3016 let registry = create_registry_from_json(spec_json).unwrap();
3017
3018 assert_eq!(registry.paths().len(), 2);
3020 assert!(registry.paths().contains(&"/users".to_string()));
3021 assert!(registry.paths().contains(&"/users/{id}".to_string()));
3022
3023 assert_eq!(registry.methods().len(), 2);
3024 assert!(registry.methods().contains(&"GET".to_string()));
3025 assert!(registry.methods().contains(&"POST".to_string()));
3026
3027 let get_users_route = registry.get_route("/users", "GET").unwrap();
3029 assert_eq!(get_users_route.method, "GET");
3030 assert_eq!(get_users_route.path, "/users");
3031
3032 let post_users_route = registry.get_route("/users", "POST").unwrap();
3033 assert_eq!(post_users_route.method, "POST");
3034 assert!(post_users_route.operation.request_body.is_some());
3035
3036 let user_by_id_route = registry.get_route("/users/{id}", "GET").unwrap();
3038 assert_eq!(user_by_id_route.axum_path(), "/users/{id}");
3039 }
3040
3041 #[tokio::test]
3047 async fn check_request_content_type_flags_mismatch() {
3048 let spec_json = json!({
3049 "openapi": "3.0.0",
3050 "info": { "title": "T", "version": "1" },
3051 "paths": {
3052 "/api/appliance/access/consolecli": {
3053 "put": {
3054 "requestBody": {
3055 "required": true,
3056 "content": {
3057 "application/json": {
3058 "schema": {
3059 "type": "object",
3060 "required": ["enabled"],
3061 "properties": {"enabled": {"type": "boolean"}}
3062 }
3063 }
3064 }
3065 },
3066 "responses": { "204": { "description": "ok" } }
3067 }
3068 }
3069 }
3070 });
3071 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3072 let registry = OpenApiRouteRegistry::new(spec);
3073
3074 let r = registry.check_request_content_type(
3076 "/api/appliance/access/consolecli",
3077 "PUT",
3078 Some("application/xml"),
3079 );
3080 assert!(r.is_err(), "should flag application/xml: {:?}", r);
3081 let msg = r.unwrap_err();
3082 assert!(msg.contains("application/xml"), "{msg}");
3083 assert!(msg.contains("application/json"), "{msg}");
3084
3085 let r = registry.check_request_content_type(
3087 "/api/appliance/access/consolecli",
3088 "PUT",
3089 Some("application/json"),
3090 );
3091 assert!(r.is_ok(), "should accept application/json: {:?}", r);
3092
3093 let r = registry.check_request_content_type(
3095 "/api/appliance/access/consolecli",
3096 "PUT",
3097 Some("application/json; charset=utf-8"),
3098 );
3099 assert!(r.is_ok(), "should strip charset: {:?}", r);
3100
3101 let r = registry.check_request_content_type(
3103 "/api/appliance/access/consolecli",
3104 "GET",
3105 Some("application/xml"),
3106 );
3107 assert!(r.is_ok(), "GET has no requestBody on this op: {:?}", r);
3108
3109 let r =
3111 registry.check_request_content_type("/api/appliance/access/consolecli", "PUT", None);
3112 assert!(r.is_ok(), "no Content-Type → don't double-report: {:?}", r);
3113 }
3114
3115 #[tokio::test]
3116 async fn test_validate_request_with_params_and_formats() {
3117 let spec_json = json!({
3118 "openapi": "3.0.0",
3119 "info": { "title": "Test API", "version": "1.0.0" },
3120 "paths": {
3121 "/users/{id}": {
3122 "post": {
3123 "parameters": [
3124 { "name": "id", "in": "path", "required": true, "schema": {"type": "string"} },
3125 { "name": "q", "in": "query", "required": false, "schema": {"type": "integer"} }
3126 ],
3127 "requestBody": {
3128 "content": {
3129 "application/json": {
3130 "schema": {
3131 "type": "object",
3132 "required": ["email", "website"],
3133 "properties": {
3134 "email": {"type": "string", "format": "email"},
3135 "website": {"type": "string", "format": "uri"}
3136 }
3137 }
3138 }
3139 }
3140 },
3141 "responses": {"200": {"description": "ok"}}
3142 }
3143 }
3144 }
3145 });
3146
3147 let registry = create_registry_from_json(spec_json).unwrap();
3148 let mut path_params = Map::new();
3149 path_params.insert("id".to_string(), json!("abc"));
3150 let mut query_params = Map::new();
3151 query_params.insert("q".to_string(), json!(123));
3152
3153 let body = json!({"email":"a@b.co","website":"https://example.com"});
3155 assert!(registry
3156 .validate_request_with("/users/{id}", "POST", &path_params, &query_params, Some(&body))
3157 .is_ok());
3158
3159 let bad_email = json!({"email":"not-an-email","website":"https://example.com"});
3161 assert!(registry
3162 .validate_request_with(
3163 "/users/{id}",
3164 "POST",
3165 &path_params,
3166 &query_params,
3167 Some(&bad_email)
3168 )
3169 .is_err());
3170
3171 let empty_path_params = Map::new();
3173 assert!(registry
3174 .validate_request_with(
3175 "/users/{id}",
3176 "POST",
3177 &empty_path_params,
3178 &query_params,
3179 Some(&body)
3180 )
3181 .is_err());
3182 }
3183
3184 #[tokio::test]
3185 async fn test_ref_resolution_for_params_and_body() {
3186 let spec_json = json!({
3187 "openapi": "3.0.0",
3188 "info": { "title": "Ref API", "version": "1.0.0" },
3189 "components": {
3190 "schemas": {
3191 "EmailWebsite": {
3192 "type": "object",
3193 "required": ["email", "website"],
3194 "properties": {
3195 "email": {"type": "string", "format": "email"},
3196 "website": {"type": "string", "format": "uri"}
3197 }
3198 }
3199 },
3200 "parameters": {
3201 "PathId": {"name": "id", "in": "path", "required": true, "schema": {"type": "string"}},
3202 "QueryQ": {"name": "q", "in": "query", "required": false, "schema": {"type": "integer"}}
3203 },
3204 "requestBodies": {
3205 "CreateUser": {
3206 "content": {
3207 "application/json": {
3208 "schema": {"$ref": "#/components/schemas/EmailWebsite"}
3209 }
3210 }
3211 }
3212 }
3213 },
3214 "paths": {
3215 "/users/{id}": {
3216 "post": {
3217 "parameters": [
3218 {"$ref": "#/components/parameters/PathId"},
3219 {"$ref": "#/components/parameters/QueryQ"}
3220 ],
3221 "requestBody": {"$ref": "#/components/requestBodies/CreateUser"},
3222 "responses": {"200": {"description": "ok"}}
3223 }
3224 }
3225 }
3226 });
3227
3228 let registry = create_registry_from_json(spec_json).unwrap();
3229 let mut path_params = Map::new();
3230 path_params.insert("id".to_string(), json!("abc"));
3231 let mut query_params = Map::new();
3232 query_params.insert("q".to_string(), json!(7));
3233
3234 let body = json!({"email":"user@example.com","website":"https://example.com"});
3235 assert!(registry
3236 .validate_request_with("/users/{id}", "POST", &path_params, &query_params, Some(&body))
3237 .is_ok());
3238
3239 let bad = json!({"email":"nope","website":"https://example.com"});
3240 assert!(registry
3241 .validate_request_with("/users/{id}", "POST", &path_params, &query_params, Some(&bad))
3242 .is_err());
3243 }
3244
3245 #[tokio::test]
3246 async fn test_header_cookie_and_query_coercion() {
3247 let spec_json = json!({
3248 "openapi": "3.0.0",
3249 "info": { "title": "Params API", "version": "1.0.0" },
3250 "paths": {
3251 "/items": {
3252 "get": {
3253 "parameters": [
3254 {"name": "X-Flag", "in": "header", "required": true, "schema": {"type": "boolean"}},
3255 {"name": "session", "in": "cookie", "required": true, "schema": {"type": "string"}},
3256 {"name": "ids", "in": "query", "required": false, "schema": {"type": "array", "items": {"type": "integer"}}}
3257 ],
3258 "responses": {"200": {"description": "ok"}}
3259 }
3260 }
3261 }
3262 });
3263
3264 let registry = create_registry_from_json(spec_json).unwrap();
3265
3266 let path_params = Map::new();
3267 let mut query_params = Map::new();
3268 query_params.insert("ids".to_string(), json!("1,2,3"));
3270 let mut header_params = Map::new();
3271 header_params.insert("X-Flag".to_string(), json!("true"));
3272 let mut cookie_params = Map::new();
3273 cookie_params.insert("session".to_string(), json!("abc123"));
3274
3275 assert!(registry
3276 .validate_request_with_all(
3277 "/items",
3278 "GET",
3279 &path_params,
3280 &query_params,
3281 &header_params,
3282 &cookie_params,
3283 None
3284 )
3285 .is_ok());
3286
3287 let empty_cookie = Map::new();
3289 assert!(registry
3290 .validate_request_with_all(
3291 "/items",
3292 "GET",
3293 &path_params,
3294 &query_params,
3295 &header_params,
3296 &empty_cookie,
3297 None
3298 )
3299 .is_err());
3300
3301 let mut bad_header = Map::new();
3303 bad_header.insert("X-Flag".to_string(), json!("notabool"));
3304 assert!(registry
3305 .validate_request_with_all(
3306 "/items",
3307 "GET",
3308 &path_params,
3309 &query_params,
3310 &bad_header,
3311 &cookie_params,
3312 None
3313 )
3314 .is_err());
3315 }
3316
3317 #[tokio::test]
3318 async fn test_query_styles_space_pipe_deepobject() {
3319 let spec_json = json!({
3320 "openapi": "3.0.0",
3321 "info": { "title": "Query Styles API", "version": "1.0.0" },
3322 "paths": {"/search": {"get": {
3323 "parameters": [
3324 {"name":"tags","in":"query","style":"spaceDelimited","schema":{"type":"array","items":{"type":"string"}}},
3325 {"name":"ids","in":"query","style":"pipeDelimited","schema":{"type":"array","items":{"type":"integer"}}},
3326 {"name":"filter","in":"query","style":"deepObject","schema":{"type":"object","properties":{"color":{"type":"string"}},"required":["color"]}}
3327 ],
3328 "responses": {"200": {"description":"ok"}}
3329 }} }
3330 });
3331
3332 let registry = create_registry_from_json(spec_json).unwrap();
3333
3334 let path_params = Map::new();
3335 let mut query = Map::new();
3336 query.insert("tags".into(), json!("alpha beta gamma"));
3337 query.insert("ids".into(), json!("1|2|3"));
3338 query.insert("filter[color]".into(), json!("red"));
3339
3340 assert!(registry
3341 .validate_request_with("/search", "GET", &path_params, &query, None)
3342 .is_ok());
3343 }
3344
3345 #[tokio::test]
3346 async fn test_oneof_anyof_allof_validation() {
3347 let spec_json = json!({
3348 "openapi": "3.0.0",
3349 "info": { "title": "Composite API", "version": "1.0.0" },
3350 "paths": {
3351 "/composite": {
3352 "post": {
3353 "requestBody": {
3354 "content": {
3355 "application/json": {
3356 "schema": {
3357 "allOf": [
3358 {"type": "object", "required": ["base"], "properties": {"base": {"type": "string"}}}
3359 ],
3360 "oneOf": [
3361 {"type": "object", "properties": {"a": {"type": "integer"}}, "required": ["a"], "not": {"required": ["b"]}},
3362 {"type": "object", "properties": {"b": {"type": "integer"}}, "required": ["b"], "not": {"required": ["a"]}}
3363 ],
3364 "anyOf": [
3365 {"type": "object", "properties": {"flag": {"type": "boolean"}}, "required": ["flag"]},
3366 {"type": "object", "properties": {"extra": {"type": "string"}}, "required": ["extra"]}
3367 ]
3368 }
3369 }
3370 }
3371 },
3372 "responses": {"200": {"description": "ok"}}
3373 }
3374 }
3375 }
3376 });
3377
3378 let registry = create_registry_from_json(spec_json).unwrap();
3379 let ok = json!({"base": "x", "a": 1, "flag": true});
3381 assert!(registry
3382 .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&ok))
3383 .is_ok());
3384
3385 let bad_oneof = json!({"base": "x", "a": 1, "b": 2, "flag": false});
3387 assert!(registry
3388 .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&bad_oneof))
3389 .is_err());
3390
3391 let bad_anyof = json!({"base": "x", "a": 1});
3393 assert!(registry
3394 .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&bad_anyof))
3395 .is_err());
3396
3397 let bad_allof = json!({"a": 1, "flag": true});
3399 assert!(registry
3400 .validate_request_with("/composite", "POST", &Map::new(), &Map::new(), Some(&bad_allof))
3401 .is_err());
3402 }
3403
3404 #[tokio::test]
3413 async fn dotted_schema_ref_resolves_in_route_validator() {
3414 let spec_json = json!({
3415 "openapi": "3.0.0",
3416 "info": { "title": "Dotted", "version": "1.0.0" },
3417 "paths": {
3418 "/x": {
3419 "post": {
3420 "requestBody": {
3421 "required": true,
3422 "content": {
3423 "application/json": {
3424 "schema": {
3425 "$ref": "#/components/schemas/Esx.Settings.Inventory.EntitySpec"
3426 }
3427 }
3428 }
3429 },
3430 "responses": {"200": {"description": "ok"}}
3431 }
3432 }
3433 },
3434 "components": {
3435 "schemas": {
3436 "Esx.Settings.Inventory.EntitySpec": {
3437 "type": "object",
3438 "required": ["type"],
3439 "properties": {"type": {"type": "string"}}
3440 }
3441 }
3442 }
3443 });
3444 let registry = create_registry_from_json(spec_json).unwrap();
3445 let good = json!({"type": "HOST"});
3448 let res =
3449 registry.validate_request_with("/x", "POST", &Map::new(), &Map::new(), Some(&good));
3450 assert!(res.is_ok(), "valid body should pass; got {res:?}");
3451 let bad = json!({"unrelated": 1});
3453 let err = registry
3454 .validate_request_with("/x", "POST", &Map::new(), &Map::new(), Some(&bad))
3455 .unwrap_err();
3456 let msg = format!("{err}");
3457 assert!(
3458 !msg.contains("Pointer") || !msg.contains("does not exist"),
3459 "should not be a pointer-resolution failure; got: {msg}"
3460 );
3461 }
3462
3463 #[tokio::test]
3464 async fn test_overrides_warn_mode_allows_invalid() {
3465 let spec_json = json!({
3467 "openapi": "3.0.0",
3468 "info": { "title": "Overrides API", "version": "1.0.0" },
3469 "paths": {"/things": {"post": {
3470 "parameters": [{"name":"q","in":"query","required":true,"schema":{"type":"integer"}}],
3471 "responses": {"200": {"description":"ok"}}
3472 }}}
3473 });
3474
3475 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3476 let mut overrides = HashMap::new();
3477 overrides.insert("POST /things".to_string(), ValidationMode::Warn);
3478 let registry = OpenApiRouteRegistry::new_with_options(
3479 spec,
3480 ValidationOptions {
3481 request_mode: ValidationMode::Enforce,
3482 aggregate_errors: true,
3483 validate_responses: false,
3484 overrides,
3485 admin_skip_prefixes: vec![],
3486 response_template_expand: false,
3487 validation_status: None,
3488 },
3489 );
3490
3491 let ok = registry.validate_request_with("/things", "POST", &Map::new(), &Map::new(), None);
3493 assert!(ok.is_ok());
3494 }
3495
3496 #[tokio::test]
3497 async fn test_admin_skip_prefix_short_circuit() {
3498 let spec_json = json!({
3499 "openapi": "3.0.0",
3500 "info": { "title": "Skip API", "version": "1.0.0" },
3501 "paths": {}
3502 });
3503 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3504 let registry = OpenApiRouteRegistry::new_with_options(
3505 spec,
3506 ValidationOptions {
3507 request_mode: ValidationMode::Enforce,
3508 aggregate_errors: true,
3509 validate_responses: false,
3510 overrides: HashMap::new(),
3511 admin_skip_prefixes: vec!["/admin".into()],
3512 response_template_expand: false,
3513 validation_status: None,
3514 },
3515 );
3516
3517 let res = registry.validate_request_with_all(
3519 "/admin/__mockforge/health",
3520 "GET",
3521 &Map::new(),
3522 &Map::new(),
3523 &Map::new(),
3524 &Map::new(),
3525 None,
3526 );
3527 assert!(res.is_ok());
3528 }
3529
3530 #[test]
3531 fn test_path_conversion() {
3532 assert_eq!(OpenApiRouteRegistry::convert_path_to_axum("/users"), "/users");
3533 assert_eq!(OpenApiRouteRegistry::convert_path_to_axum("/users/{id}"), "/users/{id}");
3534 assert_eq!(
3535 OpenApiRouteRegistry::convert_path_to_axum("/users/{id}/posts/{postId}"),
3536 "/users/{id}/posts/{postId}"
3537 );
3538 }
3539
3540 #[test]
3541 fn test_validation_options_default() {
3542 let options = ValidationOptions::default();
3543 assert!(matches!(options.request_mode, ValidationMode::Enforce));
3544 assert!(options.aggregate_errors);
3545 assert!(!options.validate_responses);
3546 assert!(options.overrides.is_empty());
3547 assert!(options.admin_skip_prefixes.is_empty());
3548 assert!(!options.response_template_expand);
3549 assert!(options.validation_status.is_none());
3550 }
3551
3552 #[test]
3553 fn test_validation_mode_variants() {
3554 let disabled = ValidationMode::Disabled;
3556 let warn = ValidationMode::Warn;
3557 let enforce = ValidationMode::Enforce;
3558 let default = ValidationMode::default();
3559
3560 assert!(matches!(default, ValidationMode::Warn));
3562
3563 assert!(!matches!(disabled, ValidationMode::Warn));
3565 assert!(!matches!(warn, ValidationMode::Enforce));
3566 assert!(!matches!(enforce, ValidationMode::Disabled));
3567 }
3568
3569 #[test]
3570 fn test_registry_spec_accessor() {
3571 let spec_json = json!({
3572 "openapi": "3.0.0",
3573 "info": {
3574 "title": "Test API",
3575 "version": "1.0.0"
3576 },
3577 "paths": {}
3578 });
3579 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3580 let registry = OpenApiRouteRegistry::new(spec.clone());
3581
3582 let accessed_spec = registry.spec();
3584 assert_eq!(accessed_spec.title(), "Test API");
3585 }
3586
3587 #[test]
3588 fn test_clone_for_validation() {
3589 let spec_json = json!({
3590 "openapi": "3.0.0",
3591 "info": {
3592 "title": "Test API",
3593 "version": "1.0.0"
3594 },
3595 "paths": {
3596 "/users": {
3597 "get": {
3598 "responses": {
3599 "200": {
3600 "description": "Success"
3601 }
3602 }
3603 }
3604 }
3605 }
3606 });
3607 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3608 let registry = OpenApiRouteRegistry::new(spec);
3609
3610 let cloned = registry.clone_for_validation();
3612 assert_eq!(cloned.routes().len(), registry.routes().len());
3613 assert_eq!(cloned.spec().title(), registry.spec().title());
3614 }
3615
3616 #[test]
3617 fn test_with_custom_fixture_loader() {
3618 let temp_dir = TempDir::new().unwrap();
3619 let spec_json = json!({
3620 "openapi": "3.0.0",
3621 "info": {
3622 "title": "Test API",
3623 "version": "1.0.0"
3624 },
3625 "paths": {}
3626 });
3627 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3628 let registry = OpenApiRouteRegistry::new(spec);
3629 let original_routes_len = registry.routes().len();
3630
3631 let custom_loader = Arc::new(crate::custom_fixture::CustomFixtureLoader::new(
3633 temp_dir.path().to_path_buf(),
3634 true,
3635 ));
3636 let registry_with_loader = registry.with_custom_fixture_loader(custom_loader);
3637
3638 assert_eq!(registry_with_loader.routes().len(), original_routes_len);
3640 }
3641
3642 #[test]
3643 fn test_get_route() {
3644 let spec_json = json!({
3645 "openapi": "3.0.0",
3646 "info": {
3647 "title": "Test API",
3648 "version": "1.0.0"
3649 },
3650 "paths": {
3651 "/users": {
3652 "get": {
3653 "operationId": "getUsers",
3654 "responses": {
3655 "200": {
3656 "description": "Success"
3657 }
3658 }
3659 },
3660 "post": {
3661 "operationId": "createUser",
3662 "responses": {
3663 "201": {
3664 "description": "Created"
3665 }
3666 }
3667 }
3668 }
3669 }
3670 });
3671 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3672 let registry = OpenApiRouteRegistry::new(spec);
3673
3674 let route = registry.get_route("/users", "GET");
3676 assert!(route.is_some());
3677 assert_eq!(route.unwrap().method, "GET");
3678 assert_eq!(route.unwrap().path, "/users");
3679
3680 let route = registry.get_route("/nonexistent", "GET");
3682 assert!(route.is_none());
3683
3684 let route = registry.get_route("/users", "POST");
3686 assert!(route.is_some());
3687 assert_eq!(route.unwrap().method, "POST");
3688 }
3689
3690 #[test]
3691 fn test_get_routes_for_path() {
3692 let spec_json = json!({
3693 "openapi": "3.0.0",
3694 "info": {
3695 "title": "Test API",
3696 "version": "1.0.0"
3697 },
3698 "paths": {
3699 "/users": {
3700 "get": {
3701 "responses": {
3702 "200": {
3703 "description": "Success"
3704 }
3705 }
3706 },
3707 "post": {
3708 "responses": {
3709 "201": {
3710 "description": "Created"
3711 }
3712 }
3713 },
3714 "put": {
3715 "responses": {
3716 "200": {
3717 "description": "Success"
3718 }
3719 }
3720 }
3721 },
3722 "/posts": {
3723 "get": {
3724 "responses": {
3725 "200": {
3726 "description": "Success"
3727 }
3728 }
3729 }
3730 }
3731 }
3732 });
3733 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3734 let registry = OpenApiRouteRegistry::new(spec);
3735
3736 let routes = registry.get_routes_for_path("/users");
3738 assert_eq!(routes.len(), 3);
3739 let methods: Vec<&str> = routes.iter().map(|r| r.method.as_str()).collect();
3740 assert!(methods.contains(&"GET"));
3741 assert!(methods.contains(&"POST"));
3742 assert!(methods.contains(&"PUT"));
3743
3744 let routes = registry.get_routes_for_path("/posts");
3746 assert_eq!(routes.len(), 1);
3747 assert_eq!(routes[0].method, "GET");
3748
3749 let routes = registry.get_routes_for_path("/nonexistent");
3751 assert!(routes.is_empty());
3752 }
3753
3754 #[test]
3755 fn test_new_vs_new_with_options() {
3756 let spec_json = json!({
3757 "openapi": "3.0.0",
3758 "info": {
3759 "title": "Test API",
3760 "version": "1.0.0"
3761 },
3762 "paths": {}
3763 });
3764 let spec1 = OpenApiSpec::from_json(spec_json.clone()).unwrap();
3765 let spec2 = OpenApiSpec::from_json(spec_json).unwrap();
3766
3767 let registry1 = OpenApiRouteRegistry::new(spec1);
3769 assert_eq!(registry1.spec().title(), "Test API");
3770
3771 let options = ValidationOptions {
3773 request_mode: ValidationMode::Disabled,
3774 aggregate_errors: false,
3775 validate_responses: true,
3776 overrides: HashMap::new(),
3777 admin_skip_prefixes: vec!["/admin".to_string()],
3778 response_template_expand: true,
3779 validation_status: Some(422),
3780 };
3781 let registry2 = OpenApiRouteRegistry::new_with_options(spec2, options);
3782 assert_eq!(registry2.spec().title(), "Test API");
3783 }
3784
3785 #[test]
3786 fn test_new_with_env_vs_new() {
3787 let spec_json = json!({
3788 "openapi": "3.0.0",
3789 "info": {
3790 "title": "Test API",
3791 "version": "1.0.0"
3792 },
3793 "paths": {}
3794 });
3795 let spec1 = OpenApiSpec::from_json(spec_json.clone()).unwrap();
3796 let spec2 = OpenApiSpec::from_json(spec_json).unwrap();
3797
3798 let registry1 = OpenApiRouteRegistry::new(spec1);
3800
3801 let registry2 = OpenApiRouteRegistry::new_with_env(spec2);
3803
3804 assert_eq!(registry1.spec().title(), "Test API");
3806 assert_eq!(registry2.spec().title(), "Test API");
3807 }
3808
3809 #[test]
3810 fn test_validation_options_custom() {
3811 let options = ValidationOptions {
3812 request_mode: ValidationMode::Warn,
3813 aggregate_errors: false,
3814 validate_responses: true,
3815 overrides: {
3816 let mut map = HashMap::new();
3817 map.insert("getUsers".to_string(), ValidationMode::Disabled);
3818 map
3819 },
3820 admin_skip_prefixes: vec!["/admin".to_string(), "/internal".to_string()],
3821 response_template_expand: true,
3822 validation_status: Some(422),
3823 };
3824
3825 assert!(matches!(options.request_mode, ValidationMode::Warn));
3826 assert!(!options.aggregate_errors);
3827 assert!(options.validate_responses);
3828 assert_eq!(options.overrides.len(), 1);
3829 assert_eq!(options.admin_skip_prefixes.len(), 2);
3830 assert!(options.response_template_expand);
3831 assert_eq!(options.validation_status, Some(422));
3832 }
3833
3834 #[test]
3835 fn test_validation_mode_default_standalone() {
3836 let mode = ValidationMode::default();
3837 assert!(matches!(mode, ValidationMode::Warn));
3838 }
3839
3840 #[test]
3841 fn test_validation_mode_clone() {
3842 let mode1 = ValidationMode::Enforce;
3843 let mode2 = mode1.clone();
3844 assert!(matches!(mode1, ValidationMode::Enforce));
3845 assert!(matches!(mode2, ValidationMode::Enforce));
3846 }
3847
3848 #[test]
3849 fn test_validation_mode_debug() {
3850 let mode = ValidationMode::Disabled;
3851 let debug_str = format!("{:?}", mode);
3852 assert!(debug_str.contains("Disabled") || debug_str.contains("ValidationMode"));
3853 }
3854
3855 #[test]
3856 fn test_validation_options_clone() {
3857 let options1 = ValidationOptions {
3858 request_mode: ValidationMode::Warn,
3859 aggregate_errors: true,
3860 validate_responses: false,
3861 overrides: HashMap::new(),
3862 admin_skip_prefixes: vec![],
3863 response_template_expand: false,
3864 validation_status: None,
3865 };
3866 let options2 = options1.clone();
3867 assert!(matches!(options2.request_mode, ValidationMode::Warn));
3868 assert_eq!(options1.aggregate_errors, options2.aggregate_errors);
3869 }
3870
3871 #[test]
3872 fn test_validation_options_debug() {
3873 let options = ValidationOptions::default();
3874 let debug_str = format!("{:?}", options);
3875 assert!(debug_str.contains("ValidationOptions"));
3876 }
3877
3878 #[test]
3879 fn test_validation_options_with_all_fields() {
3880 let mut overrides = HashMap::new();
3881 overrides.insert("op1".to_string(), ValidationMode::Disabled);
3882 overrides.insert("op2".to_string(), ValidationMode::Warn);
3883
3884 let options = ValidationOptions {
3885 request_mode: ValidationMode::Enforce,
3886 aggregate_errors: false,
3887 validate_responses: true,
3888 overrides: overrides.clone(),
3889 admin_skip_prefixes: vec!["/admin".to_string(), "/internal".to_string()],
3890 response_template_expand: true,
3891 validation_status: Some(422),
3892 };
3893
3894 assert!(matches!(options.request_mode, ValidationMode::Enforce));
3895 assert!(!options.aggregate_errors);
3896 assert!(options.validate_responses);
3897 assert_eq!(options.overrides.len(), 2);
3898 assert_eq!(options.admin_skip_prefixes.len(), 2);
3899 assert!(options.response_template_expand);
3900 assert_eq!(options.validation_status, Some(422));
3901 }
3902
3903 #[test]
3904 fn test_openapi_route_registry_clone() {
3905 let spec_json = json!({
3906 "openapi": "3.0.0",
3907 "info": { "title": "Test API", "version": "1.0.0" },
3908 "paths": {}
3909 });
3910 let spec = OpenApiSpec::from_json(spec_json).unwrap();
3911 let registry1 = OpenApiRouteRegistry::new(spec);
3912 let registry2 = registry1.clone();
3913 assert_eq!(registry1.spec().title(), registry2.spec().title());
3914 }
3915
3916 #[test]
3917 fn test_validation_mode_serialization() {
3918 let mode = ValidationMode::Enforce;
3919 let json = serde_json::to_string(&mode).unwrap();
3920 assert!(json.contains("Enforce") || json.contains("enforce"));
3921 }
3922
3923 #[test]
3924 fn test_validation_mode_deserialization() {
3925 let json = r#""Disabled""#;
3926 let mode: ValidationMode = serde_json::from_str(json).unwrap();
3927 assert!(matches!(mode, ValidationMode::Disabled));
3928 }
3929
3930 #[test]
3931 fn test_validation_options_default_values() {
3932 let options = ValidationOptions::default();
3933 assert!(matches!(options.request_mode, ValidationMode::Enforce));
3934 assert!(options.aggregate_errors);
3935 assert!(!options.validate_responses);
3936 assert!(options.overrides.is_empty());
3937 assert!(options.admin_skip_prefixes.is_empty());
3938 assert!(!options.response_template_expand);
3939 assert_eq!(options.validation_status, None);
3940 }
3941
3942 #[test]
3943 fn test_validation_mode_all_variants() {
3944 let disabled = ValidationMode::Disabled;
3945 let warn = ValidationMode::Warn;
3946 let enforce = ValidationMode::Enforce;
3947
3948 assert!(matches!(disabled, ValidationMode::Disabled));
3949 assert!(matches!(warn, ValidationMode::Warn));
3950 assert!(matches!(enforce, ValidationMode::Enforce));
3951 }
3952
3953 #[test]
3954 fn test_validation_options_with_overrides() {
3955 let mut overrides = HashMap::new();
3956 overrides.insert("operation1".to_string(), ValidationMode::Disabled);
3957 overrides.insert("operation2".to_string(), ValidationMode::Warn);
3958
3959 let options = ValidationOptions {
3960 request_mode: ValidationMode::Enforce,
3961 aggregate_errors: true,
3962 validate_responses: false,
3963 overrides,
3964 admin_skip_prefixes: vec![],
3965 response_template_expand: false,
3966 validation_status: None,
3967 };
3968
3969 assert_eq!(options.overrides.len(), 2);
3970 assert!(matches!(options.overrides.get("operation1"), Some(ValidationMode::Disabled)));
3971 assert!(matches!(options.overrides.get("operation2"), Some(ValidationMode::Warn)));
3972 }
3973
3974 #[test]
3975 fn test_validation_options_with_admin_skip_prefixes() {
3976 let options = ValidationOptions {
3977 request_mode: ValidationMode::Enforce,
3978 aggregate_errors: true,
3979 validate_responses: false,
3980 overrides: HashMap::new(),
3981 admin_skip_prefixes: vec![
3982 "/admin".to_string(),
3983 "/internal".to_string(),
3984 "/debug".to_string(),
3985 ],
3986 response_template_expand: false,
3987 validation_status: None,
3988 };
3989
3990 assert_eq!(options.admin_skip_prefixes.len(), 3);
3991 assert!(options.admin_skip_prefixes.contains(&"/admin".to_string()));
3992 assert!(options.admin_skip_prefixes.contains(&"/internal".to_string()));
3993 assert!(options.admin_skip_prefixes.contains(&"/debug".to_string()));
3994 }
3995
3996 #[test]
3997 fn test_validation_options_with_validation_status() {
3998 let options1 = ValidationOptions {
3999 request_mode: ValidationMode::Enforce,
4000 aggregate_errors: true,
4001 validate_responses: false,
4002 overrides: HashMap::new(),
4003 admin_skip_prefixes: vec![],
4004 response_template_expand: false,
4005 validation_status: Some(400),
4006 };
4007
4008 let options2 = ValidationOptions {
4009 request_mode: ValidationMode::Enforce,
4010 aggregate_errors: true,
4011 validate_responses: false,
4012 overrides: HashMap::new(),
4013 admin_skip_prefixes: vec![],
4014 response_template_expand: false,
4015 validation_status: Some(422),
4016 };
4017
4018 assert_eq!(options1.validation_status, Some(400));
4019 assert_eq!(options2.validation_status, Some(422));
4020 }
4021
4022 #[test]
4023 fn test_validate_request_with_disabled_mode() {
4024 let spec_json = json!({
4026 "openapi": "3.0.0",
4027 "info": {"title": "Test API", "version": "1.0.0"},
4028 "paths": {
4029 "/users": {
4030 "get": {
4031 "responses": {"200": {"description": "OK"}}
4032 }
4033 }
4034 }
4035 });
4036 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4037 let options = ValidationOptions {
4038 request_mode: ValidationMode::Disabled,
4039 ..Default::default()
4040 };
4041 let registry = OpenApiRouteRegistry::new_with_options(spec, options);
4042
4043 let result = registry.validate_request_with_all(
4045 "/users",
4046 "GET",
4047 &Map::new(),
4048 &Map::new(),
4049 &Map::new(),
4050 &Map::new(),
4051 None,
4052 );
4053 assert!(result.is_ok());
4054 }
4055
4056 #[test]
4057 fn test_validate_request_with_warn_mode() {
4058 let spec_json = json!({
4060 "openapi": "3.0.0",
4061 "info": {"title": "Test API", "version": "1.0.0"},
4062 "paths": {
4063 "/users": {
4064 "post": {
4065 "requestBody": {
4066 "required": true,
4067 "content": {
4068 "application/json": {
4069 "schema": {
4070 "type": "object",
4071 "required": ["name"],
4072 "properties": {
4073 "name": {"type": "string"}
4074 }
4075 }
4076 }
4077 }
4078 },
4079 "responses": {"200": {"description": "OK"}}
4080 }
4081 }
4082 }
4083 });
4084 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4085 let options = ValidationOptions {
4086 request_mode: ValidationMode::Warn,
4087 ..Default::default()
4088 };
4089 let registry = OpenApiRouteRegistry::new_with_options(spec, options);
4090
4091 let result = registry.validate_request_with_all(
4093 "/users",
4094 "POST",
4095 &Map::new(),
4096 &Map::new(),
4097 &Map::new(),
4098 &Map::new(),
4099 None, );
4101 assert!(result.is_ok()); }
4103
4104 #[test]
4105 fn test_validate_request_body_validation_error() {
4106 let spec_json = json!({
4108 "openapi": "3.0.0",
4109 "info": {"title": "Test API", "version": "1.0.0"},
4110 "paths": {
4111 "/users": {
4112 "post": {
4113 "requestBody": {
4114 "required": true,
4115 "content": {
4116 "application/json": {
4117 "schema": {
4118 "type": "object",
4119 "required": ["name"],
4120 "properties": {
4121 "name": {"type": "string"}
4122 }
4123 }
4124 }
4125 }
4126 },
4127 "responses": {"200": {"description": "OK"}}
4128 }
4129 }
4130 }
4131 });
4132 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4133 let registry = OpenApiRouteRegistry::new(spec);
4134
4135 let result = registry.validate_request_with_all(
4137 "/users",
4138 "POST",
4139 &Map::new(),
4140 &Map::new(),
4141 &Map::new(),
4142 &Map::new(),
4143 None, );
4145 assert!(result.is_err());
4146 }
4147
4148 #[test]
4149 fn test_validate_request_body_schema_validation_error() {
4150 let spec_json = json!({
4152 "openapi": "3.0.0",
4153 "info": {"title": "Test API", "version": "1.0.0"},
4154 "paths": {
4155 "/users": {
4156 "post": {
4157 "requestBody": {
4158 "required": true,
4159 "content": {
4160 "application/json": {
4161 "schema": {
4162 "type": "object",
4163 "required": ["name"],
4164 "properties": {
4165 "name": {"type": "string"}
4166 }
4167 }
4168 }
4169 }
4170 },
4171 "responses": {"200": {"description": "OK"}}
4172 }
4173 }
4174 }
4175 });
4176 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4177 let registry = OpenApiRouteRegistry::new(spec);
4178
4179 let invalid_body = json!({}); let result = registry.validate_request_with_all(
4182 "/users",
4183 "POST",
4184 &Map::new(),
4185 &Map::new(),
4186 &Map::new(),
4187 &Map::new(),
4188 Some(&invalid_body),
4189 );
4190 assert!(result.is_err());
4191 }
4192
4193 #[test]
4194 fn test_validate_request_body_referenced_schema_error() {
4195 let spec_json = json!({
4197 "openapi": "3.0.0",
4198 "info": {"title": "Test API", "version": "1.0.0"},
4199 "paths": {
4200 "/users": {
4201 "post": {
4202 "requestBody": {
4203 "required": true,
4204 "content": {
4205 "application/json": {
4206 "schema": {
4207 "$ref": "#/components/schemas/NonExistentSchema"
4208 }
4209 }
4210 }
4211 },
4212 "responses": {"200": {"description": "OK"}}
4213 }
4214 }
4215 },
4216 "components": {}
4217 });
4218 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4219 let registry = OpenApiRouteRegistry::new(spec);
4220
4221 let body = json!({"name": "test"});
4223 let result = registry.validate_request_with_all(
4224 "/users",
4225 "POST",
4226 &Map::new(),
4227 &Map::new(),
4228 &Map::new(),
4229 &Map::new(),
4230 Some(&body),
4231 );
4232 assert!(result.is_err());
4233 }
4234
4235 #[test]
4236 fn test_validate_request_body_referenced_request_body_error() {
4237 let spec_json = json!({
4239 "openapi": "3.0.0",
4240 "info": {"title": "Test API", "version": "1.0.0"},
4241 "paths": {
4242 "/users": {
4243 "post": {
4244 "requestBody": {
4245 "$ref": "#/components/requestBodies/NonExistentRequestBody"
4246 },
4247 "responses": {"200": {"description": "OK"}}
4248 }
4249 }
4250 },
4251 "components": {}
4252 });
4253 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4254 let registry = OpenApiRouteRegistry::new(spec);
4255
4256 let body = json!({"name": "test"});
4258 let result = registry.validate_request_with_all(
4259 "/users",
4260 "POST",
4261 &Map::new(),
4262 &Map::new(),
4263 &Map::new(),
4264 &Map::new(),
4265 Some(&body),
4266 );
4267 assert!(result.is_err());
4268 }
4269
4270 #[test]
4271 fn test_validate_request_body_provided_when_not_expected() {
4272 let spec_json = json!({
4274 "openapi": "3.0.0",
4275 "info": {"title": "Test API", "version": "1.0.0"},
4276 "paths": {
4277 "/users": {
4278 "get": {
4279 "responses": {"200": {"description": "OK"}}
4280 }
4281 }
4282 }
4283 });
4284 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4285 let registry = OpenApiRouteRegistry::new(spec);
4286
4287 let body = json!({"extra": "data"});
4289 let result = registry.validate_request_with_all(
4290 "/users",
4291 "GET",
4292 &Map::new(),
4293 &Map::new(),
4294 &Map::new(),
4295 &Map::new(),
4296 Some(&body),
4297 );
4298 assert!(result.is_ok());
4300 }
4301
4302 #[test]
4303 fn test_get_operation() {
4304 let spec_json = json!({
4306 "openapi": "3.0.0",
4307 "info": {"title": "Test API", "version": "1.0.0"},
4308 "paths": {
4309 "/users": {
4310 "get": {
4311 "operationId": "getUsers",
4312 "summary": "Get users",
4313 "responses": {"200": {"description": "OK"}}
4314 }
4315 }
4316 }
4317 });
4318 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4319 let registry = OpenApiRouteRegistry::new(spec);
4320
4321 let operation = registry.get_operation("/users", "GET");
4323 assert!(operation.is_some());
4324 assert_eq!(operation.unwrap().method, "GET");
4325
4326 assert!(registry.get_operation("/nonexistent", "GET").is_none());
4328 }
4329
4330 #[test]
4331 fn test_extract_path_parameters() {
4332 let spec_json = json!({
4334 "openapi": "3.0.0",
4335 "info": {"title": "Test API", "version": "1.0.0"},
4336 "paths": {
4337 "/users/{id}": {
4338 "get": {
4339 "parameters": [
4340 {
4341 "name": "id",
4342 "in": "path",
4343 "required": true,
4344 "schema": {"type": "string"}
4345 }
4346 ],
4347 "responses": {"200": {"description": "OK"}}
4348 }
4349 }
4350 }
4351 });
4352 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4353 let registry = OpenApiRouteRegistry::new(spec);
4354
4355 let params = registry.extract_path_parameters("/users/123", "GET");
4357 assert_eq!(params.get("id"), Some(&"123".to_string()));
4358
4359 let empty_params = registry.extract_path_parameters("/users", "GET");
4361 assert!(empty_params.is_empty());
4362 }
4363
4364 #[test]
4365 fn extract_path_parameters_prefers_static_route_and_rejects_empty() {
4366 let spec_json = json!({
4369 "openapi": "3.0.0",
4370 "info": {"title": "Test API", "version": "1.0.0"},
4371 "paths": {
4372 "/users/{id}": { "get": { "responses": {"200": {"description": "OK"}} } },
4373 "/users/me": { "get": { "responses": {"200": {"description": "OK"}} } }
4374 }
4375 });
4376 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4377 let registry = OpenApiRouteRegistry::new(spec);
4378
4379 let me = registry.extract_path_parameters("/users/me", "GET");
4381 assert!(!me.contains_key("id"), "literal route should win, got {me:?}");
4382
4383 let by_id = registry.extract_path_parameters("/users/123", "GET");
4385 assert_eq!(by_id.get("id"), Some(&"123".to_string()));
4386
4387 let trailing = registry.extract_path_parameters("/users/", "GET");
4389 assert!(
4390 trailing.is_empty(),
4391 "empty trailing segment should not bind id, got {trailing:?}"
4392 );
4393 }
4394
4395 #[test]
4396 fn test_extract_path_parameters_multiple_params() {
4397 let spec_json = json!({
4399 "openapi": "3.0.0",
4400 "info": {"title": "Test API", "version": "1.0.0"},
4401 "paths": {
4402 "/users/{userId}/posts/{postId}": {
4403 "get": {
4404 "parameters": [
4405 {
4406 "name": "userId",
4407 "in": "path",
4408 "required": true,
4409 "schema": {"type": "string"}
4410 },
4411 {
4412 "name": "postId",
4413 "in": "path",
4414 "required": true,
4415 "schema": {"type": "string"}
4416 }
4417 ],
4418 "responses": {"200": {"description": "OK"}}
4419 }
4420 }
4421 }
4422 });
4423 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4424 let registry = OpenApiRouteRegistry::new(spec);
4425
4426 let params = registry.extract_path_parameters("/users/123/posts/456", "GET");
4428 assert_eq!(params.get("userId"), Some(&"123".to_string()));
4429 assert_eq!(params.get("postId"), Some(&"456".to_string()));
4430 }
4431
4432 #[test]
4433 fn test_validate_request_route_not_found() {
4434 let spec_json = json!({
4436 "openapi": "3.0.0",
4437 "info": {"title": "Test API", "version": "1.0.0"},
4438 "paths": {
4439 "/users": {
4440 "get": {
4441 "responses": {"200": {"description": "OK"}}
4442 }
4443 }
4444 }
4445 });
4446 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4447 let registry = OpenApiRouteRegistry::new(spec);
4448
4449 let result = registry.validate_request_with_all(
4451 "/nonexistent",
4452 "GET",
4453 &Map::new(),
4454 &Map::new(),
4455 &Map::new(),
4456 &Map::new(),
4457 None,
4458 );
4459 assert!(result.is_err());
4460 assert!(result.unwrap_err().to_string().contains("not found"));
4461 }
4462
4463 #[test]
4464 fn test_validate_request_with_path_parameters() {
4465 let spec_json = json!({
4467 "openapi": "3.0.0",
4468 "info": {"title": "Test API", "version": "1.0.0"},
4469 "paths": {
4470 "/users/{id}": {
4471 "get": {
4472 "parameters": [
4473 {
4474 "name": "id",
4475 "in": "path",
4476 "required": true,
4477 "schema": {"type": "string", "minLength": 1}
4478 }
4479 ],
4480 "responses": {"200": {"description": "OK"}}
4481 }
4482 }
4483 }
4484 });
4485 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4486 let registry = OpenApiRouteRegistry::new(spec);
4487
4488 let mut path_params = Map::new();
4490 path_params.insert("id".to_string(), json!("123"));
4491 let result = registry.validate_request_with_all(
4492 "/users/{id}",
4493 "GET",
4494 &path_params,
4495 &Map::new(),
4496 &Map::new(),
4497 &Map::new(),
4498 None,
4499 );
4500 assert!(result.is_ok());
4501 }
4502
4503 #[test]
4504 fn test_validate_request_with_query_parameters() {
4505 let spec_json = json!({
4507 "openapi": "3.0.0",
4508 "info": {"title": "Test API", "version": "1.0.0"},
4509 "paths": {
4510 "/users": {
4511 "get": {
4512 "parameters": [
4513 {
4514 "name": "page",
4515 "in": "query",
4516 "required": true,
4517 "schema": {"type": "integer", "minimum": 1}
4518 }
4519 ],
4520 "responses": {"200": {"description": "OK"}}
4521 }
4522 }
4523 }
4524 });
4525 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4526 let registry = OpenApiRouteRegistry::new(spec);
4527
4528 let mut query_params = Map::new();
4530 query_params.insert("page".to_string(), json!(1));
4531 let result = registry.validate_request_with_all(
4532 "/users",
4533 "GET",
4534 &Map::new(),
4535 &query_params,
4536 &Map::new(),
4537 &Map::new(),
4538 None,
4539 );
4540 assert!(result.is_ok());
4541 }
4542
4543 #[test]
4544 fn test_validate_request_with_header_parameters() {
4545 let spec_json = json!({
4547 "openapi": "3.0.0",
4548 "info": {"title": "Test API", "version": "1.0.0"},
4549 "paths": {
4550 "/users": {
4551 "get": {
4552 "parameters": [
4553 {
4554 "name": "X-API-Key",
4555 "in": "header",
4556 "required": true,
4557 "schema": {"type": "string"}
4558 }
4559 ],
4560 "responses": {"200": {"description": "OK"}}
4561 }
4562 }
4563 }
4564 });
4565 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4566 let registry = OpenApiRouteRegistry::new(spec);
4567
4568 let mut header_params = Map::new();
4570 header_params.insert("X-API-Key".to_string(), json!("secret-key"));
4571 let result = registry.validate_request_with_all(
4572 "/users",
4573 "GET",
4574 &Map::new(),
4575 &Map::new(),
4576 &header_params,
4577 &Map::new(),
4578 None,
4579 );
4580 assert!(result.is_ok());
4581 }
4582
4583 #[test]
4584 fn test_validate_request_with_cookie_parameters() {
4585 let spec_json = json!({
4587 "openapi": "3.0.0",
4588 "info": {"title": "Test API", "version": "1.0.0"},
4589 "paths": {
4590 "/users": {
4591 "get": {
4592 "parameters": [
4593 {
4594 "name": "sessionId",
4595 "in": "cookie",
4596 "required": true,
4597 "schema": {"type": "string"}
4598 }
4599 ],
4600 "responses": {"200": {"description": "OK"}}
4601 }
4602 }
4603 }
4604 });
4605 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4606 let registry = OpenApiRouteRegistry::new(spec);
4607
4608 let mut cookie_params = Map::new();
4610 cookie_params.insert("sessionId".to_string(), json!("abc123"));
4611 let result = registry.validate_request_with_all(
4612 "/users",
4613 "GET",
4614 &Map::new(),
4615 &Map::new(),
4616 &Map::new(),
4617 &cookie_params,
4618 None,
4619 );
4620 assert!(result.is_ok());
4621 }
4622
4623 #[test]
4624 fn test_validate_request_no_errors_early_return() {
4625 let spec_json = json!({
4627 "openapi": "3.0.0",
4628 "info": {"title": "Test API", "version": "1.0.0"},
4629 "paths": {
4630 "/users": {
4631 "get": {
4632 "responses": {"200": {"description": "OK"}}
4633 }
4634 }
4635 }
4636 });
4637 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4638 let registry = OpenApiRouteRegistry::new(spec);
4639
4640 let result = registry.validate_request_with_all(
4642 "/users",
4643 "GET",
4644 &Map::new(),
4645 &Map::new(),
4646 &Map::new(),
4647 &Map::new(),
4648 None,
4649 );
4650 assert!(result.is_ok());
4651 }
4652
4653 #[test]
4654 fn test_validate_request_query_parameter_different_styles() {
4655 let spec_json = json!({
4657 "openapi": "3.0.0",
4658 "info": {"title": "Test API", "version": "1.0.0"},
4659 "paths": {
4660 "/users": {
4661 "get": {
4662 "parameters": [
4663 {
4664 "name": "tags",
4665 "in": "query",
4666 "style": "pipeDelimited",
4667 "schema": {
4668 "type": "array",
4669 "items": {"type": "string"}
4670 }
4671 }
4672 ],
4673 "responses": {"200": {"description": "OK"}}
4674 }
4675 }
4676 }
4677 });
4678 let spec = OpenApiSpec::from_json(spec_json).unwrap();
4679 let registry = OpenApiRouteRegistry::new(spec);
4680
4681 let mut query_params = Map::new();
4683 query_params.insert("tags".to_string(), json!(["tag1", "tag2"]));
4684 let result = registry.validate_request_with_all(
4685 "/users",
4686 "GET",
4687 &Map::new(),
4688 &query_params,
4689 &Map::new(),
4690 &Map::new(),
4691 None,
4692 );
4693 assert!(result.is_ok() || result.is_err()); }
4696}